@lucideproxy/svg 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @lucideproxy/svg might be problematic. Click here for more details.
- package/3xhqia.js +10 -0
- package/5ypec/3k2dyx.js +2 -0
- package/5ypec/qzatah.js +41 -0
- package/5ypec/zdmrcu.js +2 -0
- package/7cpa7/m20fhz.js +31 -0
- package/7cpa7/vpa1gg.wasm +0 -0
- package/assets/AccountPage-DgzsV3p_-eac502ad.js +1 -0
- package/assets/AccountPage-fg4fizGa-eac502ad.css +1 -0
- package/assets/AiPage-BYyoMN5L-eac502ad.css +1 -0
- package/assets/AiPage-C7vje5zO-eac502ad.js +1 -0
- package/assets/ChatPage-CgwrQNaj-eac502ad.js +1 -0
- package/assets/ChatPage-Hgs1zZvt-eac502ad.css +1 -0
- package/assets/DarkVeil-B3ov-j6T-eac502ad.js +1 -0
- package/assets/GamesPage-Btpg86D--eac502ad.css +1 -0
- package/assets/GamesPage-Cv8v7l5_-eac502ad.js +1 -0
- package/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/assets/SettingsModal-DLrzJ2lM-eac502ad.css +1 -0
- package/assets/SettingsPage-DKaqVxDa-eac502ad.js +1 -0
- package/assets/boot-DURONIBP-eac502ad.js +1 -0
- package/assets/emoji-BAJ2KL4a-eac502ad.js +3 -0
- package/assets/fingerprint-BEH1UDAC-eac502ad.js +1 -0
- package/assets/fingerprint-Y5nV5FVa-eac502ad.js +4 -0
- package/assets/index-C2iBobdE-eac502ad.css +1 -0
- package/assets/index-_E4fBqHJ-eac502ad.js +1 -0
- package/assets/livekit-DqpdvE-G-eac502ad.js +39 -0
- package/assets/markdown-dIRGbAJA-eac502ad.css +1 -0
- package/assets/markdown-rngvaYIh-eac502ad.js +291 -0
- package/assets/motion-ClYBgd9J-eac502ad.js +9 -0
- package/assets/ogl-BWe_HKY6-eac502ad.js +1 -0
- package/assets/proxy-runtime-1NyFshf9-eac502ad.js +13 -0
- package/assets/react-CKawGOZZ-eac502ad.js +49 -0
- package/branding/lucide.png +0 -0
- package/favicon.svg +8 -0
- package/index.html +26 -0
- package/index.svg +33 -0
- package/logo.svg +33 -0
- package/package.json +17 -0
- package/privacy.html +118 -0
- package/terms.html +97 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
var ks={};function cd(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var dd=Object.defineProperty,ld=(n,e,t)=>e in n?dd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ts=(n,e,t)=>ld(n,typeof e!="symbol"?e+"":e,t);class ue{constructor(){Ts(this,"_locking"),Ts(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function ie(n,e){if(!n)throw new Error(e)}const ud=34028234663852886e22,hd=-34028234663852886e22,pd=4294967295,md=2147483647,fd=-2147483648;function xi(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>md||n<fd)throw new Error("invalid int 32: "+n)}function lr(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>pd||n<0)throw new Error("invalid uint 32: "+n)}function Va(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>ud||n<hd))throw new Error("invalid float 32: "+n)}const ja=Symbol("@bufbuild/protobuf/enum-type");function gd(n){const e=n[ja];return ie(e,"missing enum type on enum object"),e}function Wa(n,e,t,i){n[ja]=Ha(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Ha(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=Ka(a);s.push(o),i[a.name]=o,r[a.no]=o}return{typeName:n,values:s,findName(a){return i[a]},findNumber(a){return r[a]}}}function vd(n,e,t){const i={};for(const r of e){const s=Ka(r);i[s.localName]=s.no,i[s.no]=s.localName}return Wa(i,n,e),i}function Ka(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class qr{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function bd(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new qr),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,d){return new a().fromBinary(o,d)},fromJson(o,d){return new a().fromJson(o,d)},fromJsonString(o,d){return new a().fromJsonString(o,d)},equals(o,d){return n.util.equals(a,o,d)}}),a}function yd(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function jn(n,e,t){for(let s=0;s<28;s=s+7){const a=n>>>s,o=!(!(a>>>7)&&e==0),d=(o?a|128:a)&255;if(t.push(d),!o)return}const i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),d=(o?a|128:a)&255;if(t.push(d),!o)return}t.push(e>>>31&1)}}const Ui=4294967296;function Ss(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(a,o){const d=Number(n.slice(a,o));r*=t,i=i*t+d,i>=Ui&&(r=r+(i/Ui|0),i=i%Ui)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?za(i,r):Vr(i,r)}function kd(n,e){let t=Vr(n,e);const i=t.hi&2147483648;i&&(t=za(t.lo,t.hi));const r=Ga(t.lo,t.hi);return i?"-"+r:r}function Ga(n,e){var t=Td(n,e);if(n=t.lo,e=t.hi,e<=2097151)return String(Ui*e+n);const i=n&16777215,r=(n>>>24|e<<8)&16777215,s=e>>16&65535;let a=i+r*6777216+s*6710656,o=r+s*8147497,d=s*2;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(d+=Math.floor(o/c),o%=c),d.toString()+Cs(o)+Cs(a)}function Td(n,e){return{lo:n>>>0,hi:e>>>0}}function Vr(n,e){return{lo:n|0,hi:e|0}}function za(n,e){return e=~e,n?n=~n+1:e+=1,Vr(n,e)}const Cs=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Es(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Sd(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Cd(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof ks!="object"||ks.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>s||c<r)throw new Error("int64 invalid: ".concat(d));return c},uParse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>o||c<a)throw new Error("uint64 invalid: ".concat(d));return c},enc(d){return n.setBigInt64(0,this.parse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(d){return n.setBigInt64(0,this.uParse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(d,c){return n.setInt32(0,d,!0),n.setInt32(4,c,!0),n.getBigInt64(0,!0)},uDec(d,c){return n.setInt32(0,d,!0),n.setInt32(4,c,!0),n.getBigUint64(0,!0)}}}const t=r=>ie(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>ie(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Ss(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),Ss(r)},dec(r,s){return kd(r,s)},uDec(r,s){return Ga(r,s)}}}const $=Cd();var E;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(E||(E={}));var bt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(bt||(bt={}));function dt(n,e,t){if(e===t)return!0;if(n==E.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==t}return!1}function zt(n,e){switch(n){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?$.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function Ja(n,e){switch(n){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function _s(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,i=Array(e);t<e;t++)i[t]=n[t];return i}function Ed(n){if(Array.isArray(n))return n}function j(n,e,t){return(e=Rd(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function _d(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var i,r,s,a,o=[],d=!0,c=!1;try{if(s=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(i=s.call(t)).done)&&(o.push(i.value),o.length!==e);d=!0);}catch(l){c=!0,r=l}finally{try{if(!d&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(c)throw r}}return o}}function Pd(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N(n,e){return Ed(n)||_d(n,e)||Id(n,e)||Pd()}function wd(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Rd(n){var e=wd(n,"string");return typeof e=="symbol"?e:e+""}function Id(n,e){if(n){if(typeof n=="string")return _s(n,e);var t={}.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_s(n,e):void 0}}var re;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(re||(re={}));class Md{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(lr(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return xi(e),Es(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){Va(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){lr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){xi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return xi(e),e=(e<<1^e>>31)>>>0,Es(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=$.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=$.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=$.enc(e);return jn(t.lo,t.hi,this.buf),this}sint64(e){let t=$.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return jn(r,s,this.buf),this}uint64(e){let t=$.uEnc(e);return jn(t.lo,t.hi,this.buf),this}}class Dd{constructor(e,t){this.varint64=yd,this.uint32=Sd,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case re.Varint:for(;this.buf[this.pos++]&128;);break;case re.Bit64:this.pos+=4;case re.Bit32:this.pos+=4;break;case re.LengthDelimited:let r=this.uint32();this.pos+=r;break;case re.StartGroup:for(;;){const s=this.tag(),a=N(s,2),o=a[0],d=a[1];if(d===re.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(d,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return $.dec(...this.varint64())}uint64(){return $.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=N(e,2),i=t[0],r=t[1],s=-(i&1);return i=(i>>>1|(r&1)<<31)^s,r=r>>>1^s,$.dec(i,r)}bool(){let e=this.varint64(),t=N(e,2),i=t[0],r=t[1];return i!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return $.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return $.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Od(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function Qa(n){const e=n.field.localName,t=Object.create(null);return t[e]=Ad(n),[t,()=>t[e]]}function Ad(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return zt(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Nd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),pn=[];for(let n=0;n<st.length;n++)pn[st[n].charCodeAt(0)]=n;pn[45]=st.indexOf("+");pn[95]=st.indexOf("/");const Ya={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,a=0;for(let o=0;o<n.length;o++){if(s=pn[n.charCodeAt(o)],s===void 0)switch(n[o]){case"=":r=0;case`
|
|
3
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:t[i++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[i++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[i++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s<n.length;s++)switch(i=n[s],t){case 0:e+=st[i>>2],r=(i&3)<<4,t=1;break;case 1:e+=st[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=st[r|i>>6],e+=st[i&63],t=0;break}return t&&(e+=st[r],e+="=",t==1&&(e+="=")),e}};function Ld(n,e,t){Xa(e,n);const i=e.runtime.bin.makeReadOptions(t),r=Nd(n.getType().runtime.bin.listUnknownFields(n),e.field),s=Qa(e),a=N(s,2),o=a[0],d=a[1];for(const c of r)e.runtime.bin.readField(o,i.readerFactory(c.data),e.field,c.wireType,i);return d()}function xd(n,e,t,i){Xa(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if($a(n,e)){const c=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of c)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,s);const d=r.readerFactory(a.finish());for(;d.pos<d.len;){const c=d.tag(),l=N(c,2),u=l[0],h=l[1],p=d.skip(h,u);n.getType().runtime.bin.onUnknownField(n,u,h,p)}}function $a(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function Xa(n,e){ie(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Za(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Ja(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Ps(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?zt(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function at(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(qr.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function eo(n,e){return at(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const ws={ignoreUnknownFields:!1},Rs={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ud(n){return n?Object.assign(Object.assign({},ws),n):ws}function Fd(n){return n?Object.assign(Object.assign({},Rs),n):Rs}const Yi=Symbol(),Fi=Symbol();function Bd(){return{makeReadOptions:Ud,makeWriteOptions:Fd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Ye(e)));i=i??new n;const r=new Map,s=t.typeRegistry;for(const o of Object.entries(e)){var a=N(o,2);const d=a[0],c=a[1],l=n.fields.findJsonName(d);if(l){if(l.oneof){if(c===null&&l.kind=="scalar")continue;const u=r.get(l.oneof);if(u!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(u,'", "').concat(d,'"'));r.set(l.oneof,d)}Is(i,c,l,t,n)}else{let u=!1;if(s!=null&&s.findExtension&&d.startsWith("[")&&d.endsWith("]")){const h=s.findExtension(d.substring(1,d.length-1));if(h&&h.extendee.typeName==n.typeName){u=!0;const p=Qa(h),v=N(p,2),g=v[0],T=v[1];Is(g,c,h.field,t,h),xd(i,h,T(),t)}}if(!u&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!Za(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Vd(r))continue}const a=r.oneof?n[r.oneof.localName].value:n[r.localName],o=Ms(r,a,e);o!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=s.findExtensionFor(t.typeName,a.no);if(o&&$a(n,o)){const d=Ld(n,o,e),c=Ms(o.field,d,e);c!==void 0&&(i[o.field.jsonName]=c)}}}catch(s){const a=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return ci(n,e,t??bt.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Ja(n,e)))return Bi(n,e)},debug:Ye}}function Ye(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Is(n,e,t,i,r){let s=t.localName;if(t.repeated){if(ie(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e)));const o=n[s];for(const d of e){if(d===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(d)));switch(t.kind){case"message":o.push(t.T.fromJson(d,i));break;case"enum":const c=Wn(t.T,d,i.ignoreUnknownFields,!0);c!==Fi&&o.push(c);break;case"scalar":try{o.push(ci(t.T,d,t.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(d));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e)));const o=n[s];for(const d of Object.entries(e)){var a=N(d,2);const c=a[0],l=a[1];if(l===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let u;try{u=qd(t.K,c)}catch(h){let p="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw h instanceof Error&&h.message.length>0&&(p+=": ".concat(h.message)),new Error(p)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,i);break;case"enum":const h=Wn(t.V.T,l,i.ignoreUnknownFields,!0);h!==Fi&&(o[u]=h);break;case"scalar":try{o[u]=ci(t.V.T,l,bt.BIGINT,!0)}catch(p){let v="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw p instanceof Error&&p.message.length>0&&(v+=": ".concat(p.message)),new Error(v)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let d=n[s];at(d)?d.fromJson(e,i):(n[s]=d=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[s]=o.fieldWrapper.unwrapField(d)));break;case"enum":const c=Wn(t.T,e,i.ignoreUnknownFields,!1);switch(c){case Yi:Ps(t,n);break;case Fi:break;default:n[s]=c;break}break;case"scalar":try{const l=ci(t.T,e,t.L,!1);switch(l){case Yi:Ps(t,n);break;default:n[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function qd(n,e){if(n===E.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return ci(n,e,bt.BIGINT,!0).toString()}function ci(n,e,t,i){if(e===null)return i?zt(n,t):Yi;switch(n){case E.DOUBLE:case E.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==E.FLOAT&&Va(r),r;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==E.UINT32||n==E.FIXED32?lr(s):xi(s),s;case E.INT64:case E.SFIXED64:case E.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=$.parse(e);return t?a.toString():a;case E.FIXED64:case E.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=$.uParse(e);return t?o.toString():o;case E.BOOL:if(typeof e!="boolean")break;return e;case E.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case E.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ya.dec(e)}throw new Error}function Wn(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Yi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return Fi;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Ye(e)))}function Vd(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function Ms(n,e,t){if(n.kind=="map"){ie(typeof e=="object"&&e!=null);const a={},o=Object.entries(e);switch(n.V.kind){case"scalar":for(const c of o){var i=N(c,2);const l=i[0],u=i[1];a[l.toString()]=Bi(n.V.T,u)}break;case"message":for(const c of o){var r=N(c,2);const l=r[0],u=r[1];a[l.toString()]=u.toJson(t)}break;case"enum":const d=n.V.T;for(const c of o){var s=N(c,2);const l=s[0],u=s[1];a[l.toString()]=Hn(d,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(n.repeated){ie(Array.isArray(e));const a=[];switch(n.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(Bi(n.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(Hn(n.T,e[o],t.enumAsInteger));break;case"message":for(let o=0;o<e.length;o++)a.push(e[o].toJson(t));break}return t.emitDefaultValues||a.length>0?a:void 0}switch(n.kind){case"scalar":return Bi(n.T,e);case"enum":return Hn(n.T,e,t.enumAsInteger);case"message":return eo(n.T,e).toJson(t)}}function Hn(n,e,t){var i;if(ie(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function Bi(n,e){switch(n){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return ie(typeof e=="number"),e;case E.FLOAT:case E.DOUBLE:return ie(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case E.STRING:return ie(typeof e=="string"),e;case E.BOOL:return ie(typeof e=="boolean"),e;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return ie(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case E.BYTES:return ie(e instanceof Uint8Array),Ya.enc(e)}}const xt=Symbol("@bufbuild/protobuf/unknown-fields"),Ds={readUnknownFields:!0,readerFactory:n=>new Dd(n)},Os={writeUnknownFields:!0,writerFactory:()=>new Md};function jd(n){return n?Object.assign(Object.assign({},Ds),n):Ds}function Wd(n){return n?Object.assign(Object.assign({},Os),n):Os}function Hd(){return{makeReadOptions:jd,makeWriteOptions:Wd,listUnknownFields(n){var e;return(e=n[xt])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[xt]},writeUnknownFields(n,e){const i=n[xt];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[xt])||(r[xt]=[]),r[xt].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),a=r?e.len:e.pos+t;let o,d;for(;e.pos<a;){var c=e.tag(),l=N(c,2);if(o=l[0],d=l[1],r===!0&&d==re.EndGroup)break;const u=s.fields.find(o);if(!u){const h=e.skip(d,o);i.readUnknownFields&&this.onUnknownField(n,o,d,h);continue}As(n,e,u,d,i)}if(r&&(d!=re.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:As,writeMessage(n,e,t){const i=n.getType();for(const r of i.fields.byNumber()){if(!Za(r,n)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?n[r.oneof.localName].value:n[r.localName];Ns(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Ns(n,e,t,i)}}}function As(n,e,t,i,r){let s=t.repeated,a=t.localName;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?E.INT32:t.T;let d=$i;if(t.kind=="scalar"&&t.L>0&&(d=Gd),s){let v=n[a];if(i==re.LengthDelimited&&o!=E.STRING&&o!=E.BYTES){let T=e.uint32()+e.pos;for(;e.pos<T;)v.push(d(e,o))}else v.push(d(e,o))}else n[a]=d(e,o);break;case"message":const c=t.T;s?n[a].push(qi(e,new c,r,t)):at(n[a])?qi(e,n[a],r,t):(n[a]=qi(e,new c,r,t),c.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=c.fieldWrapper.unwrapField(n[a])));break;case"map":let l=Kd(t,e,r),u=N(l,2),h=u[0],p=u[1];n[a][h]=p;break}}function qi(n,e,t,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,n,s?i.no:n.uint32(),t,s),e}function Kd(n,e,t){const i=e.uint32(),r=e.pos+i;let s,a;for(;e.pos<r;){const o=e.tag();switch(N(o,1)[0]){case 1:s=$i(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=$i(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=qi(e,new n.V.T,t,void 0);break}break}}if(s===void 0&&(s=zt(n.K,bt.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(n.V.kind){case"scalar":a=zt(n.V.T,bt.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[s,a]}function Gd(n,e){const t=$i(n,e);return typeof t=="bigint"?t.toString():t}function $i(n,e){switch(e){case E.STRING:return n.string();case E.BOOL:return n.bool();case E.DOUBLE:return n.double();case E.FLOAT:return n.float();case E.INT32:return n.int32();case E.INT64:return n.int64();case E.UINT64:return n.uint64();case E.FIXED64:return n.fixed64();case E.BYTES:return n.bytes();case E.FIXED32:return n.fixed32();case E.SFIXED32:return n.sfixed32();case E.SFIXED64:return n.sfixed64();case E.SINT64:return n.sint64();case E.UINT32:return n.uint32();case E.SINT32:return n.sint32()}}function Ns(n,e,t,i){ie(e!==void 0);const r=n.repeated;switch(n.kind){case"scalar":case"enum":let a=n.kind=="enum"?E.INT32:n.T;if(r)if(ie(Array.isArray(e)),n.packed)Jd(t,a,n.no,e);else for(const o of e)di(t,a,n.no,o);else di(t,a,n.no,e);break;case"message":if(r){ie(Array.isArray(e));for(const o of e)Ls(t,i,n,o)}else Ls(t,i,n,e);break;case"map":ie(typeof e=="object"&&e!=null);for(const o of Object.entries(e)){var s=N(o,2);const d=s[0],c=s[1];zd(t,i,n,d,c)}break}}function zd(n,e,t,i,r){n.tag(t.no,re.LengthDelimited),n.fork();let s=i;switch(t.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:s=Number.parseInt(i);break;case E.BOOL:ie(i=="true"||i=="false"),s=i=="true";break}switch(di(n,t.K,1,s),t.V.kind){case"scalar":di(n,t.V.T,2,r);break;case"enum":di(n,E.INT32,2,r);break;case"message":ie(r!==void 0),n.tag(2,re.LengthDelimited).bytes(r.toBinary(e));break}n.join()}function Ls(n,e,t,i){const r=eo(t.T,i);t.delimited?n.tag(t.no,re.StartGroup).raw(r.toBinary(e)).tag(t.no,re.EndGroup):n.tag(t.no,re.LengthDelimited).bytes(r.toBinary(e))}function di(n,e,t,i){ie(i!==void 0);let r=to(e),s=N(r,2),a=s[0],o=s[1];n.tag(t,a)[o](i)}function Jd(n,e,t,i){if(!i.length)return;n.tag(t,re.LengthDelimited).fork();let r=to(e),s=N(r,2),a=s[1];for(let o=0;o<i.length;o++)n[a](i[o]);n.join()}function to(n){let e=re.Varint;switch(n){case E.BYTES:case E.STRING:e=re.LengthDelimited;break;case E.DOUBLE:case E.FIXED64:case E.SFIXED64:e=re.Bit64;break;case E.FIXED32:case E.SFIXED32:case E.FLOAT:e=re.Bit32;break}const t=E[n].toLowerCase();return[e,t]}function Qd(){return{setEnumType:Wa,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const r of t.fields.byMember()){const s=r.localName,a=e,o=n;if(o[s]!=null)switch(r.kind){case"oneof":const d=o[s].case;if(d===void 0)continue;const c=r.findField(d);let l=o[s].value;c&&c.kind=="message"&&!at(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===E.BYTES&&(l=ei(l)),a[s]={case:d,value:l};break;case"scalar":case"enum":let u=o[s];r.T===E.BYTES&&(u=r.repeated?u.map(ei):ei(u)),a[s]=u;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===E.BYTES)for(const v of Object.entries(o[s])){var i=N(v,2);const g=i[0],T=i[1];a[s][g]=ei(T)}else Object.assign(a[s],o[s]);break;case"message":const p=r.V.T;for(const v of Object.keys(o[s])){let g=o[s][v];p.fieldWrapper||(g=new p(g)),a[s][v]=g}break}break;case"message":const h=r.T;if(r.repeated)a[s]=o[s].map(p=>at(p,h)?p:new h(p));else{const p=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[s]=ei(p):a[s]=p:a[s]=at(p,h)?p:new h(p)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((a,o)=>i.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>dt(i.T,a,s[o]));case"enum":return r.every((a,o)=>dt(E.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=r,o=s;return i.T.fieldWrapper&&(a!==void 0&&!at(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!at(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return dt(E.INT32,r,s);case"scalar":return dt(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const d=i.findField(r.case);if(d===void 0)return!0;switch(d.kind){case"message":return d.T.equals(r.value,s.value);case"enum":return dt(E.INT32,r.value,s.value);case"scalar":return dt(d.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":const c=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return c.every(h=>l.equals(r[h],s[h]));case"enum":return c.every(h=>dt(E.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return c.every(h=>dt(u,r[h],s[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const a=n[s.localName];let o;if(s.repeated)o=a.map(Oi);else if(s.kind=="map"){o=i[s.localName];for(const d of Object.entries(a)){var r=N(d,2);const c=r[0],l=r[1];o[c]=Oi(l)}}else s.kind=="oneof"?o=s.findField(a.case)?{case:a.case,value:Oi(a.value)}:{case:void 0}:o=Oi(a);i[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Oi(n){if(n===void 0)return n;if(at(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function ei(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Yd(n,e,t){return{syntax:n,json:Bd(),bin:Hd(),util:Object.assign(Object.assign({},Qd()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return bd(this,i,r,s)},makeEnum:vd,makeEnumType:Ha,getEnumType:gd,makeExtension(i,r,s){return Od(this,i,r,s)}}}class $d{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function io(n,e){const t=no(n);return e?t:nl(il(t))}function Xd(n){return io(n,!1)}const Zd=no;function no(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let r=n.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const el=new Set(["constructor","toString","toJSON","valueOf"]),tl=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ro=n=>"".concat(n,"$"),il=n=>tl.has(n)?ro(n):n,nl=n=>el.has(n)?ro(n):n;class rl{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=Xd(e)}addField(e){ie(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 t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function sl(n,e){var t,i,r,s,a,o;const d=[];let c;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=io(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Zd(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(r=l.L)!==null&&r!==void 0?r:bt.BIGINT),u.delimited=(s=l.delimited)!==null&&s!==void 0?s:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=E.BYTES&&l.T!=E.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=h)&&(c=new rl(h)),u.oneof=c,c.addField(u)}d.push(u)}return d}const f=Yd("proto3",n=>new $d(n,e=>sl(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=zt(e.T,e.L);break}}});class Ee extends qr{constructor(e){super(),this.seconds=$.zero,this.nanos=0,f.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(f.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=$.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Ee.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ee({seconds:$.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ee().fromBinary(e,t)}static fromJson(e,t){return new Ee().fromJson(e,t)}static fromJsonString(e,t){return new Ee().fromJsonString(e,t)}static equals(e,t){return f.util.equals(Ee,e,t)}}Ee.runtime=f;Ee.typeName="google.protobuf.Timestamp";Ee.fields=f.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const al=f.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ee},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:ol,repeated:!0},{no:5,name:"events",kind:"message",T:dl,repeated:!0}]),ol=f.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:cl,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),cl=f.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ee},{no:3,name:"value",kind:"scalar",T:2}]),dl=f.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:Ee},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ee,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ll=f.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),ul=f.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"}]),hl=f.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),so=f.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),xe=f.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),se=f.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"}]),jr=f.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ai=f.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),gi=f.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),je=f.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"}]),Tt=f.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"}]),pl=f.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ce=f.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"}]),Jt=f.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),mn=f.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:Xi,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:ko}]),Xi=f.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),ml=f.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:f.getEnumType(se),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}]),Ot=f.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:f.getEnumType(qt)},{no:4,name:"tracks",kind:"message",T:Ft,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:ml},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:f.getEnumType(vi)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:f.getEnumType(je)},{no:18,name:"kind_details",kind:"enum",T:f.getEnumType(fl),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:fn,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}]),qt=f.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),vi=f.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"}]),fl=f.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"}]),Q=f.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),gl=f.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:ft,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:f.getEnumType(ao)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Ft=f.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:f.getEnumType(xe)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:f.getEnumType(se)},{no:10,name:"layers",kind:"message",T:ft,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:gl,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:f.getEnumType(Q)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ko},{no:19,name:"audio_features",kind:"enum",T:f.getEnumType(ce),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:f.getEnumType(so)},{no:21,name:"packet_trailer_features",kind:"enum",T:f.getEnumType(Jt),repeated:!0}]),fn=f.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:f.getEnumType(Q)}]),vl=f.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),ft=f.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:f.getEnumType(jr)},{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}]),ao=f.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"}]),fe=f.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:f.getEnumType(gt)},{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:Wr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:bl,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:uo,oneof:"value"},{no:7,name:"transcription",kind:"message",T:yl,oneof:"value"},{no:8,name:"metrics",kind:"message",T:al,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Zi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Hr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:gn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Kr,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:en,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:tn,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:nn,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:oo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),gt=f.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),oo=f.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:f.getEnumType(Q)},{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}]),co=f.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Wr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Zi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Hr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:gn,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Kr,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:en,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:tn,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:nn,oneof:"value"}]),bl=f.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:lo,repeated:!0}]),lo=f.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}]),Wr=f.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}]),uo=f.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),yl=f.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:kl,repeated:!0}]),kl=f.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}]),Zi=f.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}]),Hr=f.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}]),gn=f.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Kr=f.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:ho,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),ho=f.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}]),po=f.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),mo=f.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:f.getEnumType(fo)},{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}]),fo=f.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),go=f.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:f.getEnumType(vo)},{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:f.getEnumType(bo),repeated:!0}]),vo=f.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"}]),bo=f.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),yo=f.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:xs},{no:2,name:"screen",kind:"message",T:xs},{no:3,name:"resume_connection",kind:"enum",T:f.getEnumType(gi)},{no:4,name:"disabled_codecs",kind:"message",T:Tl},{no:5,name:"force_relay",kind:"enum",T:f.getEnumType(gi)}]),xs=f.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:f.getEnumType(gi)}]),Tl=f.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Xi,repeated:!0},{no:2,name:"publish",kind:"message",T:Xi,repeated:!0}]),ko=f.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ur=f.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),To=f.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:f.getEnumType(ur)},{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"}),So=f.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),en=f.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:f.getEnumType(Q)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:To,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:So,oneof:"content_header"}],{localName:"DataStream_Header"}),tn=f.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"}),nn=f.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"}),Sl=f.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}]),Cl=f.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:Sl}]),El=f.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),_l=f.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),Vi=f.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:f.getEnumType(_l)},{no:4,name:"deployment",kind:"scalar",T:9}]),Co=f.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"}]),Pl=f.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),wl=f.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),Rl=f.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Il=f.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),Ml=f.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),Dl=f.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Eo=f.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:f.getEnumType(ll)},{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:f.getEnumType(ul)},{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}]),Us=f.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:f.getEnumType(wl)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),hr=f.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:f.getEnumType(Rl)},{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:f.getEnumType(Il)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:vn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:bn,oneof:"output"},{no:7,name:"azure",kind:"message",T:yn,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:kn,oneof:"output"}]),Ol=f.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:f.getEnumType(Ml)},{no:6,name:"image_codec",kind:"enum",T:f.getEnumType(hl)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:vn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:bn,oneof:"output"},{no:10,name:"azure",kind:"message",T:yn,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:kn,oneof:"output"}]),vn=f.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:_o}]),bn=f.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:_o}]),yn=f.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),kn=f.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}]),_o=f.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}]),Al=f.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:f.getEnumType(Co),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Eo,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:pr,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:hr,repeated:!0}]),Nl=f.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:vn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:bn,oneof:"output"},{no:4,name:"azure",kind:"message",T:yn,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:kn,oneof:"output"}]),Ll=f.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:f.getEnumType(Dl)},{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:pr,oneof:"output"},{no:7,name:"stream",kind:"message",T:Us,oneof:"output"},{no:10,name:"segments",kind:"message",T:hr,oneof:"output"},{no:8,name:"preset",kind:"enum",T:f.getEnumType(Co),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Eo,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:pr,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:Us,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:hr,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:Ol,repeated:!0},{no:16,name:"webhooks",kind:"message",T:Cl,repeated:!0}]),pr=f.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:f.getEnumType(Pl)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:vn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:bn,oneof:"output"},{no:5,name:"azure",kind:"message",T:yn,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:kn,oneof:"output"}]),xl=f.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:Ll},{no:3,name:"participant",kind:"message",T:Al},{no:2,name:"tracks",kind:"message",T:Nl}]),li=f.makeMessageType("livekit.RoomConfiguration",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:xl},{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:Vi,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Ue=f.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),mr=f.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Ul=f.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Fl=f.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:yt,oneof:"message"},{no:2,name:"answer",kind:"message",T:yt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Tn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:bi,oneof:"message"},{no:5,name:"mute",kind:"message",T:Sn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ro,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Mo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ao,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Zr,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qe,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:$r,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:xo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Yr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Io,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Gr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Jr,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Po,oneof:"message"}]),Fs=f.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:jl,oneof:"message"},{no:2,name:"answer",kind:"message",T:yt,oneof:"message"},{no:3,name:"offer",kind:"message",T:yt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Tn,oneof:"message"},{no:5,name:"update",kind:"message",T:Kl,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Qr,oneof:"message"},{no:8,name:"leave",kind:"message",T:En,oneof:"message"},{no:9,name:"mute",kind:"message",T:Sn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Gl,oneof:"message"},{no:11,name:"room_update",kind:"message",T:zl,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Ql,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:$l,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Zl,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:tu,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Hl,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Wl,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:nu,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:au,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ou,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:cu,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:iu,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:uu,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:eu,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:zr,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Bl,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:ql,oneof:"message"}]),fr=f.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:ft,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:f.getEnumType(ao)}]),bi=f.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:f.getEnumType(xe)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:f.getEnumType(se)},{no:9,name:"layers",kind:"message",T:ft,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:fr,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:f.getEnumType(Q)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:f.getEnumType(so)},{no:17,name:"audio_features",kind:"enum",T:f.getEnumType(ce),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:f.getEnumType(Jt),repeated:!0}]),Gr=f.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:f.getEnumType(Q)}]),zr=f.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:fn}]),Jr=f.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Bl=f.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:fn}]),ql=f.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Vl}}]),Vl=f.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"}),Tn=f.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:f.getEnumType(Ue)},{no:3,name:"final",kind:"scalar",T:8}]),Sn=f.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),jl=f.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:mn},{no:2,name:"participant",kind:"message",T:Ot},{no:3,name:"other_participants",kind:"message",T:Ot,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Do,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:yo},{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:mo},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Xi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Wl=f.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Do,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:yo},{no:3,name:"server_info",kind:"message",T:mo},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Qr=f.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ft}]),Hl=f.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),yt=f.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}}]),Kl=f.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Ot,repeated:!0}]),Cn=f.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:po,repeated:!0}]),Po=f.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:wo,repeated:!0}]),wo=f.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:vl}],{localName:"UpdateDataSubscription_Update"}),Ro=f.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:f.getEnumType(jr)},{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}]),Yr=f.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:f.getEnumType(ce),repeated:!0}]),Io=f.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}]),En=f.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:f.getEnumType(je)},{no:3,name:"action",kind:"enum",T:f.getEnumType(Vt)},{no:4,name:"regions",kind:"message",T:ru}]),Vt=f.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Mo=f.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ft,repeated:!0}]),$r=f.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}]),Do=f.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}]),Gl=f.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:lo,repeated:!0}]),zl=f.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:mn}]),Jl=f.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:f.getEnumType(ai)},{no:3,name:"score",kind:"scalar",T:2}]),Ql=f.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Jl,repeated:!0}]),Yl=f.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:f.getEnumType(mr)}]),$l=f.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Yl,repeated:!0}]),Xr=f.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:f.getEnumType(jr)},{no:2,name:"enabled",kind:"scalar",T:8}]),Xl=f.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Xr,repeated:!0}]),Zl=f.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Xr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Xl,repeated:!0}]),eu=f.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:El,repeated:!0}]),Oo=f.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}]),Ao=f.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Oo,repeated:!0}]),tu=f.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}]),iu=f.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:mn},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Ot},{no:4,name:"other_participants",kind:"message",T:Ot,repeated:!0}]),Zr=f.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:yt},{no:2,name:"subscription",kind:"message",T:Cn},{no:3,name:"publish_tracks",kind:"message",T:Qr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Lo,repeated:!0},{no:5,name:"offer",kind:"message",T:yt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:No,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:zr,repeated:!0}]),No=f.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Lo=f.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:f.getEnumType(Ue)}]),Qe=f.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:f.getEnumType(Ul),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"}]),xo=f.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),nu=f.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ru=f.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:su,repeated:!0}]),su=f.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}]),au=f.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:f.getEnumType(pl)}]),ou=f.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:f.getEnumType(Ct)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Tn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:bi,oneof:"request"},{no:6,name:"mute",kind:"message",T:Sn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:$r,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Yr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Io,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Gr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Jr,oneof:"request"}]),Ct=f.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"}]),cu=f.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Uo=f.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}]),du=f.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:go},{no:2,name:"connection_settings",kind:"message",T:Uo},{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:bi,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:yt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:f.getEnumType(Tt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Zr}]),lu=f.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:f.getEnumType(gr)},{no:2,name:"join_request",kind:"scalar",T:12}]),gr=f.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),uu=f.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]),hu=f.makeMessageType("livekit.TokenSourceRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:li,opt:!0}]),Fo=f.makeMessageType("livekit.TokenSourceResponse",()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]);function pu(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ji={exports:{}},mu=ji.exports,Bs;function fu(){return Bs||(Bs=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(mu,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(g,T){var k=g[T];if(typeof k.bind=="function")return k.bind(g);try{return Function.prototype.bind.call(k,g)}catch{return function(){return Function.prototype.apply.apply(k,[g,arguments])}}}function d(){console.log&&(console.log.apply||Function.prototype.apply.apply(console.log,[console,arguments]))}function c(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&i?d:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function l(){for(var g=this.getLevel(),T=0;T<r.length;T++){var k=r[T];this[k]=T<g?e:this.methodFactory(k,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,T,k){return c(g)||u.apply(this,arguments)}function p(g,T){var k=this,S,x,b,y="loglevel";typeof g=="string"?y+=":"+g:typeof g=="symbol"&&(y=void 0);function _(O){var F=(r[O]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=F;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+F+";"}catch{}}}function M(){var O;if(!(typeof window===t||!y)){try{O=window.localStorage[y]}catch{}if(typeof O===t)try{var F=window.document.cookie,X=encodeURIComponent(y),Z=F.indexOf(X+"=");Z!==-1&&(O=/^([^;]+)/.exec(F.slice(Z+X.length+1))[1])}catch{}return k.levels[O]===void 0&&(O=void 0),O}}function A(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function q(O){var F=O;if(typeof F=="string"&&k.levels[F.toUpperCase()]!==void 0&&(F=k.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=k.levels.SILENT)return F;throw new TypeError("log.setLevel() called with invalid level: "+O)}k.name=g,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=T||h,k.getLevel=function(){return b??x??S},k.setLevel=function(O,F){return b=q(O),F!==!1&&_(b),l.call(k)},k.setDefaultLevel=function(O){x=q(O),M()||k.setLevel(O,!1)},k.resetLevel=function(){b=null,A(),l.call(k)},k.enableAll=function(O){k.setLevel(k.levels.TRACE,O)},k.disableAll=function(O){k.setLevel(k.levels.SILENT,O)},k.rebuild=function(){if(a!==k&&(S=q(a.getLevel())),l.call(k),a===k)for(var O in s)s[O].rebuild()},S=q(a?a.getLevel():"WARN");var D=M();D!=null&&(b=q(D)),l.call(k)}a=new p,a.getLogger=function(T){if(typeof T!="symbol"&&typeof T!="string"||T==="")throw new TypeError("You must supply a name when creating a logger.");var k=s[T];return k||(k=s[T]=new p(T,a.methodFactory)),k};var v=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=v),a},a.getLoggers=function(){return s},a.default=a,a})})(ji)),ji.exports}var Di=fu(),yi;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(yi||(yi={}));var he;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks"})(he||(he={}));let U=Di.getLogger(he.Default);const Bo=Object.values(he).map(n=>Di.getLogger(n));U.setDefaultLevel(yi.info);function Pe(n,e){const t=Di.getLogger(n);return t.setDefaultLevel(U.getLevel()),e?gu(t,e):t}function gu(n,e){const t=r=>(s,a)=>{const o=e(),d=o||a?Object.assign(Object.assign({},o),a):void 0;n[r](s,d)},i=Object.create(n);return i.trace=t("trace"),i.debug=t("debug"),i.info=t("info"),i.warn=t("warn"),i.error=t("error"),i}function Gm(n,e){if(e)Di.getLogger(e).setLevel(n);else for(const t of Bo)t.setLevel(n)}function zm(n,e){(e?[e]:Bo).forEach(i=>{const r=i.methodFactory;i.methodFactory=(s,a,o)=>{const d=r(s,a,o),c=yi[s],l=c>=a&&c<yi.silent;return(u,h)=>{h?d(u,h):d(u),l&&n(c,u,h)}},i.setLevel(i.getLevel())})}const vu=Di.getLogger(he.E2EE),ti=7e3,bu=[0,300,4*300,9*300,16*300,ti,ti,ti,ti,ti];class yu{constructor(e){this._retryDelays=e!==void 0?[...e]:bu}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function es(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function m(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{c(i.next(l))}catch(u){a(u)}}function d(l){try{c(i.throw(l))}catch(u){a(u)}}function c(l){l.done?s(l.value):r(l.value).then(o,d)}c((i=i.apply(n,e||[])).next())})}function qs(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qt(n){return this instanceof Qt?(this.v=n,this):new Qt(n)}function ku(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(p){return function(v){return Promise.resolve(v).then(p,u)}}function o(p,v){i[p]&&(r[p]=function(g){return new Promise(function(T,k){s.push([p,g,T,k])>1||d(p,g)})},v&&(r[p]=v(r[p])))}function d(p,v){try{c(i[p](v))}catch(g){h(s[0][3],g)}}function c(p){p.value instanceof Qt?Promise.resolve(p.value.v).then(l,u):h(s[0][2],p)}function l(p){d("next",p)}function u(p){d("throw",p)}function h(p,v){p(v),s.shift(),s.length&&d(s[0][0],s[0][1])}}function Tu(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(a){return(t=!t)?{value:Qt(n[r](a)),done:!1}:s?s(a):a}:s}}function Fe(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof qs=="function"?qs(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(a){return new Promise(function(o,d){a=n[s](a),r(o,d,a.done,a.value)})}}function r(s,a,o,d){Promise.resolve(d).then(function(c){s({value:c,done:o})},a)}}var Ai={exports:{}},Vs;function Su(){if(Vs)return Ai.exports;Vs=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,_,M){return Function.prototype.apply.call(y,_,M)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function i(b){}var r=Number.isNaN||function(y){return y!==y};function s(){s.init.call(this)}Ai.exports=s,Ai.exports.once=k,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function d(b){return b._maxListeners===void 0?s.defaultMaxListeners:b._maxListeners}s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(y){for(var _=[],M=1;M<arguments.length;M++)_.push(arguments[M]);var A=y==="error",q=this._events;if(q!==void 0)A=A&&q.error===void 0;else if(!A)return!1;if(A){var D;if(_.length>0&&(D=_[0]),D instanceof Error)throw D;var O=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw O.context=D,O}var F=q[y];if(F===void 0)return!1;if(typeof F=="function")e(F,this,_);else for(var X=F.length,Z=v(F,X),M=0;M<X;++M)e(Z[M],this,_);return!0};function c(b,y,_,M){var A,q,D;if(o(_),q=b._events,q===void 0?(q=b._events=Object.create(null),b._eventsCount=0):(q.newListener!==void 0&&(b.emit("newListener",y,_.listener?_.listener:_),q=b._events),D=q[y]),D===void 0)D=q[y]=_,++b._eventsCount;else if(typeof D=="function"?D=q[y]=M?[_,D]:[D,_]:M?D.unshift(_):D.push(_),A=d(b),A>0&&D.length>A&&!D.warned){D.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=b,O.type=y,O.count=D.length}return b}s.prototype.addListener=function(y,_){return c(this,y,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(y,_){return c(this,y,_,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(b,y,_){var M={fired:!1,wrapFn:void 0,target:b,type:y,listener:_},A=l.bind(M);return A.listener=_,M.wrapFn=A,A}s.prototype.once=function(y,_){return o(_),this.on(y,u(this,y,_)),this},s.prototype.prependOnceListener=function(y,_){return o(_),this.prependListener(y,u(this,y,_)),this},s.prototype.removeListener=function(y,_){var M,A,q,D,O;if(o(_),A=this._events,A===void 0)return this;if(M=A[y],M===void 0)return this;if(M===_||M.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete A[y],A.removeListener&&this.emit("removeListener",y,M.listener||_));else if(typeof M!="function"){for(q=-1,D=M.length-1;D>=0;D--)if(M[D]===_||M[D].listener===_){O=M[D].listener,q=D;break}if(q<0)return this;q===0?M.shift():g(M,q),M.length===1&&(A[y]=M[0]),A.removeListener!==void 0&&this.emit("removeListener",y,O||_)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(y){var _,M,A;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[y]),this;if(arguments.length===0){var q=Object.keys(M),D;for(A=0;A<q.length;++A)D=q[A],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=M[y],typeof _=="function")this.removeListener(y,_);else if(_!==void 0)for(A=_.length-1;A>=0;A--)this.removeListener(y,_[A]);return this};function h(b,y,_){var M=b._events;if(M===void 0)return[];var A=M[y];return A===void 0?[]:typeof A=="function"?_?[A.listener||A]:[A]:_?T(A):v(A,A.length)}s.prototype.listeners=function(y){return h(this,y,!0)},s.prototype.rawListeners=function(y){return h(this,y,!1)},s.listenerCount=function(b,y){return typeof b.listenerCount=="function"?b.listenerCount(y):p.call(b,y)},s.prototype.listenerCount=p;function p(b){var y=this._events;if(y!==void 0){var _=y[b];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function v(b,y){for(var _=new Array(y),M=0;M<y;++M)_[M]=b[M];return _}function g(b,y){for(;y+1<b.length;y++)b[y]=b[y+1];b.pop()}function T(b){for(var y=new Array(b.length),_=0;_<y.length;++_)y[_]=b[_].listener||b[_];return y}function k(b,y){return new Promise(function(_,M){function A(D){b.removeListener(y,q),M(D)}function q(){typeof b.removeListener=="function"&&b.removeListener("error",A),_([].slice.call(arguments))}x(b,y,q,{once:!0}),y!=="error"&&S(b,A,{once:!0})})}function S(b,y,_){typeof b.on=="function"&&x(b,"error",y,_)}function x(b,y,_,M){if(typeof b.on=="function")M.once?b.once(y,_):b.on(y,_);else if(typeof b.addEventListener=="function")b.addEventListener(y,function A(q){M.once&&b.removeEventListener(y,A),_(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Ai.exports}var we=Su();let qo=!0,Cu=!0;function oi(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function Lt(n,e,t){if(!n.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){return}const r=n.RTCPeerConnection.prototype,s=r.addEventListener;r.addEventListener=function(o,d){if(o!==e)return s.apply(this,arguments);const c=l=>{const u=t(l);u&&(d.handleEvent?d.handleEvent(u):d(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(d,c),s.apply(this,[o,c])};const a=r.removeEventListener;r.removeEventListener=function(o,d){if(o!==e||!this._eventMap||!this._eventMap[e])return a.apply(this,arguments);if(!this._eventMap[e].has(d))return a.apply(this,arguments);const c=this._eventMap[e].get(d);return this._eventMap[e].delete(d),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[o,c])},Object.defineProperty(r,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Eu(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(qo=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function _u(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Cu=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function Vo(){}function Pu(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const t=n.navigator;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(oi(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(oi(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(oi(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=oi(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function js(n){return Object.prototype.toString.call(n)==="[object Object]"}function jo(n){return js(n)?Object.keys(n).reduce(function(e,t){const i=js(n[t]),r=i?jo(n[t]):n[t],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):n}function vr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?vr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(r=>{vr(n,n.get(r),t)})}))}function Ws(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&vr(n,o,r)})}),r}const Hs=Vo;function Wo(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){d.optional=d.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",c)]=l.ideal,d.optional.push(h),h={},h[u("max",c)]=l.ideal,d.optional.push(h)):(h[u("",c)]=l.ideal,d.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[u("",c)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[u(h,c)]=l[h])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},r=function(o,d){if(e.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const l=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(v=>v.kind==="videoinput");let p=h.find(v=>u.some(g=>v.label.toLowerCase().includes(g)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),Hs("chrome: "+JSON.stringify(o)),d(o)})}o.video=i(o.video)}return Hs("chrome: "+JSON.stringify(o)),d(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){r(o,l=>{t.webkitGetUserMedia(l,d,u=>{c&&c(s(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return r(d,c=>o(c).then(l=>{if(c.audio&&!l.getAudioTracks().length||c.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function Ho(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Ko(n,e){if(!(e.version>102))if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",s=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.track.id):a={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=a,o.transceiver={receiver:a},o.streams=[r.stream],this.dispatchEvent(o)}),r.stream.getTracks().forEach(s=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.id):a={track:s};const o=new Event("track");o.track=s,o.receiver=a,o.transceiver={receiver:a},o.streams=[r.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Lt(n,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Go(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,d){let c=r.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function zo(n,e){if(e.version>=67||!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const i=n.RTCPeerConnection.prototype.getSenders;i&&(n.RTCPeerConnection.prototype.getSenders=function(){const a=i.apply(this,[]);return a.forEach(o=>o._pc=this),a});const r=n.RTCPeerConnection.prototype.addTrack;r&&(n.RTCPeerConnection.prototype.addTrack=function(){const a=r.apply(this,arguments);return a._pc=this,a}),n.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(o=>Ws(o,a.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const i=n.RTCPeerConnection.prototype.getReceivers;i&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=i.apply(this,[]);return s.forEach(a=>a._pc=this),s}),Lt(n,"track",r=>(r.receiver._pc=r.srcElement,r)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Ws(a,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const t=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const r=arguments[0];let s,a,o;return this.getSenders().forEach(d=>{d.track===r&&(s?o=!0:s=d)}),this.getReceivers().forEach(d=>(d.track===r&&(a?o=!0:a=d),d.track===r)),o||s&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Jo(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function Qo(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Jo(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===l))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(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const v=this._streams[u.id];if(v)v.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function s(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],v=c._streams[p.id];u=u.replace(new RegExp(v.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],v=c._streams[p.id];u=u.replace(new RegExp(p.id,"g"),v.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){const l=n.RTCPeerConnection.prototype[c],u={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[v=>{const g=s(this,v);h[0].apply(null,[g])},v=>{h[1]&&h[1].apply(null,v)},arguments[2]]):l.apply(this,arguments).then(v=>s(this,v))}};n.RTCPeerConnection.prototype[c]=u[c]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(g=>l.track===g)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function br(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]})}function Yo(n,e){e.version>102||Lt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var Ks=Object.freeze({__proto__:null,fixNegotiationNeeded:Yo,shimAddTrackRemoveTrack:Qo,shimAddTrackRemoveTrackWithNative:Jo,shimGetSendersWithDtmf:Go,shimGetUserMedia:Wo,shimMediaStream:Ho,shimOnTrack:Ko,shimPeerConnection:br,shimSenderReceiverGetStats:zo});function $o(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function wu(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Xo(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function yr(n,e){typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||(!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]}))}function Zo(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const s=Array.prototype.slice.call(arguments),a=s[0],o=s[1],d=s[2];return this.signalingState==="closed"?Promise.resolve(new Map):i.apply(this,[a||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,h)=>{c.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(o,d)}}function ec(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function tc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),Lt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ic(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function nc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function rc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const a=s.sender,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function sc(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function ac(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function oc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Gs=Object.freeze({__proto__:null,shimAddTransceiver:rc,shimCreateAnswer:oc,shimCreateOffer:ac,shimGetDisplayMedia:wu,shimGetParameters:sc,shimGetStats:Zo,shimGetUserMedia:$o,shimOnTrack:Xo,shimPeerConnection:yr,shimRTCDataChannel:nc,shimReceiverGetStats:tc,shimRemoveStream:ic,shimSenderGetStats:ec});function cc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s&&s.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function dc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function lc(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h},e.createAnswer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h};let o=function(d,c,l){const u=r.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(d,c,l){const u=s.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(d,c,l){const u=a.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function uc(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>i(hc(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function hc(n){return n&&n.video!==void 0?Object.assign({},n,{video:jo(n.video)}):n}function pc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,r)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function mc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function fc(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function gc(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var zs=Object.freeze({__proto__:null,shimAudioContext:gc,shimCallbacksAPI:lc,shimConstraints:hc,shimCreateOfferLegacy:fc,shimGetUserMedia:uc,shimLocalStreamsAPI:cc,shimRTCIceServerUrls:pc,shimRemoteStreamsAPI:dc,shimTrackEventTransceiver:mc}),Kn={exports:{}},Js;function Ru(){return Js||(Js=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
4
|
+
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
5
|
+
m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
|
|
6
|
+
`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(r=>r.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":r.relatedAddress=i[s+1];break;case"rport":r.relatedPort=parseInt(i[s+1],10);break;case"tcptype":r.tcpType=i[s+1];break;case"ufrag":r.ufrag=i[s+1],r.usernameFragment=i[s+1];break;default:r[i[s]]===void 0&&(r[i[s]]=i[s+1]);break}return r},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const r=t.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const s=t.type;return i.push("typ"),i.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const r=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
|
|
7
|
+
`},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
|
|
8
|
+
`},e.parseFmtp=function(t){const i={};let r;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)r=s[a].trim().split("="),i[r[0].trim()]=r[1];return i},e.writeFmtp=function(t){let i="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),i+="a=fmtp:"+r+" "+s.join(";")+`\r
|
|
9
|
+
`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{i+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
|
|
10
|
+
`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,i),10)},s=t.indexOf(":",i);return s>-1?(r.attribute=t.substring(i+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(i+1),r},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(r=>parseInt(r,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let r="a=setup:"+i+`\r
|
|
11
|
+
`;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
|
|
12
|
+
`}),r},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
|
|
13
|
+
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const r=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
14
|
+
a=ice-pwd:`+t.password+`\r
|
|
15
|
+
`;return t.iceLite&&(i+=`a=ice-lite\r
|
|
16
|
+
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const d=s[o],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const l=e.parseRtpMap(c),u=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(l.parameters=u.length?e.parseFmtp(u[0]):{},l.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),i.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(l.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(d=>{o.rtcpFeedback.find(l=>l.type===d.type&&l.parameter===d.parameter)||o.rtcpFeedback.push(d)})}),i},e.writeRtpDescription=function(t,i){let r="";r+="m="+t+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
17
|
+
`,r+=`c=IN IP4 0.0.0.0\r
|
|
18
|
+
`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
19
|
+
`,i.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return i.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
|
|
20
|
+
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){const i=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=o.length>0&&o[0].ssrc;let c;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(v=>parseInt(v,10)));l.length>0&&l[0].length>1&&l[0][0]===d&&(c=l[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(p.rtx={ssrc:c}),i.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&d&&i.push({ssrc:d});let u=e.matchPrefix(t,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-2e3*8:u=void 0,i.forEach(h=>{h.maxBitrate=u})),i},e.parseRtcpParameters=function(t){const i={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
|
|
21
|
+
`),t.mux&&(i+=`a=rtcp-mux\r
|
|
22
|
+
`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
23
|
+
`),i},e.parseMsid=function(t){let i;const r=e.matchPrefix(t,"a=msid:");if(r.length===1)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,i){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
|
|
24
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
25
|
+
`,"a=sctp-port:"+i.port+`\r
|
|
26
|
+
`]:r=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
|
|
27
|
+
`,`c=IN IP4 0.0.0.0\r
|
|
28
|
+
`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
|
|
29
|
+
`],i.maxMessageSize!==void 0&&r.push("a=max-message-size:"+i.maxMessageSize+`\r
|
|
30
|
+
`),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,r){let s;const a=i!==void 0?i:2;return t?s=t:s=e.generateSessionId(),`v=0\r
|
|
31
|
+
o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
|
|
32
|
+
s=-\r
|
|
33
|
+
t=0 0\r
|
|
34
|
+
`},e.getDirection=function(t,i){const r=e.splitLines(t);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const r=e.splitLines(t)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){const r=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},n.exports=e})(Kn)),Kn.exports}var vc=Ru(),jt=pu(vc),Iu=cd({__proto__:null,default:jt},[vc]);function Wi(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=jt.parseCandidate(i.candidate);for(const a in s)a in r||Object.defineProperty(r,a,{value:s[a]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,Lt(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function kr(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Lt(n,"icecandidate",e=>{if(e.candidate){const t=jt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Hi(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const d=jt.splitSections(o.sdp);return d.shift(),d.some(c=>{const l=jt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const c=parseInt(d[1],10);return c!==c?-1:c},r=function(o){let d=65536;return e.browser==="firefox"&&(e.version<57?o===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},s=function(o,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const l=jt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?c=parseInt(l[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76&&this.getConfiguration().sdpSemantics==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0}),t(arguments[0])){const d=i(arguments[0]),c=r(d),l=s(arguments[0],d);let u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function Ki(n,e){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>149||e.browser==="firefox"&&e.version>60)return;function t(r,s){const a=r.send;r.send=function(){const d=arguments[0],c=d.length||d.size||d.byteLength;if(r.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return a.apply(r,arguments)}}const i=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=i.apply(this,arguments);return t(s,this),s},Lt(n,"datachannel",r=>(t(r.channel,r.target),r))}function Tr(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Sr(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
|
|
35
|
+
a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
36
|
+
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
37
|
+
`);n.RTCSessionDescription&&r instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function Gi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function zi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Mu=Object.freeze({__proto__:null,removeExtmapAllowMixed:Sr,shimAddIceCandidateNullOrEmpty:Gi,shimConnectionState:Tr,shimMaxMessageSize:Hi,shimParameterlessSetLocalDescription:zi,shimRTCIceCandidate:Wi,shimRTCIceCandidateRelayProtocol:kr,shimSendThrowTypeError:Ki});function Du(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=n.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Vo,r=Pu(e),s={browserDetails:r,commonShim:Mu,extractVersion:oi,disableLog:Eu,disableWarnings:_u,sdp:Iu};switch(r.browser){case"chrome":if(!Ks||!br||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(r.version===null)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Ks,Gi(e,r),zi(e),Wo(e,r),Ho(e),br(e,r),Ko(e,r),Qo(e,r),Go(e),zo(e,r),Yo(e,r),Wi(e),kr(e),Tr(e),Hi(e,r),Ki(e,r),Sr(e,r);break;case"firefox":if(!Gs||!yr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Gs,Gi(e,r),zi(e),$o(e,r),yr(e,r),Zo(e,r),Xo(e),ic(e),ec(e),tc(e),nc(e),rc(e),sc(e),ac(e),oc(e),Wi(e),Tr(e),Hi(e,r),Ki(e,r);break;case"safari":if(!zs||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=zs,Gi(e,r),zi(e),pc(e),fc(e),lc(e),cc(e),dc(e),mc(e),uc(e),gc(e),Wi(e),kr(e),Hi(e,r),Ki(e,r),Sr(e,r);break;default:i("Unsupported browser!");break}return s}Du({window:typeof window>"u"?void 0:window});var Cr,bc;class ke extends(bc=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)}}Cr=ke;ke.resolve=n=>Reflect.get(bc,"resolve",Cr).call(Cr,n);const Ou=/version\/(\d+(\.?_?\d+)+)/i;let Gn;function Te(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(Gn===void 0||e){const i=Au.find(r=>r.test.test(t));Gn=i==null?void 0:i.describe(t)}return Gn}const Au=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ji(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:zn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ji(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:zn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ji(Ou,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:zn(n)}}}];function Ji(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function zn(n){return n.includes("mac os")?Ji(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Nu="2.20.0";const Lu=Nu,xu=17,yc=0,rn=1,Uu=rn;class Ke extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof(i==null?void 0:i.cause)<"u"&&(this.cause=i==null?void 0:i.cause)}}class Oe extends Ke{}class Jm extends Ke{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"Simulated failure";super(-1,e),this.name="simulated"}}var J;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(J||(J={}));class L extends Oe{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=J[t]}static notAllowed(e,t,i){return new L(e,J.NotAllowed,t,i)}static timeout(e){return new L(e,J.Timeout)}static leaveRequest(e,t){return new L(e,J.LeaveRequest,void 0,t)}static internal(e,t){return new L(e,J.InternalError,void 0,t)}static cancelled(e){return new L(e,J.Cancelled)}static serverUnreachable(e,t){return new L(e,J.ServerUnreachable,t)}static websocket(e,t,i){return new L(e,J.WebSocket,t,i)}static serviceNotFound(e,t){return new L(e,J.ServiceNotFound,void 0,t)}}class _n extends Ke{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class $e extends Ke{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Fu extends Ke{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ee extends Ke{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Rt extends Ke{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Bu extends Ke{constructor(e){super(14,e??"unable to publish data"),this.name="PublishDataError"}}class Qs extends Ke{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Ys extends Oe{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Ct[t]}}var be;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(be||(be={}));class De extends Oe{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=be[t]}}class Ut extends Ke{constructor(e){super(18,e),this.name="SignalReconnectError"}}var sn;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(sn||(sn={}));(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(sn||(sn={}));class ae{}ae.setTimeout=function(){return setTimeout(...arguments)};ae.setInterval=function(){return setInterval(...arguments)};ae.clearTimeout=function(){return clearTimeout(...arguments)};ae.clearInterval=function(){return clearInterval(...arguments)};var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived",n.DataTrackPublished="dataTrackPublished",n.DataTrackUnpublished="dataTrackUnpublished",n.LocalDataTrackPublished="localDataTrackPublished",n.LocalDataTrackUnpublished="localDataTrackUnpublished"})(w||(w={}));var I;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(I||(I={}));var P;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved",n.PublishDataTrackResponse="publishDataTrackResponse",n.UnPublishDataTrackResponse="unPublishDataTrackResponse",n.DataTrackSubscriberHandles="dataTrackSubscriberHandles",n.DataTrackPacketReceived="dataTrackPacketReceived",n.Joined="joined",n.TokenRefreshed="tokenRefreshed",n.ServerRegionsReported="serverRegionsReported"})(P||(P={}));var R;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(R||(R={}));function qu(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class G{constructor(e,t,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new 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}}}const Vu=["opus","red"],ju=["vp8","h264"],Wu=["vp8","h264","vp9","av1","h265"];function kc(n){return!!ju.find(e=>e===n)}const Hu=kc;var $s;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})($s||($s={}));var Er;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Er||(Er={}));const ki={h90:new G(160,90,9e4,20),h180:new G(320,180,16e4,20),h216:new G(384,216,18e4,20),h360:new G(640,360,45e4,20),h540:new G(960,540,8e5,25),h720:new G(1280,720,17e5,30),h1080:new G(1920,1080,3e6,30),h1440:new G(2560,1440,5e6,30),h2160:new G(3840,2160,8e6,30)},_r={h120:new G(160,120,7e4,20),h180:new G(240,180,125e3,20),h240:new G(320,240,14e4,20),h360:new G(480,360,33e4,20),h480:new G(640,480,5e5,20),h540:new G(720,540,6e5,25),h720:new G(960,720,13e5,30),h1080:new G(1440,1080,23e5,30),h1440:new G(1920,1440,38e5,30)},Pn={h360fps3:new G(640,360,2e5,3,"medium"),h360fps15:new G(640,360,4e5,15,"medium"),h720fps5:new G(1280,720,8e5,5,"medium"),h720fps15:new G(1280,720,15e5,15,"medium"),h720fps30:new G(1280,720,2e6,30,"medium"),h1080fps15:new G(1920,1080,25e5,15,"medium"),h1080fps30:new G(1920,1080,5e6,30,"medium"),original:new G(0,0,7e6,30,"medium")};function Tc(n,e,t){var i,r,s,a;const o=Ec(n??{}),d=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,u=e==null?void 0:e.processor,h=t==null?void 0:t.processor,p=d??{};return p.audio===!0&&(p.audio={}),p.video===!0&&(p.video={}),p.audio&&(Pr(p.audio,e),(i=(s=p.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(p.audio.processor=c??u)),p.video&&(Pr(p.video,t),(r=(a=p.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=l??h)),p}function Pr(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function ts(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,d=n.video;Object.keys(d).forEach(c=>{switch(c){case"resolution":Pr(o,d.resolution);break;default:o[c]=d[c]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=n.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return n.audio?typeof n.audio=="object"?(s.audio=n.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Sc(n){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=is();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ge(t),r.getByteTimeDomainData(a);const d=a.some(c=>c!==128&&c!==0);return i.close(),!d}return!1})()})}function is(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>m(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch{}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Ku(n){return n==="audioinput"?C.Source.Microphone:n==="videoinput"?C.Source.Camera:C.Source.Unknown}function wr(n){return n===C.Source.Microphone?"audioinput":n===C.Source.Camera?"videoinput":void 0}function Cc(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Nt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function ui(n){return n.split("/")[1].toLowerCase()}function Gu(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Qr({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function V(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?V(n.track):{})}}function zu(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function Ju(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],r={};for(const s of i)n[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Ec(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:qu(e)}}function Qu(n){switch(n){case se.CAMERA:return C.Source.Camera;case se.MICROPHONE:return C.Source.Microphone;case se.SCREEN_SHARE:return C.Source.ScreenShare;case se.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}function Xs(n,e){return n.width*n.height<e.width*e.height}function Yu(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const $u=5e3,ii=[];var Re;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Re||(Re={}));class C extends we.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=U,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),$u):this.handleAppVisibilityChanged()},this.log=Pe((r=i.loggerName)!==null&&r!==void 0?r:he.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ii.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&ii.splice(ii.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Bt(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?R.AudioPlaybackStarted:R.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?R.AudioPlaybackFailed:R.VideoPlaybackFailed,s):s.name==="AbortError"?U.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):U.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){Wt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(R.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Wt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(R.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Pe(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ii.forEach(i=>{i.parentElement||(t=!1)}),t&&ii.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){_e()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_e()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Bt(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(r=>{t.removeTrack(r)}),t.addTrack(n)),(!Nt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Nt()||At())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Wt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(c){switch(c){case e.Audio:return xe.AUDIO;case e.Video:return xe.VIDEO;default:return xe.DATA}}n.kindToProto=r;function s(c){switch(c){case xe.AUDIO:return e.Audio;case xe.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(c){switch(c){case t.Camera:return se.CAMERA;case t.Microphone:return se.MICROPHONE;case t.ScreenShare:return se.SCREEN_SHARE;case t.ScreenShareAudio:return se.SCREEN_SHARE_AUDIO;default:return se.UNKNOWN}}n.sourceToProto=a;function o(c){switch(c){case se.CAMERA:return t.Camera;case se.MICROPHONE:return t.Microphone;case se.SCREEN_SHARE:return t.ScreenShare;case se.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function d(c){switch(c){case mr.ACTIVE:return i.Active;case mr.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=d})(C||(C={}));const Xu="|",Zs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Zu(n){const e=n.split(Xu);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function ge(n){return new ke(e=>ae.setTimeout(e,n))}function an(){return"addTransceiver"in RTCPeerConnection.prototype}function Rr(){return"addTrack"in RTCPeerConnection.prototype}function Qm(){return typeof ResizeObserver!==void 0&&typeof IntersectionObserver!==void 0}function Ym(){return an()}function eh(){if(!("getCapabilities"in RTCRtpSender)||Nt()||At())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function th(){if(!("getCapabilities"in RTCRtpSender)||At())return!1;if(Nt()){const t=Te();if(t!=null&&t.version&&et(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&et(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Be(n){return n==="av1"||n==="vp9"}function on(n){return!document||Ti()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function $m(){return on()}function ih(){return typeof RTCPeerConnection>"u"?!1:an()||Rr()}function At(){var n;return((n=Te())===null||n===void 0?void 0:n.name)==="Firefox"}function nh(){const n=Te();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function Ir(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!nh()}function Nt(){var n;return((n=Te())===null||n===void 0?void 0:n.name)==="Safari"}function Ti(){const n=Te();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function _c(){const n=Te();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&et(n.osVersion,"17")>=0}function rh(n){return n||(n=Te()),(n==null?void 0:n.name)==="Safari"&&et(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&et(n.osVersion,"18.3")>0}function Pc(){var n,e;return _e()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function sh(){const n=Te(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&et(n.osVersion,e)>=0?!0:n.name==="Safari"&&et(n.version,e)>=0}function _e(){return typeof document<"u"}function He(){return navigator.product=="ReactNative"}function Yt(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Jn(n){return Yt(n)?n.hostname.split(".")[0]:null}function wc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Rc(){if(!He())return;let n=wc();if(n)return n.platform}function ea(){if(_e())return window.devicePixelRatio;if(He()){let n=wc();if(n)return n.devicePixelRatio}return 1}function et(n,e){const t=n.split("."),i=e.split("."),r=Math.min(t.length,i.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function ah(n){for(const e of n)e.target.handleResize(e)}function oh(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Qn=null;const ta=()=>(Qn||(Qn=new ResizeObserver(ah)),Qn);let Yn=null;const ia=()=>(Yn||(Yn=new IntersectionObserver(oh,{root:null,rootMargin:"0px"})),Yn);function ch(n){var e;const t=new go({capabilities:n,sdk:vo.JS,protocol:xu,clientProtocol:Uu,version:Lu});return He()&&(t.os=(e=Rc())!==null&&e!==void 0?e:""),t}let $n;function Xm(){return $n||($n=Mr()),$n.clone()}function Mr(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=n,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(n/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream().getTracks(),d=N(o,1),c=d[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}let ni;function Xn(){if(!ni){const t=new AudioContext,i=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);const s=t.createMediaStreamDestination();i.connect(r),r.connect(s),i.start();var n=s.stream.getAudioTracks(),e=N(n,1);if(ni=e[0],!ni)throw Error("Could not get empty media stream audio track");ni.enabled=!1}return ni.clone()}class le{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,r)=>m(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Zm(n,e){const t=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},e),i=is();if(!i)throw new Error("Audio Context not supported on this browser");const r=t.cloneTrack?n.mediaStreamTrack.clone():n.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),a=i.createAnalyser();a.minDecibels=t.minDecibels,a.maxDecibels=t.maxDecibels,a.fftSize=t.fftSize,a.smoothingTimeConstant=t.smoothingTimeConstant,s.connect(a);const o=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(o);let l=0;for(const h of o)l+=Math.pow(h/255,2);return Math.sqrt(l/o.length)},analyser:a,cleanup:()=>m(this,void 0,void 0,function*(){yield i.close(),t.cloneTrack&&r.stop()})}}function ef(n){return Vu.includes(n)}function dh(n){return Wu.includes(n)}function It(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function lh(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Si(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function uh(n,e){return n.segments.map(t=>{let i=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,d=t.final;var c;const l=(c=e.get(i))!==null&&c!==void 0?c:Date.now(),u=Date.now();return d?e.delete(i):e.set(i,l),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:d,language:s,firstReceivedTime:l,lastReceivedTime:u}})}function hh(n){const e=n.id,t=n.timestamp,i=n.message,r=n.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function na(n){switch(n.reason){case J.LeaveRequest:return n.context;case J.Cancelled:return je.CLIENT_INITIATED;case J.NotAllowed:return je.USER_REJECTED;case J.ServerUnreachable:return je.JOIN_FAILURE;default:return je.UNKNOWN_REASON}}function Qi(n){return n!==void 0?Number(n):void 0}function St(n){return n!==void 0?BigInt(n):void 0}function Mt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Ze(n){return!!n&&n.kind==C.Kind.Audio}function ot(n){return!!n&&n.kind==C.Kind.Video}function ze(n){return Mt(n)&&ot(n)}function it(n){return Mt(n)&&Ze(n)}function Dr(n){return!!n&&!n.isLocal}function ph(n){return!!n&&!n.isLocal}function Zn(n){return Dr(n)&&ot(n)}function mh(n){return n.isLocal}function tf(n){return!n.isLocal}function fh(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&t.push(i),t}function gh(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function Ic(){return typeof CompressionStream<"u"}function vh(){return Ic()&&!At()}function bh(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=yh(n,e);return t?i:ns(i,"v1")}function yh(n,e){const t=new URL(lh(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),ns(t,"rtc")}function kh(n){const e=new URL(Si(n));return ns(e,"validate")}function Mc(n){return n.endsWith("/")?n:"".concat(n,"/")}function ns(n,e){return n.pathname="".concat(Mc(n.pathname)).concat(e),n}function ra(n){if(typeof n=="string")return Fs.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Fs.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function Th(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Dc="AES-GCM",Sh=10,ri="lk_e2ee",Ch="LKFrameEncryptionKey",Eh={sharedKey:!1,ratchetSalt:Ch,ratchetWindowSize:8,failureTolerance:Sh,keyringSize:16,keySize:128};var vt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(vt||(vt={}));var sa;(function(n){n.KeyRatcheted="keyRatcheted"})(sa||(sa={}));var ht;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(ht||(ht={}));var aa;(function(n){n.Error="cryptorError"})(aa||(aa={}));function _h(){return rs()||Ph()}function Ph(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function rs(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function nf(n){return"type"in n}function rf(n){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{name:Dc},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"encrypt";return(function*(){return crypto.subtle.importKey("raw",e,t,!1,i==="derive"?["deriveBits","deriveKey"]:["encrypt","decrypt"])})()})}function wh(n){return m(this,void 0,void 0,function*(){let e=new TextEncoder;return yield crypto.subtle.importKey("raw",e.encode(n),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])})}function Rh(n){return m(this,void 0,void 0,function*(){return yield crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveBits","deriveKey"])})}function Oc(n,e){const i=new TextEncoder().encode(e);switch(n){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(n," is currently unsupported"))}}function sf(n,e){return m(this,void 0,void 0,function*(){const t=Oc(n.algorithm.name,e.ratchetSalt),i=yield crypto.subtle.deriveKey(t,n,{name:Dc,length:e.keySize},!1,["encrypt","decrypt"]);return{material:n,encryptionKey:i}})}function af(){return window.crypto.getRandomValues(new Uint8Array(32))}function of(n,e){return m(this,void 0,void 0,function*(){const t=Oc(n.algorithm.name,e);return crypto.subtle.deriveBits(t,n,256)})}function cf(n){for(var e=0;e<n.length-3;e++)if(n[e]==0&&n[e+1]==0&&n[e+2]==3)return!0;return!1}function df(n){const e=[];for(var t=n.length,i=0;i<n.length;)t-i>=3&&!n[i]&&!n[i+1]&&n[i+2]==3?(e.push(n[i++]),e.push(n[i++]),i++):e.push(n[i++]);return new Uint8Array(e)}const Ih=2,oa=3;function lf(n){const e=[];for(var t=0,i=0;i<n.length;++i){var r=n[i];r<=oa&&t>=Ih&&(e.push(oa),t=0),e.push(r),r==0?++t:t=0}return new Uint8Array(e)}function Mh(n){var e,t,i,r,s;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new co({value:n.value})}class Dh extends we.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,r)=>{U.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Eh),e),this.on(vt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(vt.SetKey,r,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(vt.RatchetRequest,e,t)}}class uf extends Dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1});super(t)}setKey(e){return m(this,void 0,void 0,function*(){const t=typeof e=="string"?yield wh(e):yield Rh(e);this.onSetEncryptionKey(t)})}}var Or;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Or||(Or={}));class hf extends Ke{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Or.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=i}}function Ci(){return Ir()}function Ei(n){return!!(n!=null&&n.worker)&&(rs()||Ci())}function cn(n){return!!(n!=null&&n.timestamp||n!=null&&n.frameId)}function Oh(n){const e=[];return n!=null&&n.timestamp&&e.push(Jt.PTF_USER_TIMESTAMP),n!=null&&n.frameId&&e.push(Jt.PTF_FRAME_ID),e}function Ah(n){if(!n||n.length===0)return;const e={};return n.includes(Jt.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),n.includes(Jt.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function ss(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,r;let s;const a=(i=t.isImmediate)!==null&&i!==void 0?i:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,d=t.maxWait;let c=Date.now(),l=[];function u(){if(d!==void 0){const p=Date.now()-c;if(p+e>=d)return d-p}return e}const h=function(){for(var p=arguments.length,v=new Array(p),g=0;g<p;g++)v[g]=arguments[g];const T=this;return new Promise((k,S)=>{const x=function(){if(s=void 0,c=Date.now(),!a){const y=n.apply(T,v);o&&o(y),l.forEach(_=>{let M=_.resolve;return M(y)}),l=[]}},b=a&&s===void 0;if(s!==void 0&&ae.clearTimeout(s),s=ae.setTimeout(x,u()),b){const y=n.apply(T,v);return o&&o(y),k(y)}l.push({resolve:k,reject:S})})};return h.cancel=function(p){s!==void 0&&ae.clearTimeout(s),l.forEach(v=>{let g=v.reject;return g(p)}),l=[]},h}const as=2e3;function wn(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}class Ac extends C{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?R.Muted:R.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}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(),as)),zu()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const r=i.timestamp,s=i.rtpTimestamp;s&&this.rtpTimestamp!==s&&(this.emit(R.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}const er=100;class os extends Ac{constructor(e,t,i,r,s){super(e,t,C.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=wn(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=ss(()=>{this.updateDimensions()},er),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return(i=this.frameMetadataExtractor)===null||i===void 0?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Wt(this._mediaStreamTrack,t):Bt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Nh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const r=this.elementInfos.reduce((d,c)=>Math.max(d,c.visibilityChangedAt||0),0),s=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(d=>d.pictureInPicture),o=this.elementInfos.some(d=>d.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<er){ae.setTimeout(()=>{this.updateVisibility()},er);return}this.lastVisible=o,this.emit(R.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,d=a.height()*s;o+d>i+r&&(i=o,r=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(R.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?ea():t||(ea()>2?2:1)}}class Nh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const s=i.target,a=i.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=si(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=si(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var i;this.isPiP=si(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Ar(e),this.isPiP=_e()&&si(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ar(this.element),this.isPiP=si(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ia().observe(this.element),ta().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=ia())===null||e===void 0||e.unobserve(this.element),(t=ta())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function si(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ar(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ar(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,o=n,d=o.hidden,c=getComputedStyle(n),l=c.display;for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!d&&l!=="none"}class Lh extends we.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var r,s;const a=i.data,o=a.kind,d=a.data;switch(o){case"error":if(U.error(d.error.message),d.uuid){const u=this.decryptDataRequests.get(d.uuid);if(u!=null&&u.reject){u.reject(d.error);break}const h=this.encryptDataRequests.get(d.uuid);if(h!=null&&h.reject){h.reject(d.error);break}}this.emit(ht.EncryptionError,d.error,d.participantIdentity);break;case"initAck":d.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)});break;case"enable":if(d.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)}),this.encryptionEnabled!==d.enabled&&d.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(ht.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){const u=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(d.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(d.participantIdentity));this.emit(ht.ParticipantEncryptionStatusChanged,d.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(vt.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(d.uuid);c!=null&&c.resolve&&c.resolve(d);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(d.uuid);l!=null&&l.resolve&&l.resolve(d);break;case"packetTrailerMetadata":this.handleFrameMetadata(d.trackId,d.rtpTimestamp,d.ssrc,d.metadata);break}},this.onWorkerError=i=>{U.error("e2ee worker encountered an error:",{error:i.error}),this.emit(ht.EncryptionError,i.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(!_h())throw new _n("tried to setup end-to-end encryption on an unsupported browser");if(U.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:vu.getLevel()}};this.worker&&(U.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){U.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?U.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,r){if(this.room){for(const s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof os&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,r);return}}}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Q.NONE,r.identity)),e.on(w.ConnectionStateChanged,i=>{i===H.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Q.NONE,r.identity)})})}).on(w.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(w.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(w.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const i=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,i===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(i,r)=>m(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!ot(i.track)||!Ti())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:ui(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(vt.SetKey,(i,r)=>this.postKey(i,r??!0)).on(vt.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return m(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new le;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,t,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:r}},o=new le;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){let i=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:i,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new 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(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const r=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?ui(i.mimeType):void 0,r)}setupE2EESender(e,t){var i,r,s;if(!Mt(e)||!t){t||U.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,ot(e)?(r=(i=e.publishOptions)===null||i===void 0?void 0:i.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,i,r,s){return m(this,void 0,void 0,function*(){if(this.worker){if(Ir()){const a={kind:"decode",participantIdentity:i,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(ri in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i,hasPacketTrailer:s}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}const d={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:i,isReuse:ri in e,hasPacketTrailer:s}};this.worker.postMessage(d,[o,a])}e[ri]=!0}})}handleSender(e,t,i,r){var s;if(!(ri in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ir()){U.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:cn(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{U.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:cn(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[ri]=!0}}}const xh=300;class Uh{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=xh;){const r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class Nc{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const i=t.data;if(i.kind==="metadata"){const r=this.extractors.get(i.data.trackId);r&&r.storeMetadata(i.data.rtpTimestamp,i.data.ssrc,i.data.metadata)}},this.onWorkerError=t=>{U.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e==null?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(w.TrackSubscribed,(t,i,r)=>{t.kind==="video"&&this.setupReceiver(t,i.trackInfo)}).on(w.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(w.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,r,s;const a=e.receiver;if(!a)return;if(!(!!(t!=null&&t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){!((i=this.room)===null||i===void 0)&&i.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Ei(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){U.warn("frame metadata transform not supported; skipping extraction");return}const d=new Uh,c=e.mediaStreamID;this.extractors.set(c,d),e.frameMetadataExtractor=d,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(a,c,!0)}setupPassthroughReceiver(e,t){if(Ci()){"transform"in e&&(e.transform=null);return}if(this.worker&&Ei({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=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;const r=this.worker;if(!r)return;if(Ci()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}const s=this.workerPipelines.get(e);if(s){const d={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:i}};r.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){U.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(d){U.warn("failed to create encoded streams",{error:d});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:i}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof os&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const pf=Nc,Fh=500,Bh=15e3;class Ht{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Ht),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),r=Jn(i);if(!r)return;let s=(t=this.failedConnectionAttempts.get(r))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,ge(Math.min(Fh*Math.pow(2,s),Bh)))}getBackOffPromise(e){const t=new URL(e),i=t&&Jn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Jn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Ht._instance=null;const tr="default";class de{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new de),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=de.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){U.debug("awaiting getUserMedia promise");try{t?yield de.userMediaPromiseMap.get(t):yield Promise.all(de.userMediaPromiseMap.values())}catch{U.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Nt()&&i.hasDeviceInUse(t))&&(a.filter(d=>d.kind===t).length===0||a.some(d=>{const c=d.label==="",l=t?d.kind===t:!0;return c&&l}))){const d={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(d);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return m(this,void 0,void 0,function*(){if(t!==tr)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===tr);if(!s){U.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==tr&&o.groupId===(i??s.groupId));if(!a){U.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?de.userMediaPromiseMap.has(e):de.userMediaPromiseMap.size>0}}de.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];de.userMediaPromiseMap=new Map;const cs=65535,Lc=4294967295;class We{static u16(e){return new We(e,cs)}static u32(e){return new We(e,Lc)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new We(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new We(e,this.maxSize)}isBefore(e){const t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}}class Kt{static fromRtpTicks(e){return new Kt(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Lc);return Kt.fromRtpTicks(e)}constructor(e,t){this.timestamp=We.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new Kt(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Et{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new Et(t,new Date,e)}static startingAtTime(e,t,i){return new Et(i,e,t)}static rtpStartingNow(e){return Et.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Et.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=Et.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(i),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let r=(e*1e6*t+5e8)/1e9;return Math.round(r)}}function ds(n){if(n instanceof DataView)return n;if(n instanceof ArrayBuffer)return new DataView(n);if(n instanceof Uint8Array)return new DataView(n.buffer,n.byteOffset,n.byteLength);throw new Error("Error coercing ".concat(n," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Dt;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Dt||(Dt={}));class $t extends Oe{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Dt[t]}isReason(e){return this.reason===e}static tooLarge(){return new $t("Value too large to be a valid track handle",Dt.TooLarge)}static reserved(e){return new $t("0x".concat(e.toString(16)," is a reserved value."),Dt.Reserved)}}const qh={fromNumber(n){if(n===0)throw $t.reserved(n);if(n>cs)throw $t.tooLarge();return n}};class Vh{constructor(){this.value=0}get(){return this.value+=1,this.value>cs?null:this.value}reset(){this.value=0}}const dn={from(n){return{sid:n.sid,pubHandle:n.pubHandle,name:n.name,usesE2ee:n.encryption!==Q.NONE}},toProtobuf(n){return new fn({sid:n.sid,pubHandle:n.pubHandle,name:n.name,encryption:n.usesE2ee?Q.GCM:Q.NONE})}};var hi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(hi||(hi={}));class jh{constructor(){this.pendingTasks=new Map,this.taskMutex=new ue,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:hi.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=hi.RUNNING,yield e()}finally{t.status=hi.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Wh{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=o.closeCode,c=o.reason;return s.close(d,c)};this.opened=new ke((o,d)=>{const c=()=>{d(L.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{o({readable:new ReadableStream({start(l){s.onmessage=u=>{let h=u.data;return l.enqueue(h)},s.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){s.send(l)},abort(){s.close()},close:a}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),this.closed=new ke((o,d)=>{const c=()=>m(this,void 0,void 0,function*(){const l=new ke(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",p=>{h(p)},{once:!0})}),u=yield ke.race([ge(250),l]);u?o(u):d(L.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=l=>{let u=l.code,h=l.reason;o({closeCode:u,reason:h}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=a}}const Hh=["syncState","trickle","offer","answer","simulate","leave"];function Kh(n){const e=Hh.indexOf(n.case)>=0;return U.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var z;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(z||(z={}));const Gh=250;class ls{get currentState(){return this.state}get isDisconnected(){return this.state===z.DISCONNECTING||this.state===z.DISCONNECTED}get isEstablishingConnection(){return this.state===z.CONNECTING||this.state===z.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=z.DISCONNECTED,this.log=U,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=t.loggerContextCb,this.log=Pe((i=t.loggerName)!==null&&i!==void 0?i:he.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new jh,this.queuedRequests=[],this.closingLock=new ue,this.connectionLock=new ue,this.state=z.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){return c.state=z.CONNECTING,c.options=o,yield c.connect(s,a,o,d,l,u)})()})}reconnect(e,t,i,r){return m(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=z.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){const h=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;const p=ch(o.clientInfoCapabilities),v=l?zh(a,p,o):yield Jh(a,p,o,u),g=bh(s,v,l).toString(),T=kh(g).toString();return new Promise((k,S)=>m(c,void 0,void 0,function*(){var x,b;try{let y=!1;const _=O=>m(this,void 0,void 0,function*(){if(y)return;y=!0;const F=O instanceof Event?O.currentTarget:O,X=Th(F,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(X)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),M(),S(L.cancelled(X))});d==null||d.addEventListener("abort",_);const M=()=>{clearTimeout(A),d==null||d.removeEventListener("abort",_)},A=setTimeout(()=>{_(L.timeout("room connection has timed out (signal)"))},o.websocketTimeout),q=(O,F)=>{this.handleSignalConnected(O,A,F)},D=new URL(g);if(D.searchParams.has("access_token")&&D.searchParams.set("access_token","<redacted>"),this.ws){const O=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-O,"ms"))}this.log.info("signal connecting to ".concat(D),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new Wh(g);try{this.ws.closed.then(ve=>{var ct;this.isEstablishingConnection&&S(L.internal("Websocket got closed during a (re)connection attempt: ".concat(ve.reason))),ve.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:ve.reason,code:ve.closeCode,wasClean:ve.closeCode===1e3,state:this.state}),this.state===z.CONNECTED&&this.handleOnClose((ct=ve.reason)!==null&&ct!==void 0?ct:"Unexpected WS error"))}).catch(ve=>{this.isEstablishingConnection&&S(L.internal("Websocket error during a (re)connection attempt: ".concat(ve)))});const O=yield this.ws.opened.catch(ve=>m(this,void 0,void 0,function*(){if(this.state!==z.CONNECTED){this.state=z.DISCONNECTED,clearTimeout(A);const ct=yield this.handleConnectionError(ve,T);S(ct);return}this.handleWSError(ve),S(ve)}));if(clearTimeout(A),!O)return;const F=O.readable.getReader();this.streamWriter=O.writable.getWriter();const X=yield F.read();if(F.releaseLock(),!X.value)throw L.internal("no message received as first message");const Z=ra(X.value),Ge=this.validateFirstMessage(Z,(x=o.reconnect)!==null&&x!==void 0?x:!1);if(!Ge.isValid){S(Ge.error);return}((b=Z.message)===null||b===void 0?void 0:b.case)==="join"&&(this.pingTimeoutDuration=Z.message.value.pingTimeout,this.pingIntervalDuration=Z.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(Z.message.value));const Zt=Ge.shouldProcessFirstMessage?Z:void 0;q(O,Zt),k(Ge.response)}catch(O){S(O)}finally{M()}}finally{h()}}))})()})}startReadingLoop(e,t){return m(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ge(this.signalLatency));const i=yield e.read(),r=i.done,s=i.value;if(r)break;const a=ra(s);this.handleSignalResponse(a)}})}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([z.DISCONNECTING||z.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=z.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,ge(Gh)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=z.DISCONNECTED),r()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:_t(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:_t(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Tn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Sn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new $r({requestId:o,metadata:i,name:r,attributes:a})}),o})()})}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 Mo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ao({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:$.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new xo({timestamp:$.parse(Date.now()),rtt:$.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Yr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new En({reason:je.CLIENT_INITIATED,action:Vt.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new Gr({pubHandle:e,name:t,encryption:i?Q.GCM:Q.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Jr({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Po({updates:[new wo({trackSid:e,subscribe:t})]})})}sendRequest(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!Kh(t)&&i.state===z.RECONNECTING){i.queuedRequests.push(()=>m(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield ge(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case));return}const a=new Fl({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary().buffer)}catch(o){i.log.error("error sending signal message",{error:o})}})()})}handleSignalResponse(e){var t,i;const r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){const a=ca(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const a=ca(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(r.value):r.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(r.value):r.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(r.value):r.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===z.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=ae.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ae.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=ae.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ae.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=z.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,r,s,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===z.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.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&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:L.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:L.internal("Unexpected first message")}:{isValid:!1,error:L.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return m(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:const r=yield i.text();return r.includes("requested room does not exist")?L.notAllowed(r,i.status):L.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return L.notAllowed(s,i.status);default:break}return e instanceof L?e:L.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof L?i:L.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function ca(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function _t(n,e){return new yt({sdp:n.sdp,type:n.type,id:e})}function zh(n,e,t){var i;const r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",He()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function Jh(n,e,t,i){return m(this,void 0,void 0,function*(){const r=new URLSearchParams;r.set("access_token",n);const s=new du({clientInfo:e,connectionSettings:new Uo({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:i});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const a=s.toBinary();let o,d;if(Ic()){const h=new CompressionStream("gzip"),p=h.writable.getWriter();p.write(new Uint8Array(a)),p.close();const v=[],g=h.readable.getReader();for(;;){const x=yield g.read(),b=x.done,y=x.value;if(b)break;v.push(y)}const T=v.reduce((x,b)=>x+b.length,0),k=new Uint8Array(T);let S=0;for(const x of v)k.set(x,S),S+=x.length;o=k,d=gr.GZIP}else o=a,d=gr.NONE;const l=new lu({joinRequest:o,compression:d}).toBinary(),u=h=>{const p=Array.from(h,v=>String.fromCodePoint(v)).join("");return btoa(p)};return r.set("join_request",u(l).replace(/\+/g,"-").replace(/\//g,"_")),r})}class da{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Qh{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const i of this._map.entries()){var t=N(i,2);const r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=N(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const s of i.entries()){var r=N(s,2);const a=r[0],o=r[1];t.push(e(o,a,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=N(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}}var Ae={},ir={},nr={exports:{}},la;function us(){if(la)return nr.exports;la=1;var n=nr.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %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 e.subtype!=null?"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 e.sessionConfig!=null?"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+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),nr.exports}var ua;function Yh(){return ua||(ua=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,d,c,l){if(l&&!c)d[l]=e(o[1]);else for(var u=0;u<c.length;u+=1)o[u+1]!=null&&(d[c[u]]=e(o[u+1]))},i=function(o,d,c){var l=o.name&&o.names;o.push&&!d[o.push]?d[o.push]=[]:l&&!d[o.name]&&(d[o.name]={});var u=o.push?{}:l?d[o.name]:d;t(c.match(o.reg),u,o.names,o.name),o.push&&d[o.push].push(u)},r=us(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var d={},c=[],l=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],p=u.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var v=0;v<(r[h]||[]).length;v+=1){var g=r[h][v];if(g.reg.test(p))return i(g,l,p)}}),d.media=c,d};var a=function(o,d){var c=d.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&d.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var d=[],c=o.split(" ").map(e),l=0;l<c.length;l+=3)d.push({component:c[l],ip:c[l+1],port:c[l+2]});return d},n.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(d){return d.split(",").map(function(c){var l,u=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),u=!0),{scid:l,paused:u}})})}})(ir)),ir}var rr,ha;function $h(){if(ha)return rr;ha=1;var n=us(),e=/%[sdv%]/g,t=function(a){var o=1,d=arguments,c=d.length;return a.replace(e,function(l){if(o>=c)return l;var u=d[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,d){var c=o.format instanceof Function?o.format(o.push?d:d[o.name]):o.format,l=[a+"="+c];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(d[o.name][h]):l.push(d[o.names[u]])}else l.push(d[o.name]);return t.apply(null,l)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return rr=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var d=o.outerOrder||r,c=o.innerOrder||s,l=[];return d.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){l.push(i(u,h,p))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),c.forEach(function(h){n[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(i(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(v){l.push(i(h,p,v))})})})}),l.join(`\r
|
|
38
|
+
`)+`\r
|
|
39
|
+
`},rr}var pa;function Xh(){if(pa)return Ae;pa=1;var n=Yh(),e=$h(),t=us();return Ae.grammar=t,Ae.write=e,Ae.parse=n.parse,Ae.parseParams=n.parseParams,Ae.parseFmtpConfig=n.parseFmtpConfig,Ae.parsePayloads=n.parsePayloads,Ae.parseRemoteCandidates=n.parseRemoteCandidates,Ae.parseImageAttributes=n.parseImageAttributes,Ae.parseSimulcastStreamList=n.parseSimulcastStreamList,Ae}var Ie=Xh();const Zh=.7,ep=20,pt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class ma extends we.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=U,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=ss(r=>m(this,void 0,void 0,function*(){this.emit(pt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),ep),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=Pe((i=t.loggerName)!==null&&i!==void 0?i:he.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new ue}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(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 m(this,void 0,void 0,function*(){var i,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let a=tp(e),o=a.stereoMids,d=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const o=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const d=Ie.parse((i=o.sdp)!==null&&i!==void 0?i:"");d.media.forEach(c=>{Ni(c)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(o,Ie.write(d))}const a=Ie.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(o=>{const d=hs(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||d!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(h=>h.codec.toUpperCase()===c.codec.toUpperCase()?(l=h.payload,!0):!1),l===0)return!0;let u=!1;for(const h of o.fmtp)if(h.payload===l){h.config=h.config.split(";").filter(p=>!p.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(h.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),u=!0;break}return u||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Ie.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(pt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(pt.NegotiationComplete),e.sdp&&Ie.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(pt.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}const i=this.latestOfferId+1;this.latestOfferId=i;const r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};const s=Ie.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{Ni(a)}),r.sdp=Ie.write(s),{offer:r,offerId:i}}finally{t()}})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const a=Ie.parse((t=s.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{Ni(o),o.type==="audio"?fa(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(d=>{if(!o.msid||!d.cid||!o.msid.includes(d.cid))return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===d.codec.toUpperCase()?(c=u.payload,!0):!1),c===0||(Be(d.codec)&&!Nt()&&this.ensureVideoDDExtensionForSVC(o,a),!Be(d.codec)))return!0;const l=Math.round(d.maxbr*Zh);for(const u of o.fmtp)if(u.payload===c){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,Ie.write(a)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Ie.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Ni(r),r.type==="audio"&&fa(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ie.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 ee("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 ee("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return m(this,void 0,void 0,function*(){var r,s;const 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(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:o,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{i?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let d="unknown error";o instanceof Error?d=o.message:typeof o=="string"&&(d=o);const c={error:d,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!i&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:c})),new Rt(d)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Zs))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var d;(d=o.ext)===null||d===void 0||d.forEach(c=>{c.value>a&&(a=c.value)})}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Zs})}}}function fa(n,e,t){const i=hs(n.mid);let r=0;n.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function tp(n){var e;const t=[],i=[],r=Ie.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const d=hs(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(d),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:i}}function Ni(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function hs(n){return typeof n=="number"?n.toFixed(0):n}const Nr="vp8",ip={audioPreset:Er.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Pn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Nr,backupCodec:!0,preConnectBuffer:!1},xc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Uc={deviceId:{ideal:"default"},resolution:ki.h720.resolution},np={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new yu,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ps={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class ga{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 r;this.peerConnectionTimeout=ps.peerConnectionTimeout,this.log=U,this.updateState=()=>{var s,a;const o=this.state,d=this.requiredTransports.map(c=>c.getConnectionState());d.every(c=>c==="connected")?this.state=te.CONNECTED:d.some(c=>c==="failed")?this.state=te.FAILED:d.some(c=>c==="connecting")?this.state=te.CONNECTING:d.every(c=>c==="closed")?this.state=te.CLOSED:d.some(c=>c==="closed")?this.state=te.CLOSING:d.every(c=>c==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Pe((r=t.loggerName)!==null&&r!==void 0?r:he.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new ma(i,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new ma(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Ue.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Ue.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=te.NEW,this.connectionLock=new ue,this.remoteOfferLock=new ue}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!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 m(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){var i;t===Ue.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(this,void 0,void 0,function*(){var i,r,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new ke((t,i)=>{const r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1;const a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(pt.OfferAnswered,o),e.signal.removeEventListener("abort",d))},o=l=>{l>r&&(a(),t())},d=()=>{a(),i(new Rt("negotiation aborted"))},c=setTimeout(()=>{a(),i(new Rt("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",d),this.publisher.on(pt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?i(l):i(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ue.PUBLISHER?this.publisher.getConnectedAddress():e===Ue.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((d,c)=>m(s,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ae.clearTimeout(u),c(L.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&l(),r==null||r.signal.addEventListener("abort",l);const u=ae.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",l),c(L.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield ge(50),r!=null&&r.signal.aborted){c(L.cancelled("room connection has been cancelled"));return}ae.clearTimeout(u),r==null||r.signal.removeEventListener("abort",l),d()}))})()})}}const ms=typeof MediaRecorder<"u";class rp{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const sp=ms?MediaRecorder:rp;class ap extends sp{constructor(e,t){if(!ms)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r==null||r.close(),r=void 0},o=d=>{r==null||r.error(d),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:d=>{r=d,i=c=>m(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){const u=yield c.data.arrayBuffer();l=new Uint8Array(u)}else if(c.data.byteArray)l=c.data.byteArray;else throw new Error("no data available!");s()||d.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function op(){return ms}const cp=1e3,dp=1e4;class Fc extends C{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 r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),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=ss(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(R.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ue,this.pauseUpstreamLock=new ue,this.trackChangeLock=new ue,this.trackChangeLock.lock().then(a=>m(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return m(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Wt(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Bt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{Bt(s??e,a)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:cp;return(function*(){var i;if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Te())===null||i===void 0?void 0:i.os)==="iOS"&&(yield ge(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield ge(50)}throw new $e("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===It(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),It(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===C.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),r=i.deviceId,s=i.groupId,a=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?de.getInstance().normalizeDeviceId(a,r,s):r})()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new $e("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){})}restart(e,t){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const r=e,s=r.deviceId,a=r.facingMode,o=es(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const d={audio:!1,video:!1};this.kind===C.Kind.Video?d.video=s||a?{deviceId:s,facingMode:a}:!0:d.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(u=>{Wt(this.mediaStreamTrack,u)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===C.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(R.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?R.Muted:R.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Pc()&&(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),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(R.UpstreamPaused,this);const i=Te();if((i==null?void 0:i.name)==="Safari"&&et(i.version,"12.0")<0)throw new _n("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(R.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),d={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext,localTrack:i};if(yield t.init(d),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Bt(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Wt(i._mediaStreamTrack,c),Bt(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(R.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(R.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!op()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new ap(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},dp)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class _i extends Fc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=wn(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,ce.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,ce.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const i=ts({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const r=yield i.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){_e()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},as)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!He()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={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(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?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(R.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Sc(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(R.AudioSilenceDetected)),e})}}function lp(n,e,t){switch(n.kind){case"audio":return new _i(n,e,!1,void 0,t);case"video":return new Pi(n,e,!1,t);default:throw new $e("unsupported track type: ".concat(n.kind))}}const up=Object.values(ki),hp=Object.values(_r),pp=Object.values(Pn),mp=[ki.h180,ki.h360],fp=[_r.h180,_r.h360],gp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new G(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),Lr=["q","h","f"];function ln(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,d=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!d||!e||!t)return[{}];a||(a=vp(n,e,t,c),U.debug("using video encoding",a));const l=a.maxFramerate,u=new G(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(d&&Be(c)){const T=new qc(d),k=[];if(T.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));const S=Te();if(Ti()||He()||(S==null?void 0:S.name)==="Chrome"&&et(S==null?void 0:S.version,"113")<0){const x=T.suffix=="h"?2:3,b=rh(S);for(let y=0;y<T.spatial;y+=1)k.push({rid:Lr[2-y],maxBitrate:a.maxBitrate/Math.pow(x,y),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:b?Math.pow(2,y):void 0});k[0].scalabilityMode=d}else k.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:d});return u.encoding.priority&&(k[0].priority=u.encoding.priority,k[0].networkPriority=u.encoding.priority),U.debug("using svc encoding",{encodings:k}),k}if(!o)return[a];let h;n?h=(r=ba(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:va(n,u):h=(s=ba(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:va(n,u);let p;if(h.length>0){const T=h[0];if(h.length>1){var v=h,g=N(v,2);p=g[1]}const k=Math.max(e,t);if(k>=960&&p)return sr(e,t,[T,p,u],l);if(k>=480)return sr(e,t,[T,u],l)}return sr(e,t,[u])}function Bc(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&U.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),d=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ln(n.source===C.Source.ScreenShare,d,c,t)}function vp(n,e,t,i){const r=bp(n,e,t);let s=r[0].encoding;const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const d=r[o];if(s=d.encoding,d.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function bp(n,e,t){if(n)return pp;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?up:hp}function va(n,e){if(n)return gp(e);const t=e.width,i=e.height,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?mp:fp}function sr(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=Lr.length)return;const o=Math.min(n,e),c={rid:Lr[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=Te(),h=(u==null?void 0:u.name)==="Firefox"&&u.os!=="iOS"||a===0;s.encoding.priority&&h&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),He()&&Rc()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var d;o.maxFramerate!=s&&(a&&(a=!1,U.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),U.info('Setting framerate of encoding "'.concat((d=o.rid)!==null&&d!==void 0?d:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function ba(n){if(n)return n.slice().sort((e,t)=>{const i=e.encoding,r=t.encoding;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class qc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function yp(n){return n.source===C.Source.ScreenShare||n.constraints.height&&It(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const kp=5e3;class Pi extends Fc{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&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}const a=new Map(s.map(d=>[d.rid,d])),o=s.some(d=>d.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(R.CpuConstrained)),this.prevStats){let d=0;a.forEach((c,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);d+=wn(c,h)}),this._currentBitrate=d}this.prevStats=a}),this.senderLock=new ue}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!_e())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},as))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,d=Fe(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,d=Fe(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Re.LOW;i<=Re.HIGH;i+=1)t.push(new Xr({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Be(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const u=ts({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var d=!0,c=Fe(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;d=!0){s=l.value,d=!1;const u=s;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!d&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return m(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;const s=this.source===C.Source.ScreenShare,a=ln(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(const o of this.simulcastCodecs){var i=N(o,2);const d=i[0],c=i[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!kc(d))continue;const l=Object.assign({},this.publishOptions),u=Bc(this,d,l);u&&(yield this.applyEncodingsToSender(c.sender,u),c.encodings=u)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return m(this,void 0,void 0,function*(){const i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEach((r,s)=>{if(r.active===!1)return;const a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.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){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,d,c,l,u;if(yield t.setProcessor.call(r,i,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,p=Fe(r.simulcastCodecs.values()),v;v=yield p.next(),a=v.done,!a;h=!0)c=v.value,h=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(g){o={error:g}}finally{try{!h&&!a&&(d=p.return)&&(yield d.call(p))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},kp))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a,o,d;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(Be(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Fe(e);r=yield i.next(),s=r.done,!s;t=!0){d=r.value,t=!1;const l=d;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Be(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield ya(u.sender,u.encodings,l.qualities,this.senderLock,Be(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return m(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 ya(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Be(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Pc()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ya(n,e,t,i,r,s,a){return m(this,void 0,void 0,function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const d=n.getParameters(),c=d.encodings;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:c,senderEncodings:e}));return}let l=!1;!1&&c[0].scalabilityMode||(r&&t.some(p=>p.enabled)&&t.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var v;let g=(v=h.rid)!==null&&v!==void 0?v:"";g===""&&(g="q");const T=Vc(g),k=t.find(S=>S.quality===T);k&&h.active!==k.enabled&&(l=!0,h.active=k.enabled,s.debug("setting layer ".concat(k.quality," to ").concat(h.active?"enabled":"disabled"),a),At()&&(k.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(d.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:d.encodings})),yield n.setParameters(d))}finally{o()}})}function Vc(n){switch(n){case"f":return Re.HIGH;case"h":return Re.MEDIUM;case"q":return Re.LOW;default:return Re.HIGH}}function ka(n,e,t,i){if(!t)return[new ft({quality:Re.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new qc(r),a=[],o=s.suffix=="h"?1.5:2,d=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new ft({quality:Math.min(Re.HIGH,s.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(d,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const d=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=Vc((a=r.rid)!==null&&a!==void 0?a:"");return new ft({quality:c,width:Math.ceil(n/d),height:Math.ceil(e/d),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ta="_lossy",Sa="_reliable",Ca="_data_track",Tp=2*1e3,ar="leave-reconnect",Sp=3e4,Cp=8*1024,Ep=256*1024,_p=3,Pp=3;var Me;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Me||(Me={}));var B;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(B||(B={}));const Ea=64e3;class wp extends we.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=ps.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Me.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=U,this.reliableDataSequence=1,this.reliableMessageBuffer=new da,this.reliableReceivedState=new Qh(Sp),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new le,this.handleDataChannel=i=>m(this,[i],void 0,function(r){var s=this;let a=r.channel;return(function*(){if(!a)return;let o;if(a.label===Sa)s.reliableDCSub=a,o=s.handleDataMessage;else if(a.label===Ta)s.lossyDCSub=a,o=s.handleDataMessage;else if(a.label===Ca)s.dataTrackDCSub=a,o=s.handleDataTrackMessage;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label)),a.onmessage=o})()}),this.handleDataMessage=i=>m(this,void 0,void 0,function*(){var r,s,a,o,d;const c=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",{data:i.data});return}const u=fe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((r=u.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((s=u.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),p=co.fromBinary(h.payload),v=new fe({value:p.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=v.value)===null||o===void 0?void 0:o.case)==="user"&&_a(v,v.value.value),this.emit(P.DataPacketReceived,v,u.value.value.encryptionType)}else((d=u.value)===null||d===void 0?void 0:d.case)==="user"&&_a(u,u.value.value),this.emit(P.DataPacketReceived,u,Q.NONE)}finally{c()}}),this.handleDataTrackMessage=i=>m(this,void 0,void 0,function*(){let r;if(i.data instanceof ArrayBuffer)r=i.data;else if(i.data instanceof Blob)r=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",{data:i.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(r))}),this.handleDataError=i=>{if(this._isClosed)return;const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&i instanceof RTCErrorEvent&&i.error){const a=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(s),{event:i})},this.handleDataChannelClose=i=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(B[i],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=i=>{this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===ar&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(P.TokenRefreshed,this.token),this.reconnectTimeout=ae.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Me.Connected&&i();const s=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,s),r()};this.once(P.Restarted,s),this.once(P.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===B.RELIABLE){const s=this.dataChannelForKind(i);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(P.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.onRtpMapAvailable=i=>{const r=new Map;i.forEach(s=>{const a=s.codec.toLowerCase();dh(a)&&r.set(s.payload,a)}),this.emit(P.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch(Si(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===z.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===z.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Tt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Si(this.url),{method:"HEAD"}),ge(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Pe((t=e.loggerName)!==null&&t!==void 0?t:he.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ls(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new ue,this.dataProcessLock=new ue,this.dcBufferStatus=new Map([[B.RELIABLE,!0],[B.LOSSY,!0],[B.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(P.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(P.SignalRequestResponse,i),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onJoined=i=>this.emit(P.Joined,i),this.on(P.Closing,()=>{var i,r;(r=(i=this.bufferStatusLowClosingFuture).reject)===null||r===void 0||r.call(i,new ee("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,i,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var u,h,p;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();const v=!l&&vh();let g;if(v){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());const S=yield(u=c.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(g=_t(S.offer,S.offerId))}if(d!=null&&d.aborted)throw L.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,L.serviceNotFound("Simulated v1 path failure","v0-rtc");const T=yield c.client.join(s,a,o,d,l,g);c._isClosed=!1,c.latestJoinResponse=T,c.participantSid=(h=T.participant)===null||h===void 0?void 0:h.sid,c.subscriberPrimary=T.subscriberPrimary,v?(p=c.pcManager)===null||p===void 0||p.updateConfiguration(c.makeRTCConfiguration(T)):(c.pcManager||(yield c.configure(T,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||T.fastPublish)&&c.negotiate().catch(S=>{c.log.error(S)})),c.registerOnLineListener(),c.clientConfiguration=T.clientConfiguration,c.emit(P.SignalConnected,T);let k=T.serverInfo;return k||(k={version:T.serverVersion,region:T.serverRegion}),c.log.info("connected to Livekit Server ".concat(Object.entries(k).map(S=>{let x=N(S,2),b=x[0],y=x[1];return"".concat(b,": ").concat(y)}).join(", "))),{joinResponse:T,serverInfo:k}}catch(v){if(v instanceof L){if(v.reason===J.ServerUnreachable){if(c.log.warn("Couldn't connect to server, attempt ".concat(c.joinAttempts," of ").concat(c.maxJoinAttempts)),c.joinAttempts<c.maxJoinAttempts)return c.join(s,a,o,d,l)}else if(v.reason===J.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(v.message," – Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,d,!0)}throw v}})()})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;const t=i=>{i&&(i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null,i.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,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 da,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 m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new $e("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(L.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return m(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==te.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ga(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{const r=this.makeRTCConfiguration();this.pcManager=new ga("publisher-only",this.loggerOptions,r)}this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===te.CONNECTED){const c=this.pcState===Me.New;this.pcState=Me.Connected,c&&this.emit(P.Connected,this.latestJoinResponse)}else r===te.FAILED&&(this.pcState===Me.Connected||this.pcState===Me.Reconnecting)&&(this.pcState=Me.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Tt.RR_SUBSCRIBER_FAILED:Tt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===z.RECONNECTING,d=[te.FAILED,te.CLOSING,te.CLOSED].includes(r);o&&d&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(P.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>m(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)=>m(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(P.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(P.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(P.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(P.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Tt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e==null?void 0:e.action,")"),{reason:e==null?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(P.ServerRegionsReported,e.regions)),e.action){case Vt.DISCONNECT:this.emit(P.Disconnected,e==null?void 0:e.reason),this.close();break;case Vt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ar);break;case Vt.RESUME:this.handleDisconnect(ar)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Ci())&&rs()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gi.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),He()||this.addMediaSections(_p,Pp)}addMediaSections(e,t){var i,r;const s={direction:"recvonly"};for(let a=0;a<e;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",s);for(let a=0;a<t;a++)(r=this.pcManager)===null||r===void 0||r.addPublisherTransceiverOfKind("video",s)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ta,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Sa,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Ca,{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.onclose=this.handleDataChannelClose(B.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(B.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(B.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(B.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(B.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(B.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(B.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,Cp),Ep)}},1e3))}createSender(e,t,i){return m(this,void 0,void 0,function*(){let r;if(an())r=yield this.createTransceiverRTCRtpSender(e,t,i);else if(Rr())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new ee("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,i,r){return m(this,void 0,void 0,function*(){let s;if(an())s=yield this.createSimulcastTransceiverSender(e,t,i,r);else if(Rr())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new ee("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,i),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r,s;const a=this.frameMetadataWorker;if(!a||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;const o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,d=cn(o);if(Ci()){d&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Ei((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){d&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const c=e.createEncodedStreams(),l=c.readable,u=c.writable;d?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:u,packetTrailer:o}},[l,u]):l.pipeTo(u)}createTransceiverRTCRtpSender(e,t,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),ot(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===gi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof ee?(this.log.debug("received unrecoverable error",{error:s}),a=!1):s instanceof Ut||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Tt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new ee("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new Ut;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof L&&a.reason===J.NotAllowed?new ee("could not reconnect, token might be expired"):new Ut}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==z.CONNECTED)throw new Ut("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(s){const a=yield(i=this.regionStrategy)===null||i===void 0?void 0:i.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ee("could not reconnect, url or token not saved");if(!this.pcManager)throw new ee("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(P.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof L&&r.reason===J.NotAllowed?new ee("could not reconnect, token might be expired"):r instanceof L&&r.reason===J.LeaveRequest?r:new Ut(s)}if(this.emit(P.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==z.CONNECTED)throw new Ut("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Me.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield ge(Tp),!this.pcManager)throw new ee("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Me.Connected}catch(e){throw this.pcState=Me.Disconnected,L.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const i=new fe({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcAck",value:new gn({requestId:t})}});yield this.sendDataPacket(i,B.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){var i,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=Mh(e);if(o){const d=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new oo({encryptedValue:d.payload,iv:d.iv,keyIndex:d.keyIndex})}}}t===B.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const s=e.toBinary(),a=Math.min((r=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&r!==void 0?r:Ea,Ea);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new Bu("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));switch(t){case B.LOSSY:case B.DATA_TRACK_LOSSY:return this.sendLossyBytes(s,t);case B.RELIABLE:const o=this.dataChannelForKind(t);if(o){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:s,sequence:e.sequence}),this.attemptingReconnect)return;o.send(s)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"drop";return(function*(){yield s.ensurePublisherConnected(r);const o=s.dataChannelForKind(r);if(o){if(!s.isBufferStatusLow(r))switch(a){case"wait":yield s.waitForBufferStatusLow(r);break;case"drop":s.lossyDataDropCount+=1,s.lossyDataDropCount%100===0&&s.log.warn("dropping lossy data channel messages, total dropped: ".concat(s.lossyDataDropCount));return}if(s.lossyDataStatCurrentBytes+=i.byteLength,s.attemptingReconnect)return;o.send(i)}s.updateAndEmitDCBufferStatus(r)})()})}resendReliableMessagesForResume(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(B.RELIABLE);const t=this.dataChannelForKind(B.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(B.RELIABLE)})}waitForBufferStatusLow(e){return m(this,void 0,void 0,function*(){return new ke((t,i)=>m(this,void 0,void 0,function*(){if(this.isClosed&&i(new ee("engine closed")),this.isBufferStatusLow(e))t();else{const r=this.dataChannelForKind(e);if(!r){i(new ee("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(s=>i(s)),r.addEventListener("bufferedamountlow",()=>t(),{once:!0})}}))})}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new ee("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw L.internal("".concat(o," connection not set"));let d=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),d=!0),!d&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&i.negotiate().catch(u=>{i.log.error(u)});const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ge(50)}throw L.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![te.CONNECTING,te.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new ke((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Rt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new Rt("cannot negotiate on closed engine")),this.on(P.Closing,r),this.on(P.Restarting,r),this.pcManager.publisher.off(pt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(pt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(s){if(i.signal.aborted){e();return}s instanceof Rt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Tt.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(P.Closing,r),this.off(P.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case B.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case B.LOSSY:return t?this.lossyDCSub:this.lossyDC;case B.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,i){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const d=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),h=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,p=new Array,v=new Array;e.forEach(g=>{g.isDesired!==h&&p.push(g.trackSid),g.isEnabled||v.push(g.trackSid)}),this.client.sendSyncState(new Zr({answer:this.pcManager.mode==="publisher-only"?c?_t({sdp:c.sdp,type:c.type}):void 0:u?_t({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?d?_t({sdp:d.sdp,type:d.type}):void 0:l?_t({sdp:l.sdp,type:l.type}):void 0,subscription:new Cn({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:Gu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:v,datachannelReceiveStates:this.reliableReceivedState.map((g,T)=>new No({publisherSid:T,lastSeq:g})),publishDataTracks:i.map(g=>new zr({info:dn.toProtobuf(g)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Lo({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(B.LOSSY),Ue.PUBLISHER),t(this.dataChannelForKind(B.RELIABLE),Ue.PUBLISHER),t(this.dataChannelForKind(B.LOSSY,!0),Ue.SUBSCRIBER),t(this.dataChannelForKind(B.RELIABLE,!0),Ue.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ae.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_e()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){_e()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(s=>N(s,1)[0]===i);if(r)return r[1]}}}function _a(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}const xr=5e3,Rp=3e4;class W{static fetchRegionSettings(e,t,i){return m(this,void 0,void 0,function*(){const r=yield W.fetchLock.lock();try{const s=yield fetch("".concat(Ip(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(s.ok){const a=gh(s.headers),o=a?a*1e3:xr;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?L.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):L.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof L?s:i!=null&&i.aborted?L.cancelled("Region fetching was aborted"):L.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,i){return m(this,void 0,void 0,function*(){const r=W.settingsTimeouts.get(e.hostname);clearTimeout(r),W.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const s=yield W.fetchRegionSettings(e,t);W.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof L&&s.reason===J.NotAllowed){U.debug("token is not valid, cancelling auto region refresh");return}U.debug("auto refetching of region settings failed",{error:s}),W.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){W.cache.set(e.hostname,i),W.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=W.settingsTimeouts.get(e);t&&(clearTimeout(t),W.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=W.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=W.connectionTrackers.get(e);i&&i.connectionCount===0&&(U.debug("stopping region refetch after disconnect delay",{hostname:e}),W.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Rp))}static cancelCleanup(e){const t=W.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=W.connectionTrackers.get(e);t||(t={connectionCount:0},W.connectionTrackers.set(e,t)),t.connectionCount++,W.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=W.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&W.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),r=W.cache.get(i.hostname);W.scheduleRefetch(this.serverUrl,this.token,(t=r==null?void 0:r.maxAgeInMs)!==null&&t!==void 0?t:xr)}isCloud(){return Yt(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return W.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=W.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),W.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),U.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){W.updateCachedRegionSettings(this.serverUrl,this.token,e)}}W.cache=new Map;W.settingsTimeouts=new Map;W.connectionTrackers=new Map;W.fetchLock=new ue;function Ip(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class jc{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new De("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),be.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new De("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),be.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Mp extends jc{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){try{const i=this.signal;if(i!=null&&i.aborted)throw i.reason;const r=yield new Promise((s,a)=>{if(i){const o=()=>a(i.reason);i.addEventListener("abort",o,{once:!0}),e.read().then(s,a).finally(()=>{i.removeEventListener("abort",o)})}else e.read().then(s,a)});return r.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(i){throw t(),i}}),return(){return m(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o=new Set;const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Fe(d),u;u=yield l.next(),i=u.done,!i;c=!0){a=u.value,c=!1;const h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}}class Dp extends jc{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Qi(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){try{if(i!=null&&i.aborted)throw i.reason;const s=yield new Promise((a,o)=>{if(i){const d=()=>o(i.reason);i.addEventListener("abort",d,{once:!0}),e.read().then(a,o).finally(()=>{i.removeEventListener("abort",d)})}else e.read().then(a,o)});if(s.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(s.value);let a;try{a=t.decode(s.value.content)}catch(o){throw new De("Cannot decode datastream chunk ".concat(s.value.chunkIndex," as text: ").concat(o),be.DecodeFailed)}return{done:!1,value:a}}}catch(s){throw r(),s}}),return(){return m(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o="";const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Fe(d),u;u=yield l.next(),i=u.done,!i;c=!0)a=u.value,c=!1,o+=a}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}}class Op{constructor(){this.log=U,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new De('A text stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new De('A byte stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const a=new De("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),be.AbnormalEnd);for(const o of i){var r=N(o,2);const d=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(d)}for(const o of t){var s=N(o,2);const d=s[0];s[1].controller.error(a),this.textStreamControllers.delete(d)}}}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 new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,i){var r;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Qi(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new De("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new Mp(o,d,Qi(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new De("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new Dp(o,d,Qi(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new De("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),be.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new De("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new De("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),be.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new De("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Wc{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 m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ap extends Wc{}class Np extends Wc{}const Pa=15e3;class Lp{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return m(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),d=new Array(o?o.length+1:1).fill(0),c=(u,h)=>{var p;d[h]=u;const v=d.reduce((g,T)=>g+T,0);(p=t==null?void 0:t.onProgress)===null||p===void 0||p.call(t,v)},l=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield l.write(e),c(1,0),yield l.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>m(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:p=>{c(p,h+1)}})})))),l.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,i,r;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?Q.GCM:Q.NONE,attachedStreamIds:e==null?void 0:e.attachedStreamIds},o=new en({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:St(a.timestamp),totalLength:St(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new To({version:e==null?void 0:e.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?ur.UPDATE:ur.CREATE})}}),d=e==null?void 0:e.destinationIdentities,c=new fe({destinationIdentities:d,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,B.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(g){return m(this,void 0,void 0,function*(){for(const T of fh(g,Pa)){const k=new tn({content:T,streamId:s,chunkIndex:St(l)}),S=new fe({destinationIdentities:d,value:{case:"streamChunk",value:k}});yield u.sendDataPacket(S,B.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){const g=new nn({streamId:s}),T=new fe({destinationIdentities:d,value:{case:"streamTrailer",value:g}});yield u.sendDataPacket(T,B.RELIABLE)})},abort(g){}});let p=()=>m(this,void 0,void 0,function*(){yield v.close()});u.once(P.Closing,p);const v=new Ap(h,a,()=>this.engine.off(P.Closing,p));return v})}sendFile(e,t){return m(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return m(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const o=yield a.read(),d=o.done,c=o.value;if(d)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?Q.GCM:Q.NONE},l=new en({totalLength:St(c.size),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:St(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new So({name:c.name})}}),u=new fe({destinationIdentities:d,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,B.RELIABLE);let h=0;const p=new ue,v=this.engine,g=this.log,T=new WritableStream({write(S){return m(this,void 0,void 0,function*(){const x=yield p.lock();let b=0;try{for(;b<S.byteLength;){const y=S.slice(b,b+Pa),_=new fe({destinationIdentities:d,value:{case:"streamChunk",value:new tn({content:y,streamId:o,chunkIndex:St(h)})}});yield v.sendDataPacket(_,B.RELIABLE),h+=1,b+=y.byteLength}}finally{x()}})},close(){return m(this,void 0,void 0,function*(){const S=new nn({streamId:o}),x=new fe({destinationIdentities:d,value:{case:"streamTrailer",value:S}});yield v.sendDataPacket(x,B.RELIABLE)})},abort(S){g.error("Sink error:",S)}});return new Np(T,c)})}}function Hc(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(const r of n)if(r.aborted)return r;const e=new AbortController,t=Array(n.length),i=()=>{for(const r of t)r()};return n.forEach((r,s)=>{const a=()=>{e.abort(r.reason),i()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function Kc(n){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}const ne=1,tt=2,wa=4,xp=8,Ra=0,Ia=12,Ma=5,Up=7,Da=3,Fp=3,Oa=2,Aa=1,Na=0,La=3,Li=2,xa=2,Bp=1,qp=0;var nt;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(nt||(nt={}));class ye extends Oe{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=nt[t]}static tooShort(){return new ye("Too short to contain a valid header",nt.TooShort)}static headerOverrun(){return new ye("Header exceeds total packet length",nt.HeaderOverrun)}static missingExtWords(){return new ye("Extension word indicator is missing",nt.MissingExtWords)}static unsupportedVersion(e){return new ye("Unsupported version ".concat(e),nt.UnsupportedVersion)}static invalidHandle(e){return new ye("invalid track handle: ".concat(e.message),nt.InvalidHandle,{cause:e})}static malformedExt(e){return new ye("Extension with tag ".concat(e," is malformed"),nt.MalformedExt)}}var pi;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(pi||(pi={}));class wi extends Oe{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=pi[t]}static tooSmallForHeader(){return new wi("Buffer cannot fit header",pi.TooSmallForHeader)}static tooSmallForPayload(){return new wi("Buffer cannot fit payload",pi.TooSmallForPayload)}}class Rn{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),r=this.toBinaryInto(i);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var Xt;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Xt||(Xt={}));class Gc extends Rn{}class qe extends Gc{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return ne+ne+qe.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,qe.tag),t+=ne,e.setUint8(t,qe.lengthBytes),t+=ne,e.setBigUint64(t,this.timestamp),t+=xp;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:qe.tag,lengthBytes:qe.lengthBytes,timestamp:this.timestamp}}}qe.tag=Xt.UserTimestamp;qe.lengthBytes=8;class Ve extends Gc{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return ne+ne+Ve.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Ve.tag),t+=ne,e.setUint8(t,Ve.lengthBytes),t+=ne,e.setUint8(t,this.keyIndex),t+=ne;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=ne;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Ve.tag,lengthBytes:Ve.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Ve.tag=Xt.E2ee;Ve.lengthBytes=13;class Gt extends Rn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){const r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=ds(e);let i,r,s=0;for(;t.byteLength-s>=ne+ne;){const a=t.getUint8(s);s+=ne;const o=t.getUint8(s);if(s+=ne,a!==qp)switch(a){case Xt.UserTimestamp:if(t.byteLength-s<qe.lengthBytes)throw ye.malformedExt(a);i=new qe(t.getBigUint64(s)),s+=o;break;case Xt.E2ee:if(t.byteLength-s<Ve.lengthBytes)throw ye.malformedExt(a);const d=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let u=s;u+=ne,u+=l*ne,c[l]=t.getUint8(u)}r=new Ve(d,c),s+=o;break;default:if(t.byteLength-s<o)throw ye.malformedExt(a);s+=o;break}}return[new Gt({userTimestamp:i,e2ee:r}),t.byteLength]}toJSON(){var e,t,i,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&r!==void 0?r:null}}}const zc={from(n){return{payload:n.payload,extensions:new Gt({userTimestamp:n.userTimestamp?new qe(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},Jc=Symbol.for("lk.track"),Qc=Symbol.for("lk.data-track");class Yc{constructor(e,t,i){this.trackSymbol=Jc,this.isLocal=!1,this.typeSymbol=Qc,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e==null?void 0:e.signal,e==null?void 0:e.bufferSize),i=N(t,2),r=i[0];return i[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Ri extends Rn{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=(t=e.extensions)!==null&&t!==void 0?t:new Gt}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((Li+e)/4),i=t*4-Li-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let r=Ia;return t>0&&(r+=Li+t+i),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw wi.tooSmallForHeader();let t=Ra<<Ma,i;switch(this.marker){case Y.Inter:i=Na;break;case Y.Final:i=Aa;break;case Y.Start:i=Oa;break;case Y.Single:i=La;break}t|=i<<Da;const r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<xa);let d=0;if(e.setUint8(d,t),d+=ne,e.setUint8(d,0),d+=ne,e.setUint16(d,this.trackHandle),d+=tt,e.setUint16(d,this.sequence.value),d+=tt,e.setUint16(d,this.frameNumber.value),d+=tt,e.setUint32(d,this.timestamp.asTicks()),d+=wa,s>0){const l=a-1;e.setUint16(d,l),d+=tt;const u=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+d));d+=u;for(let h=0;h<o;h+=1)e.setUint8(d,0),d+=ne}const c=this.toBinaryLengthBytes();if(d!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=ds(e);if(t.byteLength<Ia)throw ye.tooShort();let i=0;const r=t.getUint8(i);i+=ne;const s=r>>Ma&Up;if(s>Ra)throw ye.unsupportedVersion(s);let a;switch(r>>Da&Fp){case Oa:a=Y.Start;break;case Aa:a=Y.Final;break;case La:a=Y.Single;break;case Na:default:a=Y.Inter;break}const o=(r>>xa&Bp)>0;i+=ne;let d;try{d=qh.fromNumber(t.getUint16(i))}catch(p){throw p instanceof $t&&(p.isReason(Dt.Reserved)||p.isReason(Dt.TooLarge))?ye.invalidHandle(p):p}i+=tt;const c=We.u16(t.getUint16(i));i+=tt;const l=We.u16(t.getUint16(i));i+=tt;const u=Kt.fromRtpTicks(t.getUint32(i));i+=wa;let h=new Gt;if(o){if(t.byteLength-i<tt)throw ye.missingExtWords();let p=t.getUint16(i);i+=tt;let g=4*(p+1)-Li;if(i+g>t.byteLength)throw ye.headerOverrun();let T=new DataView(t.buffer,t.byteOffset+i,g);const k=Gt.fromBinary(T),S=N(k,2),x=S[0],b=S[1];h=x,i+=b}return[new Ri({marker:a,trackHandle:d,sequence:c,frameNumber:l,timestamp:u,extensions:h}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var Y;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Y||(Y={}));class In extends Rn{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw wi.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=ne;const r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){const t=ds(e),i=Ri.fromBinary(t),r=N(i,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new In(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const or=Pe(he.DataTracks);class Xe extends Oe{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Pt[t],this.frameNumber=i}static interrupted(e,t){return new Xe("Interrupted by the start of a new frame ".concat(t),Pt.Interrupted,e)}static unknownFrame(e){return new Xe("Initial packet was never received.",Pt.UnknownFrame,e)}static bufferFull(e){return new Xe("Reorder buffer is full.",Pt.BufferFull,e)}static incomplete(e,t,i){return new Xe("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),Pt.Incomplete,e)}}var Pt;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(Pt||(Pt={}));class Mn{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Y.Single:return this.frameFromSingle(e,t);case Y.Start:return this.beginPartial(e,t);case Y.Inter:case Y.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==Y.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const r=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){const s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t!=null&&t.throwOnInterruption)throw Xe.interrupted(s,e.header.frameNumber.value);or.warn("Data track frame ".concat(s," 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!==Y.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){const d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t!=null&&t.throwOnInterruption)throw Xe.interrupted(d,s);or.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(d," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==Y.Inter&&e.header.marker!==Y.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),Xe.unknownFrame(t);if(i.payloads.size>=Mn.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Xe.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&or.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===Y.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const r=t.payloads.size;let s=0;for(const c of t.payloads.values())s+=c.length;const a=new Uint8Array(s);let o=t.startSequence.clone(),d=0;for(;;){const c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);const l=a.length-d;if(c.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(c.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(c,d),d+=c.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Xe.incomplete(e,r,i-t.startSequence.value+1)}}Mn.MAX_BUFFER_PACKETS=128;var wt;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(wt||(wt={}));class Ce extends Oe{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=wt[t]}static unpublished(){return new Ce("The track has been unpublished and is no longer available",wt.Unpublished)}static timeout(){return new Ce("Request to subscribe to data track timed-out",wt.Timeout)}static disconnected(){return new Ce("Cannot subscribe to data track when disconnected",wt.Disconnected)}static cancelled(){return new Ce("Subscription to data track cancelled by caller",wt.Cancelled)}}const cr=Pe(he.DataTracks);class Vp{constructor(e){var t,i;const r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const s=new Mn;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return m(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return cr.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return m(this,void 0,void 0,function*(){var t,i;const r=this.e2eeManager;if(!r)return e;const s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return cr.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return cr.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const pe=Pe(he.DataTracks),jp=1e4,Wp=16;class Hp extends we.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);if(!i){pe.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Wp,r=null;const s=new le,a=()=>{t==null||t.removeEventListener("abort",d)},o=()=>{if(a(),!r){pe.warn("ReadableStream subscribed to ".concat(e," was not started."));return}const l=this.descriptors.get(e);if(!l){pe.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(l.subscription.type!=="active"){pe.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}l.subscription.streamControllers.delete(r),l.subscription.streamControllers.size===0&&this.unSubscribeRequest(l.info.sid)},d=()=>{var l;if(!r)return;const u=this.descriptors.get(e);(u==null?void 0:u.subscription.type)==="active"&&u.subscription.streamControllers.delete(r),r.error(Ce.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,Ce.cancelled()),o()};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>m(this,void 0,void 0,function*(){var u,h,p;const v=this.descriptors.get(e);if(!v){pe.error("Unknown track ".concat(e));const g=Ce.disconnected();l.error(g),(u=s.reject)===null||u===void 0||u.call(s,g);return}if(v.subscription.type!=="active"){pe.error("Subscription for track ".concat(e," is not active"));const g=Ce.disconnected();l.error(g),(h=s.reject)===null||h===void 0||h.call(s,g);return}if(t!=null&&t.aborted){d();return}t==null||t.addEventListener("abort",d),v.subscription.streamControllers.set(l,a),(p=s.resolve)===null||p===void 0||p.call(s)})).catch(u=>{var h;l.error(u),(h=s.reject)===null||h===void 0||h.call(s,u)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return m(this,void 0,void 0,function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const r=(s,a,o)=>m(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));const d=Hc([a,o].filter(u=>typeof u<"u")),c=new le;s.subscription.completionFuture.promise.then(()=>{var u;return(u=c.resolve)===null||u===void 0?void 0:u.call(c)}).catch(u=>{var h;return(h=c.reject)===null||h===void 0?void 0:h.call(c,u)});const l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o!=null&&o.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(u=c.reject)===null||u===void 0||u.call(c,Ce.cancelled())}};d.aborted&&l(),d.addEventListener("abort",l),yield c.promise,d.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new le,pendingRequestCount:1,cancel:()=>{var a,o;const d=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),d.type==="pending"&&((o=(a=d.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?Ce.timeout():Ce.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const s=Kc(jp);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){pe.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);const r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var i=N(r,2);const s=i[0],a=i[1];a();try{s.close()}catch(o){pe.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return m(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const s of e.entries()){var i=N(s,2);const a=i[0],o=i[1],d=new Set;for(const c of o)d.add(c.sid),!this.descriptors.has(c.sid)&&(yield this.handleTrackPublished(a,c));t.set(a,d)}for(const s of t.entries()){var r=N(s,2);const a=r[0],o=r[1];let c=Array.from(this.descriptors.entries()).filter(l=>{let u=N(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>N(l,1)[0]).filter(l=>!o.has(l));for(const l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return m(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){pe.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);const r=new Yc(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){pe.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=N(i,2);const r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;const s=this.descriptors.get(t);if(!s){pe.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{pe.warn("No subscription for ".concat(t));return}case"active":{s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{const a=new Vp({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return m(this,void 0,void 0,function*(){let t;try{var i=In.fromBinary(e),r=N(i,1);t=r[0]}catch(d){pe.error("Failed to deserialize packet: ".concat(d));return}const s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){pe.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(s);if(!a){pe.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){pe.warn("Received packet for track ".concat(s," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const d of a.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){pe.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(d.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const c=zc.lossyIntoFrame(o);d.enqueue(c)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=N(t,2);const i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,Ce.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,Ce.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Dn extends Oe{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=un[t]}static mtuTooShort(){return new Dn("MTU is too short to send frame",un.MtuTooShort)}}var un;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(un||(un={}));class fs{constructor(e,t){this.sequence=We.u16(0),this.frameNumber=We.u16(0),this.clock=Et.rtpStartingNow(Kt.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Y.Single:e===0?Y.Start:e===t-1?Y.Final:Y.Inter}*packetize(e,t){var i;const r=this.frameNumber.getThenIncrement(),s={marker:Y.Inter,trackHandle:this.handle,sequence:We.u16(0),frameNumber:r,timestamp:(i=t==null?void 0:t.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new Ri(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Dn.mtuTooShort();const o=this.mtuSizeBytes-a,d=Math.ceil(e.payload.byteLength/o);for(let l=0,u=0;u<e.payload.byteLength;c=[l+1,u+o],l=c[0],u=c[1],c){var c;const h=this.sequence.getThenIncrement(),p=new Ri(Object.assign(Object.assign({},s),{marker:fs.computeFrameMarker(l,d),sequence:h})),v=Math.min(o,e.payload.byteLength-u),g=new Uint8Array(e.payload.buffer,e.payload.byteOffset+u,v);yield new In(p,g)}}}var Ne;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(Ne||(Ne={}));class oe extends Oe{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Ne[t],this.rawMessage=i==null?void 0:i.rawMessage}static notAllowed(e){return new oe("Data track publishing unauthorized",Ne.NotAllowed,{rawMessage:e})}static duplicateName(e){return new oe("Track name already taken",Ne.DuplicateName,{rawMessage:e})}static invalidName(e){return new oe("Track name is invalid",Ne.InvalidName,{rawMessage:e})}static timeout(){return new oe("Publish data track timed-out. Does the LiveKit server support data tracks?",Ne.Timeout)}static limitReached(e){return new oe("Data track publication limit reached",Ne.LimitReached,{rawMessage:e})}static unknown(e,t){return new oe("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Ne.Unknown)}static disconnected(){return new oe("Room disconnected",Ne.Disconnected)}static cancelled(){return new oe("Publish data track cancelled by caller",Ne.Cancelled)}}var mi;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(mi||(mi={}));class mt extends Oe{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=mi[t]}static trackUnpublished(){return new mt("Track is no longer published",mi.TrackUnpublished)}static dropped(e){return new mt("Frame was dropped",mi.Dropped,{cause:e})}}var fi;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(fi||(fi={}));class Ii extends Oe{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=fi[t]}static packetizer(e){return new Ii("Error packetizing frame",fi.Packetizer,{cause:e})}static encryption(e){return new Ii("Error encrypting frame",fi.Encryption,{cause:e})}}class On{constructor(e,t){this.trackSymbol=Jc,this.isLocal=!0,this.typeSymbol=Qc,this.handle=null,this.log=U,this.flushedFuture=new le,this.isFlushed=!0,this.handleManagerReset=()=>{var i,r;(r=(i=this.flushedFuture).resolve)===null||r===void 0||r.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var r,s;this.isFlushed=i.isFlushed,i.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new le)},this.options=e,this.manager=t,this.log=Pe(he.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const r=new On(e,t);return r.handle=i,r}get info(){const e=this.descriptor;if((e==null?void 0:e.type)==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return m(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw mt.trackUnpublished();const t=zc.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return m(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return m(this,void 0,void 0,function*(){if(!this.handle){U.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 An{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new fs(e.info.pubHandle,An.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return ku(this,arguments,function*(){const i=yield Qt(this.encryptIfNeeded(e));try{yield Qt(yield*Tu(Fe(this.packetizer.packetize(i))))}catch(r){throw r instanceof Dn?Ii.packetizer(r):r}})}encryptIfNeeded(e){return m(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Ii.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new Ve(t.keyIndex,t.iv),e})}}An.TRANSPORT_MTU_BYTES=16e3;const Je=Pe(he.DataTracks),Ua={pending(){return{type:"pending",completionFuture:new le}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new An({info:n,e2eeManager:e}),unpublishingFuture:new le}}},Kp=1e4;class gs extends we.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Vh,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new gs;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return m(this,void 0,void 0,function*(){var i,r,s,a,o;const d=this.getDescriptor(e);if((d==null?void 0:d.type)!=="active"||d.publishState==="unpublished")throw mt.trackUnpublished();if(d.publishState==="republishing")throw mt.dropped("Data track republishing");try{try{for(var c=!0,l=Fe(d.pipeline.processFrame(t)),u;u=yield l.next(),i=u.done,!i;c=!0){a=u.value,c=!1;const h=a,p=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,p+1),p===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw mt.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(Je.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return m(this,void 0,void 0,function*(){const i=this.handleAllocator.get();if(!i)throw oe.limitReached();const r=Kc(Kp),s=t?Hc([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const a=Ua.pending();this.descriptors.set(i,a);const o=()=>{var d,c;const l=this.descriptors.get(i);if(!l){Je.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((c=(d=l.completionFuture).reject)===null||c===void 0||c.call(d,r.aborted?oe.timeout():oe.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:On.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return m(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){Je.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Je.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,r,s,a;const o=this.descriptors.get(e);if(!o){Je.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const d=t.data,c=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,Ua.active(d,c)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){Je.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Je.warn("Republish failed for track ".concat(e));return}Je.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;const r=this.descriptors.get(e);if(!r){Je.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){Je.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(const r of this.descriptors.entries()){var i=N(r,2);const s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,oe.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return m(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(const s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,oe.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class K extends Error{constructor(e,t,i,r){super(t),this.code=e,this.message=Fa(t,K.MAX_MESSAGE_BYTES),this.data=i?Fa(i,K.MAX_DATA_BYTES):void 0,typeof(r==null?void 0:r.cause)<"u"&&(this.cause=r==null?void 0:r.cause)}static fromProto(e){return new K(e.code,e.message,e.data)}toProto(){return new ho({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new K(K.ErrorCode[e],K.ErrorMessage[e],t,i)}}K.MAX_MESSAGE_BYTES=256;K.MAX_DATA_BYTES=15360;K.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};K.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const $c=15360,Xc="lk.rpc_request",Zc="lk.rpc_response";var me;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="lk.rpc_request_version"})(me||(me={}));const Gp=1,ed=2;function vs(n){return new TextEncoder().encode(n).length}function Fa(n,e){if(vs(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}class zp extends we.EventEmitter{constructor(e,t,i,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=r}performRpc(e){return m(this,arguments,void 0,function(t){var i=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,d=o===void 0?15e3:o;return(function*(){const u=i.getRemoteParticipantClientProtocol(r);if(vs(a)>$c&&u<rn)throw K.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const p=i.getServerVersion();if(p&&et(p,"1.8.0")<0)throw K.builtIn("UNSUPPORTED_SERVER");const v=Math.max(d,8e3),g=crypto.randomUUID(),T=new le;let k=null;const S=setTimeout(()=>{var b;i.pendingAcks.delete(g),(b=T.reject)===null||b===void 0||b.call(T,K.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(g),k!==null&&clearTimeout(k)},7e3);i.pendingAcks.set(g,{resolve:()=>{clearTimeout(S)},participantIdentity:r}),i.pendingResponses.set(g,{completionFuture:T,participantIdentity:r}),yield i.publishRpcRequest(r,g,s,a,v,u),k=setTimeout(()=>{var b;i.pendingResponses.delete(g),(b=T.reject)===null||b===void 0||b.call(T,K.builtIn("RESPONSE_TIMEOUT"))},d);const x=T.promise.finally(()=>{clearTimeout(k),i.pendingAcks.has(g)&&(i.log.warn("RPC response received before ack",g),i.pendingAcks.delete(g),clearTimeout(S))});return[g,x]})()})}publishRpcRequest(e,t,i,r,s,a){return m(this,void 0,void 0,function*(){if(a>=rn){const o=yield this.outgoingDataStreamManager.streamText({topic:Xc,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t,[me.RPC_REQUEST_METHOD]:i,[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[me.RPC_REQUEST_VERSION]:"".concat(ed)}});yield o.write(r),yield o.close();return}this.emit("sendDataPacket",{packet:new fe({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcRequest",value:new Hr({id:t,method:i,payload:r,responseTimeoutMs:s,version:Gp})}})})})}handleIncomingDataStream(e,t,i){return m(this,void 0,void 0,function*(){const r=i[me.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," not set."));return}const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,K.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).resolve)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).reject)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var i=N(a,2);const o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var r=N(a,2);const o=r[0];var s=r[1];const d=s.participantIdentity,c=s.completionFuture;d===e&&((t=c.reject)===null||t===void 0||t.call(c,K.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class Jp extends we.EventEmitter{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 m(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,K.builtIn("UNSUPPORTED_VERSION"));return}const r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,K.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof K?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=K.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a==null?void 0:a.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,i){return m(this,void 0,void 0,function*(){const r=i[me.RPC_REQUEST_ID],s=i[me.RPC_REQUEST_METHOD],a=parseInt(i[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[me.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," / ").concat(me.RPC_REQUEST_METHOD," / ").concat(me.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(me.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,K.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==ed){this.publishRpcResponsePacket(t,r,null,K.builtIn("UNSUPPORTED_VERSION"));return}let d;try{d=yield e.readAll()}catch(u){this.log.warn("Error reading RPC request payload: ".concat(u)),this.publishRpcResponsePacket(t,r,null,K.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:u}));return}const c=this.rpcHandlers.get(s);if(!c){this.publishRpcResponsePacket(t,r,null,K.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:d,responseTimeout:a})}catch(u){let h;u instanceof K?h=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),u),h=K.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,h);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new fe({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcAck",value:new gn({requestId:t})}})})}publishRpcResponsePacket(e,t,i,r){this.emit("sendDataPacket",{packet:new fe({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcResponse",value:new Kr({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return m(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=rn){const a=yield this.outgoingDataStreamManager.streamText({topic:Zc,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t}});yield a.write(i),yield a.close();return}if(vs(i)>$c){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,K.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class Qp extends Ac{constructor(e,t,i,r,s,a){super(e,t,C.Kind.Audio,i,a),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=wn(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;He()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(He())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(on(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&on(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,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(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(R.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(R.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}class rt extends we.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Q.NONE,this.log=U,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},this.log=Pe((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:he.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.Source.Unknown}setTrack(e){this.track&&(this.track.off(R.Muted,this.handleMuted),this.track.off(R.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(R.Muted,this.handleMuted),e.on(R.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Q.NONE}get audioTrack(){if(Ze(this.track))return this.track}get videoTrack(){if(ot(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(rt||(rt={}));class Ur extends rt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(R.Ended)},this.handleCpuConstrained=()=>{this.track&&ot(this.track)&&this.emit(R.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(R.Ended,this.handleTrackEnded),this.track.off(R.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(R.Ended,this.handleTrackEnded),e.on(R.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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ze(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ce.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ce.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ce.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ce.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ce.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ce.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Nn(n,e){return m(this,void 0,void 0,function*(){n??(n={});let t=!1;const i=Ec(n),r=i.audioProcessor,s=i.videoProcessor,a=i.optionsWithoutProcessor;let o=a.audio,d=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const h=a.audio.deviceId;a.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:h}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const h=a.video.deviceId;a.video.deviceId={exact:h},t=!0,d=Object.assign(Object.assign({},a.video),{deviceId:{ideal:h}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const c=Tc(a,xc,Uc),l=ts(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(de.userMediaPromiseMap.set("audioinput",u),u.catch(()=>de.userMediaPromiseMap.delete("audioinput"))),a.video&&(de.userMediaPromiseMap.set("videoinput",u),u.catch(()=>de.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(p=>m(this,void 0,void 0,function*(){const v=p.kind==="audio";let g;const T=v?l.audio:l.video;typeof T!="boolean"&&(g=T);const k=p.getSettings().deviceId;g!=null&&g.deviceId&&It(g.deviceId)!==k?g.deviceId=k:g||(g={deviceId:k});const S=lp(p,g,e);return S.kind===C.Kind.Video?S.source=C.Source.Camera:S.kind===C.Kind.Audio&&(S.source=C.Source.Microphone),S.mediaStream=h,Ze(S)&&r?yield S.setProcessor(r):ot(S)&&s&&(yield S.setProcessor(s)),S})))}catch(h){if(!t)throw h;return Nn(Object.assign(Object.assign({},n),{audio:o,video:d}),e)}})}function Yp(n){return m(this,void 0,void 0,function*(){return(yield Nn({audio:!1,video:n??!0}))[0]})}function $p(n){return m(this,void 0,void 0,function*(){return(yield Nn({audio:n??!0,video:!1}))[0]})}function mf(n){return m(this,void 0,void 0,function*(){if(n===void 0&&(n={}),n.resolution===void 0&&!_c()&&(n.resolution=Pn.h1080fps30.resolution),navigator.mediaDevices.getDisplayMedia===void 0)throw new _n("getDisplayMedia not supported");const e=Cc(n),t=yield navigator.mediaDevices.getDisplayMedia(e),i=t.getVideoTracks();if(i.length===0)throw new $e("no video track found");const r=new Pi(i[0],void 0,!1);r.source=C.Source.ScreenShare;const s=[r];if(t.getAudioTracks().length>0){const a=new _i(t.getAudioTracks()[0],void 0,!1);a.source=C.Source.ScreenShareAudio,s.push(a)}return s})}var ut;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(ut||(ut={}));function Xp(n){switch(n){case ai.EXCELLENT:return ut.Excellent;case ai.GOOD:return ut.Good;case ai.POOR:return ut.Poor;case ai.LOST:return ut.Lost;default:return ut.Unknown}}class td extends we.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?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((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===vi.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===qt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:vi.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ut.Unknown,this.log=U,this.loggerOptions=a,this.log=Pe((d=a==null?void 0:a.loggerName)!==null&&d!==void 0?d:he.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const i of this.trackPublications){var t=N(i,2);const r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(const i of this.trackPublications){var t=N(i,2);const r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new le,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===qt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==qt.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ju(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const d=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(I.ParticipantPermissionsChanged,d),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Xp(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ze(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Zp(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Oo({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class em extends td{constructor(e,t,i,r,s,a,o,d){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Q.NONE,this.e2eeStateMutex=new ue,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new le)},this.handleReconnected=()=>{var c,l;(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.resolve)===null||l===void 0||l.call(c),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var c,l,u,h,p,v;this.reconnectFuture&&(this.reconnectFuture.promise.catch(g=>this.log.warn(g.message)),(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((h=(u=this.signalConnectedFuture).reject)===null||h===void 0||h.call(u,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(v=(p=this.activeAgentFuture)===null||p===void 0?void 0:p.reject)===null||v===void 0||v.call(p,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=c=>{var l,u;c.participant&&this.updateInfo(c.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new le),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=c=>{const l=c.requestId,u=c.reason,h=c.message,p=this.pendingSignalRequests.get(l);switch(p&&(u!==Ct.OK&&p.reject(new Ys(h,u)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let v;switch(c.reason){case Ct.NOT_ALLOWED:v=oe.notAllowed(c.message);break;case Ct.DUPLICATE_NAME:v=oe.duplicateName(c.message);break;case Ct.INVALID_NAME:v=oe.invalidName(c.message);break;case Ct.LIMIT_EXCEEDED:v=oe.limitReached(c.message);break;default:v=oe.unknown(c.reason,c.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(c.request.value.pubHandle,{type:"error",error:v});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(c=>Zp(c)))},this.onTrackUnmuted=c=>{this.onTrackMuted(c,c.isUpstreamPaused)},this.onTrackMuted=(c,l)=>{if(l===void 0&&(l=!0),!c.sid){this.log.error("could not update mute status for unpublished track",V(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",V(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",V(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{const l=this.audioTrackPublications.get(c.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(c.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(c,l)=>{this.log.debug("track cpu constrained",V(l)),this.emit(I.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>m(this,void 0,void 0,function*(){var l,u,h,p,v;if(!(!((v=this.roomOptions)===null||v===void 0)&&v.dynacast))return;const g=this.videoTrackPublications.get(c.trackSid);if(!g){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!g.videoTrack)return;const T=yield g.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var k=!0,S=Fe(T),x;x=yield S.next(),l=x.done,!l;k=!0){p=x.value,k=!1;const b=p;Hu(b)&&(this.log.debug("publish ".concat(b," for ").concat(g.videoTrack.sid),V(g)),yield this.publishAdditionalCodecForTrack(g.videoTrack,b,g.options))}}catch(b){u={error:b}}finally{try{!k&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=c=>{const l=this.trackPublications.get(c.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:c.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=c=>m(this,void 0,void 0,function*(){if(c.source===C.Source.ScreenShare||c.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",V(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(it(c)||ze(c))try{if(_e())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:c.source===C.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),V(c)),l.onchange=()=>{l.state!=="denied"&&(c.isMuted||c.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}c.isMuted||(this.log.debug("track ended, attempting to use a different device",V(c)),it(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",V(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=d}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Q.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var i=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new ke((o,d)=>m(i,void 0,void 0,function*(){var c,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:v=>{d(v),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(v=>{let g=N(v,2),T=g[0],k=g[1];return this.attributes[T]===k||k===""&&!this.attributes[T]}))){this.pendingSignalRequests.delete(h),o();return}yield ge(50)}d(new Ys("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?d(u):d(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(C.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(C.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?Q.GCM:Q.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,r){return m(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let u;if(this.pendingPublishing.has(e)){const h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h==null?void 0:h.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:u=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case C.Source.Microphone:u=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},i));break;default:throw new $e(e)}}catch(h){throw u==null||u.forEach(p=>{p.stop()}),h instanceof Error&&this.emit(I.MediaDevicesError,h,wr(e)),this.pendingPublishing.delete(e),h}for(const h of u){const p=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===C.Source.Microphone&&Ze(h)&&p.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{const h=[];for(const v of u)this.log.info("publishing track",V(v)),h.push(this.publishTrack(v,r));const p=yield Promise.all(h);var d=N(p,1);o=d[0]}catch(h){throw u==null||u.forEach(p=>{p.stop()}),h}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===C.Source.ScreenShare){const u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(C.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var c=yield Promise.all(u),l=N(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,i;e??(e={});const r=Tc(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Nn(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ze(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(I.AudioStreamAcquired)),ot(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new _n("getDisplayMedia not supported");e.resolution===void 0&&!_c()&&(e.resolution=Pn.h1080fps30.resolution);const t=Cc(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new $e("no video track found");const s=new Pi(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=C.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new _i(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{const r=()=>{clearTimeout(o),this.engine.off(P.Restarted,s),this.engine.off(P.Closing,a)},s=()=>{r(),t()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(P.Restarted,s),this.engine.once(P.Closing,a)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return(function*(){var d,c,l,u;it(i)&&i.setAudioContext(s.audioContext),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!a&&(yield s.republishPromise),Mt(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let h;if(i instanceof MediaStreamTrack)h=i.getConstraints();else{h=i.constraints;let S;switch(i.source){case C.Source.Microphone:S="audioinput";break;case C.Source.Camera:S="videoinput"}S&&s.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(S)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new _i(i,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Pi(i,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new $e("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let p;if(s.trackPublications.forEach(S=>{S.track&&S.track===i&&(p=S)}),p)return s.log.warn("track has already been published, skipping",V(p)),p;const v=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),g="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,T=(c=v.forceStereo)!==null&&c!==void 0?c:g;T&&(v.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",V(i)),v.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=v.dtx)!==null&&l!==void 0||(v.dtx=!1),(u=v.red)!==null&&u!==void 0||(v.red=!1)),!sh()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),v.simulcast=!1),v.source&&(i.source=v.source);const k=new Promise((S,x)=>m(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==z.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:V(i)});let b=!1;const y=setTimeout(()=>{b=!0,i.stop(),x(new Qs("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),b)return;const _=yield this.publish(i,v,T);S(_)}else try{const b=yield this.publish(i,v,T);S(b)}catch(b){x(b)}}catch(b){x(b)}}));s.pendingPublishPromises.set(i,k);try{return yield k}catch(S){if(!o&&S instanceof Rt)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),s.pendingPublishPromises.delete(i),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(i,r,a,!0);throw S}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new le),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",V(e)),!1;const t=this.permissions,i=t.canPublish,r=t.canPublishSources;return i&&(r.length===0||r.map(s=>Qu(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",V(e)),!1)}publish(e,t,i){return m(this,void 0,void 0,function*(){var r,s,a,o,d,c,l,u,h,p;if(!this.hasPermissionsToPublish(e))throw new Qs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(D=>Mt(e)&&D.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),V(e)),t.stopMicTrackOnMute&&Ze(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&At()&&(t.simulcast=!1),t.videoCodec==="av1"&&!eh()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!th()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Nr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(D=>t.videoCodec===ui(D.mime))||(t.videoCodec=ui(this.enabledPublishVideoCodecs[0].mime)));const g=t.videoCodec;e.on(R.Muted,this.onTrackMuted),e.on(R.Unmuted,this.onTrackUnmuted),e.on(R.Ended,this.handleTrackEnded),e.on(R.UpstreamPaused,this.onTrackUpstreamPaused),e.on(R.UpstreamResumed,this.onTrackUpstreamResumed),e.on(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const T=[],k=!(!((r=t.dtx)!==null&&r!==void 0)||r),S=e.getSourceTrackSettings();S.autoGainControl&&T.push(ce.TF_AUTO_GAIN_CONTROL),S.echoCancellation&&T.push(ce.TF_ECHO_CANCELLATION),S.noiseSuppression&&T.push(ce.TF_NOISE_SUPPRESSION),S.channelCount&&S.channelCount>1&&T.push(ce.TF_STEREO),k&&T.push(ce.TF_NO_DTX),it(e)&&e.hasPreConnectBuffer&&T.push(ce.TF_PRECONNECT_BUFFER);const x=this.normalizeRequestedFrameMetadataOptions(e,t),b=new bi({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:k,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:T,packetTrailerFeatures:x});let y;if(e.kind===C.Kind.Video){let D;try{D=yield e.waitForDimensions()}catch{const F=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:ki.h720.resolution;D={width:F.width,height:F.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},V(e)),{dims:D}))}b.width=D.width,b.height=D.height,ze(e)&&(Be(g)&&(e.source===C.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",V(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),b.simulcastCodecs=[new fr({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Nr}),t.backupCodec&&g!==t.backupCodec.codec&&b.encryption===Q.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new fr({codec:t.backupCodec.codec,cid:""})))),y=ln(e.source===C.Source.ScreenShare,b.width,b.height,t),b.layers=ka(b.width,b.height,y,Be(t.videoCodec))}else e.kind===C.Kind.Audio&&(y=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new ee("cannot publish track when not connected");const _=()=>m(this,void 0,void 0,function*(){var D,O,F;if(!this.engine.pcManager)throw new ee("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),ze(e)&&(e.publishOptions=t),this.emit(I.LocalSenderCreated,e.sender,e),ze(e)&&((D=t.degradationPreference)!==null&&D!==void 0||(t.degradationPreference=yp(e)),e.setDegradationPreference(t.degradationPreference)),y)if(At()&&e.kind===C.Kind.Audio){let X;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){X=Z;break}X&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:X,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Be(e.codec)&&(!((F=y[0])===null||F===void 0)&&F.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let M;const A=new Promise((D,O)=>m(this,void 0,void 0,function*(){var F;try{M=yield this.engine.addTrack(b),D(M)}catch(X){if(e.sender&&(!((F=this.engine.pcManager)===null||F===void 0)&&F.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(Z){this.log.error(Z)}yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},V(e)),{error:Z}))})}O(X)}}));if(this.enabledPublishVideoCodecs.length>0&&x.length===0)M=(yield Promise.all([A,_()]))[0];else{M=yield A;let D;if(M.codecs.forEach(O=>{D===void 0&&(D=O.mimeType)}),D&&e.kind===C.Kind.Video){const O=ui(D);O!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},V(e)),{codec:O})),t.videoCodec=O,y=ln(e.source===C.Source.ScreenShare,b.width,b.height,t))}yield _()}const q=new Ur(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(q.on(R.CpuConstrained,D=>this.onTrackCpuConstrained(D,q)),q.options=t,e.sid=M.sid,ze(e)&&(e.publishOptions=t,b.width&&b.height&&(e.lastEncodedDimensions={width:b.width,height:b.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:M}),ze(e)?e.startMonitor(this.engine.client):it(e)&&e.startMonitor(),this.addTrackPublication(q),this.emit(I.LocalTrackPublished,q),it(e)&&M.audioFeatures.includes(ce.TF_PRECONNECT_BUFFER)){const D=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,F=>{if(F.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",V(e)),e.stopPreConnectBuffer()}}),D&&new Promise((X,Z)=>m(this,void 0,void 0,function*(){var Ge,Zt,ve,ct,Ln,xn;try{this.log.debug("waiting for agent",V(e));const qn=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),od=yield this.waitUntilActiveAgentPresent();clearTimeout(qn),this.log.debug("sending preconnect buffer",V(e));const ys=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[od.identity],attributes:{trackId:q.trackSid,sampleRate:String((Ln=S.sampleRate)!==null&&Ln!==void 0?Ln:"48000"),channels:String((xn=S.channelCount)!==null&&xn!==void 0?xn:"1")}});try{for(var Un=!0,Fn=Fe(D),Bn;Bn=yield Fn.next(),Ge=Bn.done,!Ge;Un=!0){ct=Bn.value,Un=!1;const Vn=ct;yield ys.write(Vn)}}catch(Vn){Zt={error:Vn}}finally{try{!Un&&!Ge&&(ve=Fn.return)&&(yield ve.call(Fn))}finally{if(Zt)throw Zt.error}}yield ys.close(),X()}catch(qn){Z(qn)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",V(e))}).catch(X=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},V(e)),{error:X}))})}return q})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Ei((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const r=(i=t.frameMetadata)!==null&&i!==void 0?i:t.packetTrailer;if(e.kind!==C.Kind.Video||!cn(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),V(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const s=Oh(r),a=Ah(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return m(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Q.NONE)return;let s;if(this.trackPublications.forEach(v=>{v.track&&v.track===e&&(s=v)}),!s)throw new $e("track is not published");if(!ze(e))throw new $e("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=Bc(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",V(e));return}const d=e.addSimulcastTrack(t,o);if(!d)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new bi({cid:d.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=ka(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new ee("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,a,o),yield this.engine.negotiate()}),p=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:p})})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var i,r;if(Mt(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",V(e)),yield l)}const s=this.getPublicationForTrack(e),a=s?V(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(R.Muted,this.onTrackMuted),e.off(R.Unmuted,this.onTrackUnmuted),e.off(R.Ended,this.handleTrackEnded),e.off(R.UpstreamPaused,this.onTrackUpstreamPaused),e.off(R.UpstreamResumed,this.onTrackUpstreamResumed),e.off(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&d)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===d&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(d)}catch(l){this.log.warn(l),o=!0}if(ze(e)){for(const l of e.simulcastCodecs){var c=N(l,2);const u=c[1];if(u.sender){try{o=this.engine.removeTrack(u.sender)}catch(h){this.log.warn(h),o=!0}u.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case C.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(I.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ke((s,a)=>m(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(d=>{d.track&&(t&&(d.options=Object.assign(Object.assign({},d.options),t)),o.push(d))}),yield Promise.all(o.map(d=>m(this,void 0,void 0,function*(){const c=d.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==C.Source.ScreenShare&&c.source!==C.Source.ScreenShareAudio&&(it(c)||ze(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",{track:d.trackSid}),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,d.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?B.RELIABLE:B.LOSSY,a=r.reliable?gt.RELIABLE:gt.LOSSY,o=r.destinationIdentities,d=r.topic;let c=new Wr({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:d});const l=new fe({kind:a,value:{case:"user",value:c}});yield i.engine.sendDataPacket(l,s)})()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const i=new fe({kind:gt.RELIABLE,value:{case:"sipDtmf",value:new uo({code:e,digit:t})}});yield this.engine.sendDataPacket(i,B.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new fe({value:{case:"chatMessage",value:new Zi(Object.assign(Object.assign({},i),{timestamp:$.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,B.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new fe({value:{case:"chatMessage",value:new Zi(Object.assign(Object.assign({},i),{timestamp:$.parse(i.timestamp),editTimestamp:$.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,B.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let i=N(t,2);return i[0],i[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},V(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new le),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(it(r)||ze(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>N(s,1)[0].source===e);if(r)return r[1];yield ge(20)}})}publishDataTrack(e){return m(this,void 0,void 0,function*(){const t=new On(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class Ba extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class tm extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,r;super.set(e,t);const s=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(s){for(const a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return m(this,void 0,void 0,function*(){const i=this.get(e);if(typeof i<"u")return i;if(t!=null&&t.aborted)throw new Ba("The operation was aborted.",t.reason);const r=new le(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){const a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new Ba("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}}class im extends rt{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(R.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Cn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new po({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?rt.SubscriptionStatus.Unsubscribed:super.isSubscribed?rt.SubscriptionStatus.Subscribed:rt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?rt.PermissionStatus.Allowed:rt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Zn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Zn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Re.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(R.VisibilityChanged,this.handleVisibilityChange),r.off(R.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(R.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(R.VisibilityChanged,this.handleVisibilityChange),e.on(R.Ended,this.handleEnded),this.emit(R.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(R.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?R.Muted:R.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(R.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(R.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Zn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ro({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Xs(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Yu(this.trackInfo,this.requestedMaxQuality);i&&Xs(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using 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:Re.HIGH})),e.quality=Re.HIGH)}this.emit(R.UpdateSettings,e)}}class hn extends td{static fromParticipantInfo(e,t,i,r){return new hn(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(s=>{const a=dn.from(s);return new Yc(a,r,{publisherIdentity:t.identity})}),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:vi.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:yc;super(t,i||"",r,s,a,o,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new tm(c.map(u=>[u.info.name,u])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(R.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(R.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(R.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:C.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),V(o))),this.emit(I.TrackSubscriptionFailed,t);return}const d=e.kind==="video";let c;return d?c=new os(e,t,r,s):c=new Qp(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Dr(c)&&Ze(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const d=C.kindFromProto(r.type);if(!d)return;o=new im(d,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));c&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:V(c),newTrack:V(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),V(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(I.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;Ze(i.track)&&Dr(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=N(i,2);const r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var H;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(H||(H={}));const nm=4*1e3;class Mi extends we.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,r,s,a,o,d;if(super(),t=this,this.state=H.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new ue,this.isVideoPlaybackBlocked=!1,this.log=U,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,u)=>m(this,void 0,void 0,function*(){var h;if(!ih())throw He()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const p=yield this.disconnectLock.lock();if(this.state===H.Connected)return this.log.info("already connected to room ".concat(this.name)),p(),Promise.resolve();if(this.connectFuture)return p(),this.connectFuture.promise;this.setAndEmitConnectionState(H.Connecting),((h=this.regionUrlProvider)===null||h===void 0?void 0:h.getServerUrl().toString())!==Mc(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Yt(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new W(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(T=>{var k;(k=this.regionUrlProvider)===null||k===void 0||k.setServerReportedRegions(T)}).catch(T=>{this.log.warn("could not fetch region settings",{error:T})}));const v=(T,k,S)=>m(this,void 0,void 0,function*(){var x,b;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,p==null||p();try{if(yield Ht.getInstance().getBackOffPromise(c),y.signal.aborted)throw L.cancelled("Connection attempt aborted");yield this.attemptConnection(S??c,l,u,y),this.abortController=void 0,T()}catch(_){if(this.regionUrlProvider&&_ instanceof L&&_.reason!==J.Cancelled&&_.reason!==J.NotAllowed){let M=null;try{this.log.debug("Fetching next region"),M=yield this.regionUrlProvider.getNextBestRegionUrl((x=this.abortController)===null||x===void 0?void 0:x.signal)}catch(A){if(A instanceof L&&(A.status===401||A.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),k(A);return}}[J.InternalError,J.ServerUnreachable,J.Timeout].includes(_.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Ht.getInstance().addFailedConnectionAttempt(c)),M&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(M)),this.recreateEngine(!0),yield v(T,k,M)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,na(_)),k(_))}else{let M=je.UNKNOWN_REASON;_ instanceof L&&(M=na(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,M),k(_)}}}),g=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new le((T,k)=>{v(T,k,g)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,u,h,p,v)=>m(this,void 0,void 0,function*(){var g;const T=yield u.join(c,l,{autoSubscribe:h.autoSubscribe,adaptiveStream:typeof p.adaptiveStream=="object"?!0:p.adaptiveStream,clientInfoCapabilities:Ei((g=p.frameMetadata)!==null&&g!==void 0?g:p.packetTrailer)||this.e2eeManager?[bo.CAP_PACKET_TRAILER]:void 0,maxRetries:h.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:h.websocketTimeout},v.signal,!p.singlePeerConnection),k=T.joinResponse,S=T.serverInfo;if(this.serverInfo=S,!S.version)throw new Fu("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),p.dynacast=!1),k}),this.applyJoinResponse=c=>{const l=c.participant;if(this.localParticipant.sid=l.sid,this.localParticipant.identity=l.identity,this.localParticipant.setEnabledPublishCodecs(c.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(c.sifTrailer)}catch(u){this.log.error(u instanceof Error?u.message:"Could not set SifTrailer",{error:u})}this.handleParticipantUpdates([l,...c.otherParticipants]),c.room&&this.handleRoomUpdate(c.room)},this.attemptConnection=(c,l,u,h)=>m(this,void 0,void 0,function*(){var p,v;this.state===H.Reconnecting||this.isResuming||!((p=this.engine)===null||p===void 0)&&p.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((v=this.regionUrlProvider)===null||v===void 0)&&v.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ps),u),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const g=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,h);this.applyJoinResponse(g),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected)}catch(g){yield this.engine.close(),this.recreateEngine();const T=h.signal.aborted?L.cancelled("Signal connection aborted"):L.serverUnreachable("could not establish signal connection");throw g instanceof Error&&(T.message="".concat(T.message,": ").concat(g.message)),g instanceof L&&(T.reason=g.reason,T.status=g.status),this.log.debug("error trying to establish signal connection",{error:g}),T}if(h.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),L.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,h)}catch(g){throw yield this.engine.close(),this.recreateEngine(),g}_e()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_e()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(H.Connected),this.emit(w.Connected),Ht.getInstance().resetFailedConnectionAttempts(c),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var c=arguments.length,l=new Array(c),u=0;u<c;u++)l[u]=arguments[u];return m(t,[...l],void 0,function(){var h=this;let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var v,g,T;const k=yield h.disconnectLock.lock();try{if(h.state===H.Disconnected){h.log.debug("already disconnected");return}if(h.log.info("disconnect from room"),h.state===H.Connecting||h.state===H.Reconnecting||h.isResuming){const S="Abort connection attempt due to user initiated disconnect";h.log.warn(S),(v=h.abortController)===null||v===void 0||v.abort(S),(T=(g=h.connectFuture)===null||g===void 0?void 0:g.reject)===null||T===void 0||T.call(g,L.cancelled("Client initiated disconnect")),h.connectFuture=void 0}h.engine&&(h.engine.client.isDisconnected||(yield h.engine.client.sendLeave()),yield h.engine.close()),h.handleDisconnect(p,je.CLIENT_INITIATED),h.engine=void 0}finally{k()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const c=[],l=Te();if(l&&l.os==="iOS"){const u="livekit-dummy-audio-el";let h=document.getElementById(u);if(!h){h=document.createElement("audio"),h.id=u,h.autoplay=!0,h.hidden=!0;const p=Xn();p.enabled=!0;const v=new MediaStream([p]);h.srcObject=v,document.addEventListener("visibilitychange",()=>{h&&(h.srcObject=document.hidden?null:v,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(h),this.once(w.Disconnected,()=>{h==null||h.remove(),h=null})}c.push(h)}this.remoteParticipants.forEach(u=>{u.audioTrackPublications.forEach(h=>{h.track&&h.track.attachedElements.forEach(p=>{c.push(p)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(u=>(u.muted=!1,u.play()))]),this.handleAudioPlaybackStarted()}catch(u){throw this.handleAudioPlaybackFailed(u),u}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const c=[];for(const l of this.remoteParticipants.values())l.videoTrackPublications.forEach(u=>{var h;(h=u.track)===null||h===void 0||h.attachedElements.forEach(p=>{c.includes(p)||c.push(p)})});yield Promise.all(c.map(l=>l.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(l=>{l.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(w.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(c.serverRegion),{region:c.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(c);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(l){this.log.error("error trying to re-publish tracks after reconnection",{error:l})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:c.serverRegion})}catch{return}this.setAndEmitConnectionState(H.Connected),this.emit(w.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(const h of c){if(h.identity===this.localParticipant.identity){this.localParticipant.updateInfo(h);continue}h.identity===""&&(h.identity=(l=this.sidToIdentity.get(h.sid))!==null&&l!==void 0?l:"");let p=this.remoteParticipants.get(h.identity);h.state===qt.DISCONNECTED?this.handleParticipantDisconnected(h.identity,p):this.getOrCreateParticipant(h.identity,h)}const u=new Map(c.filter(h=>h.identity!==this.localParticipant.identity).map(h=>[h.identity,h.dataTracks.map(p=>dn.from(p))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(u)},this.handleActiveSpeakersUpdate=c=>{const l=[],u={};c.forEach(h=>{if(u[h.sid]=!0,h.sid===this.localParticipant.sid)this.localParticipant.audioLevel=h.level,this.localParticipant.setIsSpeaking(!0),l.push(this.localParticipant);else{const p=this.getRemoteParticipantBySid(h.sid);p&&(p.audioLevel=h.level,p.setIsSpeaking(!0),l.push(p))}}),u[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(h=>{u[h.sid]||(h.audioLevel=0,h.setIsSpeaking(!1))}),this.activeSpeakers=l,this.emitWhenConnected(w.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{const l=new Map;this.activeSpeakers.forEach(h=>{const p=this.remoteParticipants.get(h.identity);p&&p.sid!==h.sid||l.set(h.sid,h)}),c.forEach(h=>{let p=this.getRemoteParticipantBySid(h.sid);h.sid===this.localParticipant.sid&&(p=this.localParticipant),p&&(p.audioLevel=h.level,p.setIsSpeaking(h.active),h.active?l.set(h.sid,p):l.delete(h.sid))});const u=Array.from(l.values());u.sort((h,p)=>p.audioLevel-h.audioLevel),this.activeSpeakers=u,this.emitWhenConnected(w.ActiveSpeakersChanged,u)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{const u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);if(!h||!h.track)return;const p=C.streamStateFromProto(l.state);h.track.setStreamState(p),p!==h.track.streamState&&(u.emit(I.TrackStreamStateChanged,h,h.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,h,h.track.streamState,u))})},this.handleSubscriptionPermissionUpdate=c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{const l=Array.from(this.remoteParticipants.values()).find(h=>h.trackPublications.has(c.trackSid));if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{const u=this.remoteParticipants.get(c.participantIdentity);if(c.value.case==="user")this.handleUserPacket(u,c.value.value,c.kind,l);else if(c.value.case==="transcription")this.handleTranscription(u,c.value.value);else if(c.value.case==="sipDtmf")this.handleSipDtmf(u,c.value.value);else if(c.value.case==="chatMessage")this.handleChatMessage(u,c.value.value);else if(c.value.case==="metrics")this.handleMetrics(c.value.value,u);else if(c.value.case==="streamHeader"||c.value.case==="streamChunk"||c.value.case==="streamTrailer")this.handleDataStream(c,l);else if(c.value.case==="rpcRequest"){const h=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,h)}else if(c.value.case==="rpcResponse"){const h=c.value.value;switch(h.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(h.requestId,h.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(h.requestId,K.fromProto(h.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(h.value.case),this.logContext);break}}else c.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(c.value.value.requestId)},this.handleUserPacket=(c,l,u,h)=>{this.emit(w.DataReceived,l.payload,c,u,l.topic,h),c==null||c.emit(I.DataReceived,l.payload,u,h)},this.handleSipDtmf=(c,l)=>{this.emit(w.SipDTMFReceived,l,c),c==null||c.emit(I.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{const u=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),h=u==null?void 0:u.trackPublications.get(l.trackId),p=uh(l,this.transcriptionReceivedTimes);h==null||h.emit(R.TranscriptionReceived,p),u==null||u.emit(I.TranscriptionReceived,p,h),this.emit(w.TranscriptionReceived,p,u,h)},this.handleChatMessage=(c,l)=>{const u=hh(l);this.emit(w.ChatMessage,u,c)},this.handleMetrics=(c,l)=>{this.emit(w.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(w.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(w.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(w.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(w.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var c;((c=Te())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{const l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,c.metadata),(l==null?void 0:l.activeRecording)!==c.activeRecording&&this.emitWhenConnected(w.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}const u=this.getRemoteParticipantBySid(l.participantSid);u&&u.setConnectionQuality(l.quality)})},this.getRemoteParticipantClientProtocol=c=>{var l,u;return(u=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.clientProtocol)!==null&&u!==void 0?u:yc},this.onLocalParticipantMetadataChanged=c=>{this.emit(w.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(w.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(w.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(w.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(w.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c==null?void 0:c.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>m(this,void 0,void 0,function*(){var l,u,h,p,v,g;(l=c.track)===null||l===void 0||l.on(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.on(R.Restarted,this.onLocalTrackRestarted),(v=(p=(h=c.track)===null||h===void 0?void 0:h.getProcessor())===null||p===void 0?void 0:p.onPublish)===null||v===void 0||v.call(p,this),this.emit(w.LocalTrackPublished,c,this.localParticipant),it(c.track)&&(yield c.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,c);const T=yield(g=c.track)===null||g===void 0?void 0:g.getDeviceId(!1),k=wr(c.source);k&&T&&T!==this.localParticipant.activeDeviceMap.get(k)&&(this.localParticipant.activeDeviceMap.set(k,T),this.emit(w.ActiveDeviceChanged,k,T))}),this.onLocalTrackUnpublished=c=>{var l,u;(l=c.track)===null||l===void 0||l.off(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.off(R.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>m(this,void 0,void 0,function*(){const l=yield c.getDeviceId(!1),u=wr(c.source);u&&l&&l!==this.localParticipant.activeDeviceMap.get(u)&&(this.log.debug("local track restarted, setting ".concat(u," ").concat(l," active")),this.localParticipant.activeDeviceMap.set(u,l),this.emit(w.ActiveDeviceChanged,u,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(w.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(w.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(w.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(w.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},np),e),this.log=Pe((i=this.options.loggerName)!==null&&i!==void 0?i:he.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},xc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Uc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},ip),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Op,this.outgoingDataStreamManager=new Lp(this.engine,this.log),this.incomingDataTrackManager=new Hp({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",c=>{this.engine.client.sendUpdateDataSubscription(c.sid,c.subscribe)}).on("trackPublished",c=>{var l;c.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(w.DataTrackPublished,c.track),(l=this.remoteParticipants.get(c.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(c.track))}).on("trackUnpublished",c=>{var l;c.publisherIdentity!==this.localParticipant.identity&&(this.emit(w.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new gs({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",c=>{this.engine.client.sendPublishDataTrackRequest(c.handle,c.name,c.usesE2ee)}).on("sfuUnpublishRequest",c=>{this.engine.client.sendUnPublishDataTrackRequest(c.handle)}).on("trackPublished",c=>{this.emit(w.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(w.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,u=c.bytes;this.engine.sendLossyBytes(u,B.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new zp(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var c,l;return(l=(c=this.engine.latestJoinResponse)===null||c===void 0?void 0:c.serverInfo)===null||l===void 0?void 0:l.version}),this.rpcClientManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,B.RELIABLE)}),this.rpcServerManager=new Jp(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,B.RELIABLE)}),this.disconnectLock=new ue,this.localParticipant=new em("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.outgoingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",It(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",It(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",It(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),_e()){const c=new AbortController;let l;if(Mi.cleanupRegistry){const u=new WeakRef(this);l=()=>{const h=u.deref();h&&h.handleDeviceChange()},Mi.cleanupRegistry.register(this,()=>{c.abort()})}else l=this.handleDeviceChange;(d=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||d===void 0||d.call(o,"devicechange",l,{signal:c.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const 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;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new Lh(r,i),this.e2eeManager.on(ht.ParticipantEncryptionStatusChanged,(s,a)=>{mh(a)&&(this.isE2EEEnabled=s),this.emit(w.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(ht.EncryptionError,(s,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(w.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new Nc(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===H.Disconnected?ke.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ke.resolve(this.roomInfo.sid):new ke((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(r.sid))};this.engine.on(P.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new ee("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new wp(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(H.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(H.Connected)&&this.emit(w.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===H.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.Restarted,this.handleRestarted).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(H.Reconnecting)&&this.emit(w.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(w.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(P.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!==Q.NONE}})}).on(P.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(P.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(i=>{let r=N(i,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(P.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(P.Joined,e=>{const t=new Map(e.otherParticipants.map(i=>[i.identity,i.dataTracks.map(r=>dn.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(P.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(P.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:xr})}),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=>m(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return de.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===H.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Yt(new URL(e))&&t){this.regionUrlProvider=new W(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===H.Disconnected&&(this.regionUrl=i,yield fetch(Si(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Si(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let i=()=>m(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new Qe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Qe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Qe({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Qe({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new Qe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>m(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new En({reason:je.CLIENT_INITIATED,action:Vt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Qe({scenario:{case:"subscriberBandwidth",value:St(t)}});break;case"leave-full-reconnect":r=new Qe({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,d,c,l,u,h,p;let v=!0,g=!1;const T=a?{exact:r}:r;if(i==="audioinput"){g=s.localParticipant.audioTrackPublications.size===0;const k=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=T;const S=Array.from(s.localParticipant.audioTrackPublications.values()).filter(b=>b.source===C.Source.Microphone);try{v=(yield Promise.all(S.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(T)}))).every(b=>b===!0)}catch(b){throw s.options.audioCaptureDefaults.deviceId=k,b}const x=S.some(b=>{var y,_;return(_=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&_!==void 0?_:!1});v&&x&&(g=!0)}else if(i==="videoinput"){g=s.localParticipant.videoTrackPublications.size===0;const k=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=T;const S=Array.from(s.localParticipant.videoTrackPublications.values()).filter(b=>b.source===C.Source.Camera);try{v=(yield Promise.all(S.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(T)}))).every(b=>b===!0)}catch(b){throw s.options.videoCaptureDefaults.deviceId=k,b}const x=S.some(b=>{var y,_;return(_=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&_!==void 0?_:!1});v&&x&&(g=!0)}else if(i==="audiooutput"){if(g=!0,!on()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(c=yield de.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(p=s.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const k=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(S=>S.setAudioOutput({deviceId:r})))}catch(S){throw s.options.audioOutput.deviceId=k,S}}return g&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(w.ActiveDeviceChanged,i,r)),v})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t==null||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===H.Connecting||this.state===H.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(p=>p.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(w.Reconnected,u),this.off(w.Connected,u),this.off(w.Disconnected,h)};this.once(w.Reconnected,u),this.once(w.Connected,u),this.once(w.Disconnected,h);return}if(this.state===H.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const r=Zu(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const d=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!d){s.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s));return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(s,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:s,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const l=d.addSubscribedMediaTrack(e,o,t,i,c);l!=null&&l.isEncrypted&&!this.e2eeManager&&this.emit(w.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const r=1e4;let s;const a=d=>{d.trackSid===e&&(o(),this.emitLocalTrackSubscribed(d))},o=()=>{clearTimeout(s),this.localParticipant.off(I.LocalTrackPublished,a),this.off(w.Disconnected,o)};this.localParticipant.on(I.LocalTrackPublished,a),this.once(w.Disconnected,o),s=setTimeout(()=>{o();const d=t();d?this.emitLocalTrackSubscribed(d):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit(I.LocalTrackSubscribed,e),this.emitWhenConnected(w.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==H.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,d;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(d=s.track)===null||d===void 0||d.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),_e()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||r===void 0||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(H.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return m(this,void 0,void 0,function*(){var e,t,i;const r=de.getInstance().previousDevices,s=yield de.getInstance().getDevices(void 0,!1),a=Te();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let d of s){const c=r.find(l=>l.deviceId===d.deviceId);c&&c.label!==""&&c.kind===d.kind&&c.label!==d.label&&this.getActiveDevice(d.kind)==="default"&&this.emit(w.ActiveDeviceChanged,d.kind,d.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let d of o){const c=Ku(d),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(p=>p.kind===d),h=this.getActiveDevice(d);if(h===((t=r.filter(p=>p.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(d,u[0].deviceId);continue}d==="audioinput"&&!Ti()||d==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Ti())&&(yield this.switchActiveDevice(d,u[0].deviceId))}})}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=is())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ge(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(w.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=hn.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new hn(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(w.ParticipantConnected,i),i.on(I.TrackPublished,r=>{this.emitWhenConnected(w.TrackPublished,r,i)}).on(I.TrackSubscribed,(r,s)=>{r.kind===C.Kind.Audio?(r.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===C.Kind.Video&&(r.on(R.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(R.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(w.TrackSubscribed,r,s,i)}).on(I.TrackUnpublished,r=>{this.emit(w.TrackUnpublished,r,i)}).on(I.TrackUnsubscribed,(r,s)=>{this.emit(w.TrackUnsubscribed,r,s,i)}).on(I.TrackMuted,r=>{this.emitWhenConnected(w.TrackMuted,r,i)}).on(I.TrackUnmuted,r=>{this.emitWhenConnected(w.TrackUnmuted,r,i)}).on(I.ParticipantMetadataChanged,r=>{this.emitWhenConnected(w.ParticipantMetadataChanged,r,i)}).on(I.ParticipantNameChanged,r=>{this.emitWhenConnected(w.ParticipantNameChanged,r,i)}).on(I.AttributesChanged,r=>{this.emitWhenConnected(w.ParticipantAttributesChanged,r,i)}).on(I.ConnectionQualityChanged,r=>{this.emitWhenConnected(w.ConnectionQualityChanged,r,i)}).on(I.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,r,i)}).on(I.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,r,s,i)}).on(I.TrackSubscriptionFailed,(r,s)=>{this.emit(w.TrackSubscriptionFailed,r,i,s)}).on(I.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,r,s,i)}).on(I.Active,()=>{this.emitWhenConnected(w.ParticipantActive,i),i.kind===vi.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&ph(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Xc,(e,t)=>m(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return(function*(){var o;const d=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(i,a,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(Zc,(e,t)=>m(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return(function*(){var o;const d=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(i,a,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ae.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(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,je.STATE_MISMATCH))):e=0},nm)}clearConnectionReconcile(){this.connectionReconcileInterval&&ae.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===H.Connected),this.emit(w.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=N(e,2),i=t[0],r=t[1];this.emit(i,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===H.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===H.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,i,r,s;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new mn({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:$.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(H.Connected),a.video){const d=new Ur(C.Kind.Video,new Ft({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:xe.AUDIO,name:"video-dummy"}),new Pi(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Mr(160*((i=o.aspectRatios[0])!==null&&i!==void 0?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(d),this.localParticipant.emit(I.LocalTrackPublished,d)}if(a.audio){const d=new Ur(C.Kind.Audio,new Ft({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:xe.AUDIO}),new _i(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Xn(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(I.LocalTrackPublished,d)}for(let d=0;d<o.count-1;d+=1){let c=new Ot({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:qt.ACTIVE,tracks:[],joinedAt:$.parse(Date.now())});const l=this.getOrCreateParticipant(c.identity,c);if(o.video){const u=Mr(160*((s=o.aspectRatios[d%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new Ft({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:xe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}if(o.audio){const u=Xn(),h=new Ft({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:xe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}l.updateInfo(c)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==w.ActiveSpeakersChanged&&e!==w.TranscriptionReceived){const s=id(i).filter(a=>a!==void 0);(e===w.TrackSubscribed||e===w.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...i)}}Mi.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});function id(n){return n.map(e=>{if(e)return Array.isArray(e)?id(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}class rm{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}var ff=Object.freeze({__proto__:null,Convert:rm}),Le;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Le||(Le={}));class kt extends we.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Le.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Mi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Le.IDLE)throw Error("check is running already");this.setStatus(Le.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Le.SKIPPED&&this.setStatus(this.isSuccess()?Le.SUCCESS:Le.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===H.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==H.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Le.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(w.Reconnecting,()=>{t=!0}),this.room.once(w.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield ge(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class sm extends kt{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new W(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,d=1e6/a,c="A".repeat(a),l=Date.now();for(let v=0;v<d;v++)yield s.write(c);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:u-l};return h==null||h.forEach(v=>{v.type==="candidate-pair"&&v.nominated&&(p.rtt=v.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const dr=1e4;class am extends kt{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(dr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(dr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>m(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(l.packetsSent=p.packetsSent,l.qualityLimitationDurations=p.qualityLimitationDurations,l.bitrateTotal+=p.targetBitrate,l.count++):p.type==="remote-inbound-rtp"&&(l.packetsLost=p.packetsLost,l.rttTotal+=p.roundTripTime,l.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,dr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class om extends kt{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield $p();if(yield Sc(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class cm extends kt{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Yp();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,d;const c=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(d=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&d!==void 0?d:720;c.width=u,c.height=h;const p=c.getContext("2d");p.drawImage(i,0,0);const g=p.getImageData(0,0,c.width,c.height).data;let T=!0;for(let k=0;k<g.length;k+=4)if(g[k]!==0||g[k+1]!==0||g[k+2]!==0){T=!1;break}T?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}}class dm extends kt{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(w.SignalReconnecting,o).on(w.Reconnecting,o).on(w.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const d=t.engine.client.onClose;if(d&&d(""),yield a,i){if(!r||t.state!==H.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class lm extends kt{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;Yt(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new W(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new ls,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,d=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,d=!0):l.startsWith("turns:")&&(o=!0,d=!0,a=!0),l.startsWith("stun:")&&(d=!0);d?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class um extends kt{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let d="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(hm(o.address)?d+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,d+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(d)}r&&r(s,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),U.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function hm(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class pm extends kt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ls,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(Yt(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const d=yield new W(this.url,this.token).getNextBestRegionUrl();d&&(s=yield r.join(d,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===fo.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class gf extends we.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Le.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Le.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(pm)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(um)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(lm)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(dm)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(om)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(cm)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(am);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(sm)})}}class mm{}class fm{}new TextEncoder;const Fr=new TextDecoder;function gm(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(n);const e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function vm(n){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof n=="string"?n:Fr.decode(n),{alphabet:"base64url"});let e=n;e instanceof Uint8Array&&(e=Fr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return gm(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class Se extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}j(Se,"code","ERR_JOSE_GENERIC");class bm extends Se{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}j(bm,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class ym extends Se{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}j(ym,"code","ERR_JWT_EXPIRED");class km extends Se{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}j(km,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Tm extends Se{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}}j(Tm,"code","ERR_JOSE_NOT_SUPPORTED");class Sm extends Se{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}}j(Sm,"code","ERR_JWE_DECRYPTION_FAILED");class Cm extends Se{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}}j(Cm,"code","ERR_JWE_INVALID");class Em extends Se{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}}j(Em,"code","ERR_JWS_INVALID");class lt extends Se{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}}j(lt,"code","ERR_JWT_INVALID");class _m extends Se{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}}j(_m,"code","ERR_JWK_INVALID");class Pm extends Se{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}}j(Pm,"code","ERR_JWKS_INVALID");class wm extends Se{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}j(wm,"code","ERR_JWKS_NO_MATCHING_KEY");class Rm extends Se{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,Symbol.asyncIterator,void 0),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}j(Rm,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Im extends Se{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_TIMEOUT")}}j(Im,"code","ERR_JWKS_TIMEOUT");class Mm extends Se{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}j(Mm,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const Dm=n=>typeof n=="object"&&n!==null;function Om(n){if(!Dm(n)||Object.prototype.toString.call(n)!=="[object Object]")return!1;if(Object.getPrototypeOf(n)===null)return!0;let e=n;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(n)===e}function Am(n){if(typeof n!="string")throw new lt("JWTs must use Compact JWS serialization, JWT must be a string");const e=n.split("."),t=e[1],i=e.length;if(i===5)throw new lt("Only JWTs using Compact JWS serialization can be decoded");if(i!==3)throw new lt("Invalid JWT");if(!t)throw new lt("JWTs must contain a payload");let r;try{r=vm(t)}catch{throw new lt("Failed to base64url decode the payload")}let s;try{s=JSON.parse(Fr.decode(r))}catch{throw new lt("Failed to parse the decoded payload as JSON")}if(!Om(s))throw new lt("Invalid JWT Claims Set");return s}const Br=1e3,Nm=60*Br;function Lm(n){const e=nd(n.participantToken);if(!(e!=null&&e.nbf)||!(e!=null&&e.exp))return!0;const t=new Date,i=e.nbf*Br,r=new Date(i),s=e.exp*Br,a=new Date(s-Nm);return r<=t&&a>t}function nd(n){const e=Am(n);e.roomConfig;const t=es(e,["roomConfig"]);return Object.assign(Object.assign({},t),{roomConfig:e.roomConfig?li.fromJson(e.roomConfig,{ignoreUnknownFields:!0}):void 0})}function xm(n,e){const t=new Set([...Object.keys(n),...Object.keys(e)]);for(const i of t)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":case"deployment":if(n[i]!==e[i])return!1;break;default:const r=i;throw new Error("Options key ".concat(r," not being checked for equality!"))}return!0}class rd extends fm{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new ue}isSameAsCachedFetchOptions(e){return this.cachedFetchOptions?xm(e,this.cachedFetchOptions):!1}shouldReturnCachedValueFromFetch(e){return!(!this.cachedResponse||!Lm(this.cachedResponse)||!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?nd(this.cachedResponse.participantToken):null}fetch(e,t){return m(this,void 0,void 0,function*(){const i=yield this.fetchMutex.lock();try{if(t&&(this.cachedResponse=null),this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();this.cachedFetchOptions=e;const r=yield this.update(e);return this.cachedResponse=r,r.toJson()}finally{i()}})}}class Um extends mm{constructor(e){super(),this.literalOrFn=e}fetch(){return m(this,void 0,void 0,function*(){return typeof this.literalOrFn=="function"?this.literalOrFn():this.literalOrFn})}}class Fm extends rd{constructor(e){super(),this.customFn=e}update(e){return m(this,void 0,void 0,function*(){const t=this.customFn(e);let i;return t instanceof Promise?i=yield t:i=t,Fo.fromJson(i,{ignoreUnknownFields:!0})})}}class sd extends rd{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.url=e,this.endpointOptions=t}createRequestFromOptions(e){var t,i,r,s;const a=new hu;for(const o of Object.keys(e))switch(o){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":a[o]=e[o];break;case"participantAttributes":a.participantAttributes=(t=e.participantAttributes)!==null&&t!==void 0?t:{};break;case"agentName":a.roomConfig=(i=a.roomConfig)!==null&&i!==void 0?i:new li,a.roomConfig.agents.length===0&&a.roomConfig.agents.push(new Vi),a.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":a.roomConfig=(r=a.roomConfig)!==null&&r!==void 0?r:new li,a.roomConfig.agents.length===0&&a.roomConfig.agents.push(new Vi),a.roomConfig.agents[0].metadata=e.agentMetadata;break;case"deployment":a.roomConfig=(s=a.roomConfig)!==null&&s!==void 0?s:new li,a.roomConfig.agents.length===0&&a.roomConfig.agents.push(new Vi),a.roomConfig.agents[0].deployment=e.deployment;break;default:const d=o;throw new Error("Options key ".concat(d," not being included in forming request!"))}return a}update(e){return m(this,void 0,void 0,function*(){var t;const i=this.createRequestFromOptions(e),r=yield fetch(this.url,Object.assign(Object.assign({},this.endpointOptions),{method:(t=this.endpointOptions.method)!==null&&t!==void 0?t:"POST",headers:Object.assign({"Content-Type":"application/json"},this.endpointOptions.headers),body:i.toJsonString({useProtoFieldName:!0})}));if(!r.ok)throw new Error("Error generating token from endpoint ".concat(this.url,": received ").concat(r.status," / ").concat(yield r.text()));const s=yield r.json();return Fo.fromJson(s,{ignoreUnknownFields:!0})})}}class Bm extends sd{constructor(e,t){const i=t.baseUrl,r=i===void 0?"https://cloud-api.livekit.io":i,s=es(t,["baseUrl"]);super("".concat(r,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},s),{headers:{"X-Sandbox-ID":e}}))}}const vf={literal(n){return new Um(n)},custom(n){return new Fm(n)},endpoint(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new sd(n,e)},sandboxTokenServer(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Bm(n,e)}};function bf(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var t;const i=Mt(n)?n.mediaStreamTrack:n,r=i.getSettings();let s={facingMode:(t=e.defaultFacingMode)!==null&&t!==void 0?t:"user",confidence:"low"};if("facingMode"in r){const a=r.facingMode;U.trace("rawFacingMode",{rawFacingMode:a}),a&&typeof a=="string"&&jm(a)&&(s={facingMode:a,confidence:"high"})}if(["low","medium"].includes(s.confidence)){U.trace("Try to get facing mode from device label: (".concat(i.label,")"));const a=Vm(i.label);a!==void 0&&(s=a)}return s}const qa=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),qm=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Vm(n){var e;const t=n.trim().toLowerCase();if(t!=="")return qa.has(t)?qa.get(t):(e=Array.from(qm.entries()).find(i=>{let r=N(i,1),s=r[0];return t.includes(s)}))===null||e===void 0?void 0:e[1]}function jm(n){return n===void 0||["user","environment","left","right"].includes(n)}const ad=Symbol.for("lk.serializer");function yf(n){return typeof n=="object"&&n!==null&&"symbol"in n&&n.symbol===ad}function bs(n){return Object.assign(Object.assign({},n),{symbol:ad})}function Wm(){return bs({parse:n=>JSON.parse(n),serialize:n=>JSON.stringify(n)})}function Hm(){return bs({parse:n=>n,serialize:n=>n})}function Km(n){return bs(n)}const kf={json:Wm,raw:Hm,custom:Km};export{Er as AudioPresets,$s as BackupCodecPolicy,Dh as BaseKeyProvider,rn as CLIENT_PROTOCOL_DATA_STREAM_RPC,yc as CLIENT_PROTOCOL_DEFAULT,Le as CheckStatus,kt as Checker,gf as ConnectionCheck,L as ConnectionError,J as ConnectionErrorReason,ut as ConnectionQuality,H as ConnectionState,ae as CriticalTimers,hf as CryptorError,Or as CryptorErrorReason,aa as CryptorEvent,gt as DataPacket_Kind,De as DataStreamError,be as DataStreamErrorReason,In as DataTrackPacket,yu as DefaultReconnectPolicy,_n as DeviceUnsupportedError,je as DisconnectReason,ht as EncryptionEvent,Q as Encryption_Type,P as EngineEvent,uf as ExternalE2EEKeyProvider,Nc as FrameMetadataManager,sa as KeyHandlerEvent,vt as KeyProviderEvent,Ke as LivekitError,Oe as LivekitReasonedError,_i as LocalAudioTrack,On as LocalDataTrack,em as LocalParticipant,Fc as LocalTrack,Ur as LocalTrackPublication,ap as LocalTrackRecorder,Pi as LocalVideoTrack,yi as LogLevel,he as LoggerNames,sn as MediaDeviceFailure,ue as Mutex,Rt as NegotiationError,pf as PacketTrailerManager,td as Participant,I as ParticipantEvent,vi as ParticipantKind,Bu as PublishDataError,Qs as PublishTrackError,Qp as RemoteAudioTrack,Yc as RemoteDataTrack,hn as RemoteParticipant,Ac as RemoteTrack,im as RemoteTrackPublication,os as RemoteVideoTrack,Mi as Room,w as RoomEvent,K as RpcError,Pn as ScreenSharePresets,Ut as SignalReconnectError,Ys as SignalRequestError,Jm as SimulatedError,pl as SubscriptionError,vf as TokenSource,fm as TokenSourceConfigurable,mm as TokenSourceFixed,C as Track,R as TrackEvent,$e as TrackInvalidError,rt as TrackPublication,xe as TrackType,ee as UnexpectedConnectionState,Fu as UnsupportedServer,G as VideoPreset,ki as VideoPresets,_r as VideoPresets43,Re as VideoQuality,xm as areTokenSourceFetchOptionsEqual,Mh as asEncryptablePacket,Bt as attachToElement,ff as attributes,Vu as audioCodecs,Uu as clientProtocol,et as compareVersions,Zm as createAudioAnalyser,af as createE2EEKey,Rh as createKeyMaterialFromBuffer,wh as createKeyMaterialFromString,$p as createLocalAudioTrack,mf as createLocalScreenTracks,Nn as createLocalTracks,Yp as createLocalVideoTrack,nd as decodeTokenPayload,sf as deriveKeys,Wt as detachTrack,Vm as facingModeFromDeviceLabel,bf as facingModeFromLocalTrack,Te as getBrowser,Xn as getEmptyAudioStreamTrack,Xm as getEmptyVideoStreamTrack,Pe as getLogger,rf as importKey,ef as isAudioCodec,Ze as isAudioTrack,Hu as isBackupCodec,kc as isBackupVideoCodec,ih as isBrowserSupported,_h as isE2EESupported,rs as isInsertableStreamSupported,mh as isLocalParticipant,Mt as isLocalTrack,tf as isRemoteParticipant,Dr as isRemoteTrack,Ph as isScriptTransformSupported,yf as isSerializer,dh as isVideoCodec,nf as isVideoFrame,ot as isVideoTrack,cf as needsRbspUnescaping,df as parseRbsp,xu as protocolVersion,of as ratchet,kf as serializers,zm as setLogExtension,Gm as setLogLevel,eh as supportsAV1,Qm as supportsAdaptiveStream,$m as supportsAudioOutputSelection,Ym as supportsDynacast,th as supportsVP9,Lu as version,Wu as videoCodecs,lf as writeRbsp};
|