liveroom-client-element 0.0.44 → 0.0.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{constants-D2eonWil.js → constants-DJD2AXO4.js} +12 -10
- package/dist/constants-DfeL-H6H.cjs +1 -0
- package/dist/liveroom-client-element.cjs +9 -9
- package/dist/liveroom-client-element.js +2350 -2332
- package/dist/main.cjs +1 -1
- package/dist/main.js +45 -39
- package/package.json +1 -1
- package/dist/constants-BJHM5eo7.cjs +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var Pc=Object.defineProperty;var _c=(i,e,t)=>e in i?Pc(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var A=(i,e,t)=>(_c(i,typeof e!="symbol"?e+"":e,t),t);const Er=require("./constants-BJHM5eo7.cjs");function kn(){}function _o(i){return i()}function Pr(){return Object.create(null)}function On(i){i.forEach(_o)}function Ro(i){return typeof i=="function"}function Rc(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}function Oc(i){return Object.keys(i).length===0}function Ae(i,e){i.appendChild(e)}function xc(i,e,t){const n=Ic(i);if(!n.getElementById(e)){const s=$e("style");s.id=e,s.textContent=t,Nc(n,s)}}function Ic(i){if(!i)return document;const e=i.getRootNode?i.getRootNode():i.ownerDocument;return e&&e.host?e:i.ownerDocument}function Nc(i,e){return Ae(i.head||i,e),e.sheet}function Si(i,e,t){i.insertBefore(e,t||null)}function yi(i){i.parentNode&&i.parentNode.removeChild(i)}function $e(i){return document.createElement(i)}function _r(i){return document.createElementNS("http://www.w3.org/2000/svg",i)}function rr(i){return document.createTextNode(i)}function an(){return rr(" ")}function Ac(){return rr("")}function V(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function Mc(i){return Array.from(i.childNodes)}function Dc(i,e){e=""+e,i.data!==e&&(i.data=e)}function nt(i,e,t,n){t==null?i.style.removeProperty(e):i.style.setProperty(e,t,n?"important":"")}function Lc(i){const e={};return i.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let Cn;function dn(i){Cn=i}function Oo(){if(!Cn)throw new Error("Function called outside component initialization");return Cn}function Uc(i){Oo().$$.on_mount.push(i)}function Fc(i){Oo().$$.on_destroy.push(i)}const Li=[],Ps=[];let ji=[];const Rr=[],jc=Promise.resolve();let _s=!1;function Bc(){_s||(_s=!0,jc.then(Ti))}function Rs(i){ji.push(i)}const fs=new Set;let Ai=0;function Ti(){if(Ai!==0)return;const i=Cn;do{try{for(;Ai<Li.length;){const e=Li[Ai];Ai++,dn(e),Jc(e.$$)}}catch(e){throw Li.length=0,Ai=0,e}for(dn(null),Li.length=0,Ai=0;Ps.length;)Ps.pop()();for(let e=0;e<ji.length;e+=1){const t=ji[e];fs.has(t)||(fs.add(t),t())}ji.length=0}while(Li.length);for(;Rr.length;)Rr.pop()();_s=!1,fs.clear(),dn(i)}function Jc(i){if(i.fragment!==null){i.update(),On(i.before_update);const e=i.dirty;i.dirty=[-1],i.fragment&&i.fragment.p(i.ctx,e),i.after_update.forEach(Rs)}}function Vc(i){const e=[],t=[];ji.forEach(n=>i.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),ji=e}const qc=new Set;function xo(i,e){i&&i.i&&(qc.delete(i),i.i(e))}function Or(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function $c(i,e){i.d(1),e.delete(i.key)}function Hc(i,e,t,n,s,r,o,a,c,u,l,h){let f=i.length,p=r.length,v=f;const y={};for(;v--;)y[i[v].key]=v;const R=[],S=new Map,w=new Map,$=[];for(v=p;v--;){const U=h(s,r,v),ee=t(U);let M=o.get(ee);M?n&&$.push(()=>M.p(U,e)):(M=u(ee,U),M.c()),S.set(ee,R[v]=M),ee in y&&w.set(ee,Math.abs(v-y[ee]))}const K=new Set,me=new Set;function de(U){xo(U,1),U.m(a,l),o.set(U.key,U),l=U.first,p--}for(;f&&p;){const U=R[p-1],ee=i[f-1],M=U.key,H=ee.key;U===ee?(l=U.first,f--,p--):S.has(H)?!o.has(M)||K.has(M)?de(U):me.has(H)?f--:w.get(M)>w.get(H)?(me.add(M),de(U)):(K.add(H),f--):(c(ee,o),f--)}for(;f--;){const U=i[f];S.has(U.key)||c(U,o)}for(;p;)de(R[p-1]);return On($),R}function zc(i,e,t){const{fragment:n,after_update:s}=i.$$;n&&n.m(e,t),Rs(()=>{const r=i.$$.on_mount.map(_o).filter(Ro);i.$$.on_destroy?i.$$.on_destroy.push(...r):On(r),i.$$.on_mount=[]}),s.forEach(Rs)}function Gc(i,e){const t=i.$$;t.fragment!==null&&(Vc(t.after_update),On(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function Wc(i,e){i.$$.dirty[0]===-1&&(Li.push(i),Bc(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<<e%31}function Kc(i,e,t,n,s,r,o=null,a=[-1]){const c=Cn;dn(i);const u=i.$$={fragment:null,ctx:[],props:r,update:kn,not_equal:s,bound:Pr(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:Pr(),dirty:a,skip_bound:!1,root:e.target||c.$$.root};o&&o(u.root);let l=!1;if(u.ctx=t?t(i,e.props||{},(h,f,...p)=>{const v=p.length?p[0]:f;return u.ctx&&s(u.ctx[h],u.ctx[h]=v)&&(!u.skip_bound&&u.bound[h]&&u.bound[h](v),l&&Wc(i,h)),f}):[],u.update(),l=!0,On(u.before_update),u.fragment=n?n(u.ctx):!1,e.target){if(e.hydrate){const h=Mc(e.target);u.fragment&&u.fragment.l(h),h.forEach(yi)}else u.fragment&&u.fragment.c();e.intro&&xo(i.$$.fragment),zc(i,e.target,e.anchor),Ti()}dn(c)}let Io;typeof HTMLElement=="function"&&(Io=class extends HTMLElement{constructor(e,t,n){super();A(this,"$$ctor");A(this,"$$s");A(this,"$$c");A(this,"$$cn",!1);A(this,"$$d",{});A(this,"$$r",!1);A(this,"$$p_d",{});A(this,"$$l",{});A(this,"$$l_u",new Map);this.$$ctor=e,this.$$s=t,n&&this.attachShadow({mode:"open"})}addEventListener(e,t,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const s=this.$$c.$on(e,t);this.$$l_u.set(t,s)}super.addEventListener(e,t,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),this.$$c){const s=this.$$l_u.get(t);s&&(s(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(r){return()=>{let o;return{c:function(){o=$e("slot"),r!=="default"&&V(o,"name",r)},m:function(u,l){Si(u,o,l)},d:function(u){u&&yi(o)}}}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},n=Lc(this);for(const r of this.$$s)r in n&&(t[r]=[e(r)]);for(const r of this.attributes){const o=this.$$g_p(r.name);o in this.$$d||(this.$$d[o]=Fn(o,r.value,this.$$p_d,"toProp"))}for(const r in this.$$p_d)!(r in this.$$d)&&this[r]!==void 0&&(this.$$d[r]=this[r],delete this[r]);this.$$c=new this.$$ctor({target:this.shadowRoot||this,props:{...this.$$d,$$slots:t,$$scope:{ctx:[]}}});const s=()=>{this.$$r=!0;for(const r in this.$$p_d)if(this.$$d[r]=this.$$c.$$.ctx[this.$$c.$$.props[r]],this.$$p_d[r].reflect){const o=Fn(r,this.$$d[r],this.$$p_d,"toAttribute");o==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,o)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const o of this.$$l[r]){const a=this.$$c.$on(r,o);this.$$l_u.set(o,a)}this.$$l={}}}attributeChangedCallback(e,t,n){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=Fn(e,n,this.$$p_d,"toProp"),(s=this.$$c)==null||s.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{this.$$cn||(this.$$c.$destroy(),this.$$c=void 0)})}$$g_p(e){return Object.keys(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function Fn(i,e,t,n){var r;const s=(r=t[i])==null?void 0:r.type;if(e=s==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!t[i])return e;if(n==="toAttribute")switch(s){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(s){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function Yc(i,e,t,n,s,r){let o=class extends Io{constructor(){super(i,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(a=>(e[a].attribute||a).toLowerCase())}};return Object.keys(e).forEach(a=>{Object.defineProperty(o.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(c){var u;c=Fn(a,c,e),this.$$d[a]=c,(u=this.$$c)==null||u.$set({[a]:c})}})}),n.forEach(a=>{Object.defineProperty(o.prototype,a,{get(){var c;return(c=this.$$c)==null?void 0:c[a]}})}),r&&(o=r(o)),i.element=o,o}class Xc{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Gc(this,1),this.$destroy=kn}$on(e,t){if(!Ro(t))return kn;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const s=n.indexOf(t);s!==-1&&n.splice(s,1)}}$set(e){this.$$set&&!Oc(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Qc="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Qc);const{isArray:Zc}=Array,eu=Object.keys,Tn=i=>{if(!i)return i;if(Zc(i)){const e=[],t=i.length;for(let n=0;n<t;n++)e.push(Tn(i[n]));return e}else if(typeof i=="object"){const e=eu(i),t=e.length,n={};for(let s=0;s<t;s++){const r=e[s];n[r]=Tn(i[r])}return n}return i};class Le{constructor(e){A(this,"path");A(this,"from");this.path=e}}const tu=/~1/g,iu=/~0/g,nu=/~/g,su=/\//g;function ru(i){return i.indexOf("~")===-1?i:i.replace(tu,"/").replace(iu,"~")}function ou(i){return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(nu,"~0").replace(su,"~1")}function au(i){return i?i.slice(1).split("/").map(ru):[]}function W(i){return cu(i)?"":"/"+i.map(e=>ou(String(e))).join("/")}const J=i=>typeof i=="string"?au(i):i,cu=i=>!i.length,uu=Object.prototype.hasOwnProperty;function lu(i,e){return uu.call(i,e)}const{isArray:No}=Array,ne=(i,e)=>{const t=e.length;if(!t)return{val:i};let n,s;for(let o=0;o<t;o++)if(n=i,s=e[o],No(n)){const a=n.length;if(s==="-")s=a;else if(typeof s=="string"){const c=~~s;if(""+c!==s)throw new Error("INVALID_INDEX");if(s=c,s<0)throw new Error("INVALID_INDEX")}i=n[s]}else if(typeof n=="object"&&n)i=lu(n,s)?n[s]:void 0;else throw new Error("NOT_FOUND");return{val:i,obj:n,key:s}},xn=i=>No(i.obj)&&typeof i.key=="number",rs=i=>typeof i.obj=="object"&&typeof i.key=="string";class or extends Le{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"add"}code(){return 0}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path),o=Tn(this.value);if(!r)t=o;else if(typeof s=="string")r[s]=o;else{const a=r.length;if(s<a)r.splice(s,0,o);else{if(s>a)throw new Error("INVALID_INDEX");r.push(o)}}return{doc:t,old:n}}toJson(t){return{op:"add",path:W(this.path),value:this.value}}toCompact(t,n){return[n?"add":0,this.path,this.value]}encode(t){t.encodeArrayHeader(3),t.writer.u8(0),t.encodeArray(this.path),t.encodeAny(this.value)}}class Ao extends Le{constructor(t,n){super(t);A(this,"oldValue");this.oldValue=n}op(){return"remove"}code(){return 1}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return rs(n)?delete n.obj[n.key]:xn(n)?n.val!==void 0&&n.obj.splice(n.key,1):t=null,{doc:t,old:n.val}}toJson(t){const n={op:"remove",path:W(this.path)};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"remove":1;return this.oldValue===void 0?[s,this.path]:[s,this.path,this.oldValue]}encode(t,n){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?3:2),t.writer.u8(1),t.encodeArray(this.path),s&&t.encodeAny(this.oldValue)}}class du extends Le{constructor(t,n,s){super(t);A(this,"value");A(this,"oldValue");this.value=n,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return rs(n)?n.obj[n.key]=this.value:xn(n)?n.obj[n.key]=this.value:t=this.value,{doc:t,old:n.val}}toJson(t){const n={op:"replace",path:W(this.path),value:this.value};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"replace":2;return this.oldValue===void 0?[s,this.path,this.value]:[s,this.path,this.value,this.oldValue]}encode(t,n){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?4:3),t.writer.u8(2),t.encodeArray(this.path),t.encodeAny(this.value),s&&t.encodeAny(this.oldValue)}}class hu extends Le{constructor(t,n){super(t);A(this,"from");this.from=n}op(){return"move"}code(){return 4}apply(t){const n=new Ao(J(this.from),void 0).apply(t);return new or(this.path,n.old).apply(n.doc)}toJson(t){return{op:"move",path:W(this.path),from:W(this.from)}}toCompact(t,n){return[n?"move":4,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(4),t.encodeArray(this.path),t.encodeArray(this.from)}}class fu extends Le{constructor(t,n){super(t);A(this,"from");this.from=n}op(){return"copy"}code(){return 3}apply(t){const{val:n}=ne(t,this.from);if(n===void 0)throw new Error("NOT_FOUND");return new or(this.path,Tn(n)).apply(t)}toJson(t){return{op:"copy",path:W(this.path),from:W(this.from)}}toCompact(t,n){return[n?"copy":3,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(3),t.encodeArray(this.path),t.encodeArray(this.from)}}class Re extends Le{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const Yn=(i,e)=>{if(i===e)return!0;if(i&&e&&typeof i=="object"&&typeof e=="object"){if(i.constructor!==e.constructor)return!1;let t,n,s;if(Array.isArray(i)){if(t=i.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!Yn(i[n],e[n]))return!1;return!0}if(s=Object.keys(i),t=s.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;){const r=s[n];if(!Yn(i[r],e[r]))return!1}return!0}return!1};class pu extends Re{constructor(t,n,s){super(t);A(this,"value");A(this,"not");this.value=n,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:n}=ne(t,this.path);if(n===void 0)return!!this.not;const s=Yn(n,this.value);return this.not?!s:s}toJson(t){const n={op:"test",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=t?this.path.slice(t.path.length):this.path,r=n?"test":5;return this.not?[r,s,this.value,1]:[r,s,this.value]}encode(t,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(5),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeAny(this.value),this.not&&t.writer.u8(1)}}class mu extends Le{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=ne(e,this.path);return t.obj?t.obj[t.key]=!t.val:e=!t.val,{doc:e,old:t.val}}toJson(e){return{op:"flip",path:W(this.path)}}toCompact(e,t){return[t?"flip":8,this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(8),e.encodeArray(this.path)}}class gu extends Le{constructor(t,n){super(t);A(this,"inc");this.inc=n}op(){return"inc"}code(){return 9}apply(t){const n=ne(t,this.path),s=this.inc+Number(n.val);return n.obj?n.obj[n.key]=s:t=s,{doc:t,old:n.val}}toJson(t){return{op:"inc",path:W(this.path),inc:this.inc}}toCompact(t,n){return[n?"inc":9,this.path,this.inc]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(9),t.encodeArray(this.path),t.encodeNumber(this.inc)}}class vu extends Le{constructor(t,n,s){super(t);A(this,"pos");A(this,"str");this.pos=n,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path);if(typeof n!="string"){if(n!==void 0)throw new Error("NOT_A_STRING");if(this.pos!==0)throw new Error("POS")}const o=typeof n=="string"?n:"",a=Math.min(this.pos,o.length),c=o.slice(0,a),u=o.slice(a),l=c+this.str+u;return r?r[s]=l:t=l,{doc:t,old:n}}toJson(t){return{op:"str_ins",path:W(this.path),pos:this.pos,str:this.str}}toCompact(t,n){return[n?"str_ins":6,this.path,this.pos,this.str]}encode(t,n){t.encodeArrayHeader(4),t.writer.u8(6),t.encodeArray(this.path),t.encodeNumber(this.pos),t.encodeString(this.str)}}class yu extends Le{constructor(t,n,s,r){super(t);A(this,"pos");A(this,"str");A(this,"len");this.pos=n,this.str=s,this.len=r}op(){return"str_del"}code(){return 7}deleteLength(){return typeof this.str=="string"?this.str.length:this.len}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path);if(typeof n!="string")throw new Error("NOT_A_STRING");const o=n.length,a=Math.min(this.pos,n.length),c=Math.min(a,o),u=this.str!==void 0?this.str.length:this.len,l=Math.min(a+u,o),h=n.slice(0,c),f=n.substr(l),p=h+f;return r?r[s]=p:t=p,{doc:t,old:n}}toJson(t){return typeof this.str=="string"?{op:"str_del",path:W(this.path),pos:this.pos,str:this.str}:{op:"str_del",path:W(this.path),pos:this.pos,len:this.len}}toCompact(t,n){const s=n?"str_del":7;return typeof this.str=="string"?[s,this.path,this.pos,this.str]:[s,this.path,this.pos,0,this.len]}encode(t,n){const s=typeof this.str=="string";t.encodeArrayHeader(s?4:5),t.writer.u8(7),t.encodeArray(this.path),t.encodeNumber(this.pos),s?t.encodeString(this.str):(t.writer.u8(0),t.encodeNumber(this.len))}}const{isArray:bu}=Array,Os=i=>!!i&&typeof i=="object"&&typeof i.text=="string",xs=i=>!!i&&typeof i=="object"&&bu(i.children),ku=(i,e)=>{const t=new RegExp(i,e?"i":void 0);return n=>t.test(n)};class Cu extends Le{constructor(t,n,s){super(t);A(this,"pos");A(this,"props");this.pos=n,this.props=s}op(){return"split"}code(){return 10}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");const s=this.split(n.val);return rs(n)?n.obj[n.key]=s:xn(n)?(n.obj[n.key]=s[0],n.obj.splice(n.key+1,0,s[1])):t=s,{doc:t,old:n.val}}split(t){if(typeof t=="string"){const{pos:n,props:s}=this,r=t.slice(0,n),o=t.slice(n);return s?[{...s,text:r},{...s,text:o}]:[r,o]}else if(Os(t)){const{pos:n,props:s}=this,r=t.text.slice(0,n),o=t.text.slice(n);return[{...t,...s,text:r},{...t,...s,text:o}]}else if(xs(t)){const{pos:n,props:s}=this,r=t.children.slice(0,n),o=t.children.slice(n);return[{...t,...s,children:r},{...t,...s,children:o}]}else if(typeof t=="number"){const{pos:n}=this;return[n,t-n]}else return[t,t]}toJson(t){const n={op:"split",path:W(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"split":10;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){t.encodeArrayHeader(this.props?4:3),t.writer.u8(10),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeObject(this.props)}}class Tu extends Le{constructor(t,n,s){super(t);A(this,"pos");A(this,"props");this.pos=n,this.props=s}op(){return"merge"}code(){return 11}apply(t){const n=ne(t,this.path);if(!xn(n))throw new Error("INVALID_TARGET");if(n.key<=0)throw new Error("INVALID_KEY");const s=n.obj[n.key-1],r=n.obj[n.key],o=this.merge(s,r);return n.obj[n.key-1]=o,n.obj.splice(n.key,1),{doc:t,old:[s,r]}}merge(t,n){return typeof t=="string"&&typeof n=="string"||typeof t=="number"&&typeof n=="number"?t+n:Os(t)&&Os(n)?{...t,...n,text:t.text+n.text}:xs(t)&&xs(n)?{...t,...n,children:[...t.children,...n.children]}:[t,n]}toJson(t){const n={op:"merge",path:W(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"merge":11;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){t.encodeArrayHeader(this.props?4:3),t.writer.u8(11),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeAny(this.props)}}const{isArray:Su}=Array;class wu extends Le{constructor(t,n,s){super(t);A(this,"props");A(this,"deleteNull");this.props=n,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const n=ne(t,this.path);return xn(n)?n.val!==void 0&&(n.obj[n.key]=this.extend(n.val)):rs(n)?n.obj[n.key]=this.extend(n.val):t=this.extend(t),{doc:t}}extend(t){if(Su(t)||typeof t!="object"||!t)return t;for(const[n,s]of Object.entries(this.props)){if(n==="__proto__")throw new Error("NO_PROTO");if(s===null&&this.deleteNull){delete t[n];continue}t[n]=s}return t}toJson(t){const n={op:"extend",path:W(this.path),props:this.props};return this.deleteNull&&(n.deleteNull=this.deleteNull),n}toCompact(t,n){const s=n?"extend":12;return this.deleteNull?[s,this.path,this.props,1]:[s,this.path,this.props]}encode(t,n){const{deleteNull:s}=this;t.encodeArrayHeader(s?4:3),t.writer.u8(12),t.encodeArray(this.path),t.encodeObject(this.props),s&&t.writer.u8(1)}}class Eu extends Re{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=ne(e,this.path);return t!==void 0}toJson(e){return{op:"defined",path:W(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"defined":31,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(31),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}class Pu extends Re{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=ne(e,this.path);return t===void 0}catch(t){if(t.message==="NOT_FOUND")return!0;throw t}}toJson(e){return{op:"undefined",path:W(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"undefined":38,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(38),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}const{isArray:_u}=Array;class Ru extends Re{constructor(t,n){super(t);A(this,"type");this.type=n}op(){return"test_type"}code(){return 39}test(t){const{val:n}=ne(t,this.path);return n===null?this.type.indexOf("null")>-1:_u(n)?this.type.indexOf("array")>-1:this.type.indexOf(typeof n)>-1||typeof n=="number"&&n===Math.round(n)&&this.type.indexOf("integer")>-1}toJson(t){return{op:"test_type",path:W(t?this.path.slice(t.path.length):this.path),type:this.type}}toCompact(t,n){return[n?"test_type":39,t?this.path.slice(t.path.length):this.path,this.type]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(39),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.type)}}class Ou extends Re{constructor(t,n,s,r){super(t);A(this,"pos");A(this,"str");A(this,"not");this.pos=n,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=n.length,r=Math.min(this.pos,s),o=Math.min(this.pos+this.str.length,s),a=n.substring(r,o)===this.str;return this.not?!a:a}toJson(t){const n={op:"test_string",path:W(t?this.path.slice(t.path.length):this.path),pos:this.pos,str:this.str};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"test_string":40,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.pos,this.str,1]:[s,r,this.pos,this.str]}encode(t,n){t.encodeArrayHeader(this.not?5:4),t.writer.u8(40),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.pos),t.encodeString(this.str),this.not&&t.writer.u8(1)}}class xu extends Re{constructor(t,n,s){super(t);A(this,"len");A(this,"not");this.len=n,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const r=n.length>=this.len;return this.not?!r:r}toJson(t){const n={op:"test_string_len",path:W(t?this.path.slice(t.path.length):this.path),len:this.len};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"test_string_len":41,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.len,1]:[s,r,this.len]}encode(t,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(41),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.len),this.not&&t.writer.u8(1)}}class Iu extends Re{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.indexOf(r)>-1}toJson(t){const n={op:"contains",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"contains":30;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(30),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Nu extends Re{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.endsWith(r)}toJson(t){const n={op:"ends",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"ends":32;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(32),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Au extends Re{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.startsWith(r)}toJson(t){const n={op:"starts",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"starts":37;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(37),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Mu extends Re{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"in"}code(){return 33}test(t){const{val:n}=ne(t,this.path);for(const s of this.value)if(Yn(n,s))return!0;return!1}toJson(t){return{op:"in",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"in":33,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(33),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.value)}}class Du extends Re{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"less"}code(){return 34}test(t){const{val:n}=ne(t,this.path);return typeof n!="number"?!1:n<this.value}toJson(t){return{op:"less",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"less":34,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(34),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class Lu extends Re{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"more"}code(){return 36}test(t){const{val:n}=ne(t,this.path);return typeof n!="number"?!1:n>this.value}toJson(t){return{op:"more",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"more":36,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(36),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class ar extends Re{constructor(t,n){super(t);A(this,"ops");this.ops=n}}class Uu extends ar{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"and"}code(){return 43}test(t){for(const n of this.ops)if(!n.test(t))return!1;return!0}toJson(t){return{op:"and",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"and":43,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){const s=n?this.path.slice(n.path.length):this.path;t.encodeArrayHeader(3),t.writer.u8(43),t.encodeArray(s);const r=this.ops.length;t.encodeArrayHeader(r);for(let o=0;o<r;o++)this.ops[o].encode(t,this)}}class Fu extends ar{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"or"}code(){return 45}test(t){for(const n of this.ops)if(n.test(t))return!0;return!1}toJson(t){return{op:"or",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"or":45,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(45),t.encodeArray(n?this.path.slice(n.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class ju extends ar{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"not"}code(){return 44}test(t){for(const n of this.ops)if(n.test(t))return!1;return!0}toJson(t){return{op:"not",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"not":44,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(44),t.encodeArray(n?this.path.slice(n.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class Bu extends Re{constructor(t,n,s,r){super(t);A(this,"value");A(this,"ignore_case");A(this,"matcher");this.value=n,this.ignore_case=s,this.matcher=r(n,s)}op(){return"matches"}code(){return 35}test(t){const{val:n}=ne(t,this.path);return typeof n!="string"?!1:this.matcher(n)}toJson(t){const n={op:"matches",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"matches":35;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(35),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}const{isArray:Ju}=Array;class Vu extends Re{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"type"}code(){return 42}test(t){const{val:n}=ne(t,this.path);return n===null?this.value==="null":Ju(n)?this.value==="array":typeof n===this.value||typeof n=="number"&&n===Math.round(n)&&this.value==="integer"}toJson(t){return{op:"type",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"type":42,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(42),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value)}}const qu=(i,e)=>{switch(i.op){case"add":return new or(J(i.path),i.value);case"remove":return new Ao(J(i.path),i.oldValue);case"replace":return new du(J(i.path),i.value,i.oldValue);case"move":return new hu(J(i.path),J(i.from));case"copy":return new fu(J(i.path),J(i.from));case"flip":return new mu(J(i.path));case"inc":return new gu(J(i.path),i.inc);case"str_ins":return new vu(J(i.path),i.pos,i.str);case"str_del":return new yu(J(i.path),i.pos,i.str,i.len);case"split":return new Cu(J(i.path),i.pos,i.props||null);case"merge":return new Tu(J(i.path),i.pos,i.props||null);case"extend":return new wu(J(i.path),i.props,!!i.deleteNull);default:return jn(i,e)}},jn=(i,e)=>{switch(i.op){case"test":return new pu(J(i.path),i.value,!!i.not);case"defined":return new Eu(J(i.path));case"undefined":return new Pu(J(i.path));case"type":return new Vu(J(i.path),i.value);case"test_type":return new Ru(J(i.path),i.type);case"test_string":return new Ou(J(i.path),i.pos,i.str,!!i.not);case"test_string_len":return new xu(J(i.path),i.len,!!i.not);case"contains":return new Iu(J(i.path),i.value,!!i.ignore_case);case"ends":return new Nu(J(i.path),i.value,!!i.ignore_case);case"starts":return new Au(J(i.path),i.value,!!i.ignore_case);case"matches":return new Bu(J(i.path),i.value,!!i.ignore_case,e.createMatcher||ku);case"in":return new Mu(J(i.path),i.value);case"less":return new Du(J(i.path),i.value);case"more":return new Lu(J(i.path),i.value);case"and":{const t=J(i.path);return new Uu(t,i.apply.map(n=>jn({...n,path:[...t,...J(n.path)]},e)))}case"or":{const t=J(i.path);return new Fu(t,i.apply.map(n=>jn({...n,path:[...t,...J(n.path)]},e)))}case"not":{const t=J(i.path);return new ju(t,i.apply.map(n=>jn({...n,path:[...t,...J(n.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function $u(i,e,t){t.mutate||(i=Tn(i));const n=[],s=e.length;for(let r=0;r<s;r++){const a=qu(e[r],t).apply(i);i=a.doc,n.push(a)}return{doc:i,res:n}}var hn=i=>typeof i=="function"?i:function(){return i},Hu=typeof self<"u"?self:null,cn=typeof window<"u"?window:null,fn=Hu||cn||fn,zu="2.0.0",st={connecting:0,open:1,closing:2,closed:3},Gu=1e4,Wu=1e3,Ne={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ot={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Is={longpoll:"longpoll",websocket:"websocket"},Ku={complete:4},Mn=class{constructor(i,e,t,n){this.channel=i,this.event=e,this.payload=t||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(i){this.timeout=i,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(i,e){return this.hasReceived(i)&&e(this.receivedResp.response),this.recHooks.push({status:i,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:i,response:e,_ref:t}){this.recHooks.filter(n=>n.status===i).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,i=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=i,this.matchReceive(i)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(i){return this.receivedResp&&this.receivedResp.status===i}trigger(i,e){this.channel.trigger(this.refEvent,{status:i,response:e})}},Mo=class{constructor(i,e){this.callback=i,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Yu=class{constructor(i,e,t){this.state=Ne.closed,this.topic=i,this.params=hn(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Mn(this,Ot.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Mo(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Ne.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=Ne.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=Ne.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Ne.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new Mn(this,Ot.leave,hn({}),this.timeout).send(),this.state=Ne.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Ot.reply,(n,s)=>{this.trigger(this.replyEventName(s),n)})}join(i=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=i,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(i){this.on(Ot.close,i)}onError(i){return this.on(Ot.error,e=>i(e))}on(i,e){let t=this.bindingRef++;return this.bindings.push({event:i,ref:t,callback:e}),t}off(i,e){this.bindings=this.bindings.filter(t=>!(t.event===i&&(typeof e>"u"||e===t.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(i,e,t=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${i}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Mn(this,i,function(){return e},t);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(i=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Ne.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Ot.close,"leave")},t=new Mn(this,Ot.leave,hn({}),i);return t.receive("ok",()=>e()).receive("timeout",()=>e()),t.send(),this.canPush()||t.trigger("ok",{}),t}onMessage(i,e,t){return e}isMember(i,e,t,n){return this.topic!==i?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:i,event:e,payload:t,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(i=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Ne.joining,this.joinPush.resend(i))}trigger(i,e,t,n){let s=this.onMessage(i,e,t,n);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===i);for(let o=0;o<r.length;o++)r[o].callback(s,t,n||this.joinRef())}replyEventName(i){return`chan_reply_${i}`}isClosed(){return this.state===Ne.closed}isErrored(){return this.state===Ne.errored}isJoined(){return this.state===Ne.joined}isJoining(){return this.state===Ne.joining}isLeaving(){return this.state===Ne.leaving}},Xn=class{static request(i,e,t,n,s,r,o){if(fn.XDomainRequest){let a=new fn.XDomainRequest;return this.xdomainRequest(a,i,e,n,s,r,o)}else{let a=new fn.XMLHttpRequest;return this.xhrRequest(a,i,e,t,n,s,r,o)}}static xdomainRequest(i,e,t,n,s,r,o){return i.timeout=s,i.open(e,t),i.onload=()=>{let a=this.parseJSON(i.responseText);o&&o(a)},r&&(i.ontimeout=r),i.onprogress=()=>{},i.send(n),i}static xhrRequest(i,e,t,n,s,r,o,a){return i.open(e,t,!0),i.timeout=r,i.setRequestHeader("Content-Type",n),i.onerror=()=>a&&a(null),i.onreadystatechange=()=>{if(i.readyState===Ku.complete&&a){let c=this.parseJSON(i.responseText);a(c)}},o&&(i.ontimeout=o),i.send(s),i}static parseJSON(i){if(!i||i==="")return null;try{return JSON.parse(i)}catch{return console&&console.log("failed to parse JSON response",i),null}}static serialize(i,e){let t=[];for(var n in i){if(!Object.prototype.hasOwnProperty.call(i,n))continue;let s=e?`${e}[${n}]`:n,r=i[n];typeof r=="object"?t.push(this.serialize(r,s)):t.push(encodeURIComponent(s)+"="+encodeURIComponent(r))}return t.join("&")}static appendParams(i,e){if(Object.keys(e).length===0)return i;let t=i.match(/\?/)?"&":"?";return`${i}${t}${this.serialize(e)}`}},ps=class{constructor(i){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(i),this.readyState=st.connecting,this.poll()}normalizeEndpoint(i){return i.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Is.websocket),"$1/"+Is.longpoll)}endpointURL(){return Xn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(i,e,t){this.close(i,e,t),this.readyState=st.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===st.open||this.readyState===st.connecting}poll(){this.ajax("GET",null,()=>this.ontimeout(),i=>{if(i){var{status:e,token:t,messages:n}=i;this.token=t}else e=0;switch(e){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=st.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(i){this.ajax("POST",i,()=>this.onerror("timeout"),e=>{(!e||e.status!==200)&&(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(i,e,t){for(let s of this.reqs)s.abort();this.readyState=st.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:i,reason:e,wasClean:t});typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(i,e,t,n){let s,r=()=>{this.reqs.delete(s),t()};s=Xn.request(i,this.endpointURL(),"application/json",e,this.timeout,r,o=>{this.reqs.delete(s),this.isActive()&&n(o)}),this.reqs.add(s)}},Dn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(i,e){if(i.payload.constructor===ArrayBuffer)return e(this.binaryEncode(i));{let t=[i.join_ref,i.ref,i.topic,i.event,i.payload];return e(JSON.stringify(t))}},decode(i,e){if(i.constructor===ArrayBuffer)return e(this.binaryDecode(i));{let[t,n,s,r,o]=JSON.parse(i);return e({join_ref:t,ref:n,topic:s,event:r,payload:o})}},binaryEncode(i){let{join_ref:e,ref:t,event:n,topic:s,payload:r}=i,o=this.META_LENGTH+e.length+t.length+s.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(a),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,e.length),c.setUint8(u++,t.length),c.setUint8(u++,s.length),c.setUint8(u++,n.length),Array.from(e,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(t,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(u++,h.charCodeAt(0)));var l=new Uint8Array(a.byteLength+r.byteLength);return l.set(new Uint8Array(a),0),l.set(new Uint8Array(r),a.byteLength),l.buffer},binaryDecode(i){let e=new DataView(i),t=e.getUint8(0),n=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(i,e,n);case this.KINDS.reply:return this.decodeReply(i,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(i,e,n)}},decodePush(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=t.decode(i.slice(o,o+n));o=o+n;let c=t.decode(i.slice(o,o+s));o=o+s;let u=t.decode(i.slice(o,o+r));o=o+r;let l=i.slice(o,i.byteLength);return{join_ref:a,ref:null,topic:c,event:u,payload:l}},decodeReply(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(i.slice(a,a+n));a=a+n;let u=t.decode(i.slice(a,a+s));a=a+s;let l=t.decode(i.slice(a,a+r));a=a+r;let h=t.decode(i.slice(a,a+o));a=a+o;let f=i.slice(a,i.byteLength),p={status:h,response:f};return{join_ref:c,ref:u,topic:l,event:Ot.reply,payload:p}},decodeBroadcast(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,o=t.decode(i.slice(r,r+n));r=r+n;let a=t.decode(i.slice(r,r+s));r=r+s;let c=i.slice(r,i.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},Xu=class{constructor(i,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||Gu,this.transport=e.transport||fn.WebSocket||ps,this.establishedConnections=0,this.defaultEncoder=Dn.encode.bind(Dn),this.defaultDecoder=Dn.decode.bind(Dn),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==ps?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;cn&&cn.addEventListener&&(cn.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),t=this.connectClock)}),cn.addEventListener("pageshow",n=>{t===this.connectClock&&(t=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=hn(e.params||{}),this.endPoint=`${i}/${Is.websocket}`,this.vsn=e.vsn||zu,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Mo(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return ps}replaceTransport(i){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.sendBuffer=[],this.conn&&(this.conn.close(),this.conn=null),this.transport=i}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let i=Xn.appendParams(Xn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return i.charAt(0)!=="/"?i:i.charAt(1)==="/"?`${this.protocol()}:${i}`:`${this.protocol()}://${location.host}${i}`}disconnect(i,e,t){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(i,e,t)}connect(i){i&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=hn(i)),!this.conn&&(this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e))}log(i,e,t){this.logger(i,e,t)}hasLogger(){return this.logger!==null}onOpen(i){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,i]),e}onClose(i){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,i]),e}onError(i){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,i]),e}onMessage(i){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,i]),e}ping(i){if(!this.isConnected())return!1;let e=this.makeRef(),t=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(s=>{s.ref===e&&(this.off([n]),i(Date.now()-t))});return!0}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,i])=>i())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Wu,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(i,e,t){if(!this.conn)return i&&i();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,t||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),i&&i()})})}waitForBufferDone(i,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){i();return}setTimeout(()=>{this.waitForBufferDone(i,e+1)},150*e)}waitForSocketClosed(i,e=1){if(e===5||!this.conn||this.conn.readyState===st.closed){i();return}setTimeout(()=>{this.waitForSocketClosed(i,e+1)},150*e)}onConnClose(i){let e=i&&i.code;this.hasLogger()&&this.log("transport","close",i),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(i))}onConnError(i){this.hasLogger()&&this.log("transport",i);let e=this.transport,t=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,n])=>{n(i,e,t)}),(e===this.transport||t>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(i=>{i.isErrored()||i.isLeaving()||i.isClosed()||i.trigger(Ot.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case st.connecting:return"connecting";case st.open:return"open";case st.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(i){this.off(i.stateChangeRefs),this.channels=this.channels.filter(e=>e.joinRef()!==i.joinRef())}off(i){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([t])=>i.indexOf(t)===-1)}channel(i,e={}){let t=new Yu(i,e,this);return this.channels.push(t),t}push(i){if(this.hasLogger()){let{topic:e,event:t,payload:n,ref:s,join_ref:r}=i;this.log("push",`${e} ${t} (${r}, ${s})`,n)}this.isConnected()?this.encode(i,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(i,e=>this.conn.send(e)))}makeRef(){let i=this.ref+1;return i===this.ref?this.ref=0:this.ref=i,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(i=>i()),this.sendBuffer=[])}onConnMessage(i){this.decode(i.data,e=>{let{topic:t,event:n,payload:s,ref:r,join_ref:o}=e;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${n} ${r&&"("+r+")"||""}`,s);for(let a=0;a<this.channels.length;a++){const c=this.channels[a];c.isMember(t,n,s,o)&&c.trigger(n,s,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,c]=this.stateChangeCallbacks.message[a];c(e)}})}leaveOpenTopic(i){let e=this.channels.find(t=>t.topic===i&&(t.isJoined()||t.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${i}"`),e.leave())}};class Qu{constructor(e){this.connected=!1,this.config=e,this.socket=new Xu(this.config.url,this.config.socketOptions||{logger:(t,n,s)=>{console.debug(`${t}: ${n}`,s)}}),this.channel=this.socket.channel(this.config.topic,this.config.params),this.eventTarget=new EventTarget}connect(){this.connected||(this.socket.onError(e=>this.emitError("socket error",e)),this.socket.connect(),this.channel.onError(e=>this.emitError("channel error",e)),this.channel.join().receive("ok",e=>{console.debug("channel joined",e)}).receive("error",e=>{this.emitError("channel join error",e)}),this.channel.on("state:change",e=>this.handleChange(e)),this.channel.on("state:patch",e=>this.handlePatch(e)),this.channel.on("error",e=>this.emitServerError(e)),this.connected=!0)}disconnect(){this.channel&&this.channel.leave(),this.socket.disconnect(),this.connected=!1}addEventListener(e,t,n){var s;this.eventTarget.addEventListener(e,t,n),e.startsWith("livestate-")||(s=this.channel)==null||s.on(e,r=>{this.eventTarget.dispatchEvent(new CustomEvent(e,{detail:r}))})}removeEventListener(e,t,n){return this.eventTarget.removeEventListener(e,t,n)}subscribe(e){this.addEventListener("livestate-change",e)}unsubscribe(e){this.removeEventListener("livestate-change",e)}emitServerError(e){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:e}))}emitError(e,t){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:{type:e,message:this.extractMessage(t)}}))}extractMessage(e){if(e&&typeof(e=="object")){const t=[e.reason,e.name,e.message].find(n=>n);return console.log(t),t}else if(typeof e=="string")return e}handleChange({state:e,version:t}){this.state=e,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}handlePatch({patch:e,version:t}){if(this.eventTarget.dispatchEvent(new CustomEvent("livestate-patch",{detail:{patch:e,version:t}})),this.versionMatches(t)){const{doc:n,res:s}=$u(this.state,e,{mutate:!1});this.state=n,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}else this.channel.push("lvs_refresh")}versionMatches(e){return e===this.stateVersion+1||e===0}pushEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}dispatchEvent(e){return this.channel.push(`lvs_evt:${e.type}`,e.detail),!0}pushCustomEvent(e){this.dispatchEvent(e)}}const Do=32;let le,He,Qn=i=>(le=0,He=i,i=li(),He[le]?ai():i||""),ai=(i="Bad syntax",e=He[le],t=He.slice(0,le).split(`
|
|
1
|
+
"use strict";var Pc=Object.defineProperty;var _c=(i,e,t)=>e in i?Pc(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var A=(i,e,t)=>(_c(i,typeof e!="symbol"?e+"":e,t),t);const Pr=require("./constants-DfeL-H6H.cjs");function kn(){}function Ro(i){return i()}function _r(){return Object.create(null)}function On(i){i.forEach(Ro)}function Oo(i){return typeof i=="function"}function Rc(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}function Oc(i){return Object.keys(i).length===0}function Me(i,e){i.appendChild(e)}function xc(i,e,t){const n=Ic(i);if(!n.getElementById(e)){const s=$e("style");s.id=e,s.textContent=t,Nc(n,s)}}function Ic(i){if(!i)return document;const e=i.getRootNode?i.getRootNode():i.ownerDocument;return e&&e.host?e:i.ownerDocument}function Nc(i,e){return Me(i.head||i,e),e.sheet}function Ti(i,e,t){i.insertBefore(e,t||null)}function yi(i){i.parentNode&&i.parentNode.removeChild(i)}function $e(i){return document.createElement(i)}function Rr(i){return document.createElementNS("http://www.w3.org/2000/svg",i)}function or(i){return document.createTextNode(i)}function an(){return or(" ")}function Ac(){return or("")}function q(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function Mc(i){return Array.from(i.childNodes)}function Dc(i,e){e=""+e,i.data!==e&&(i.data=e)}function it(i,e,t,n){t==null?i.style.removeProperty(e):i.style.setProperty(e,t,n?"important":"")}function Lc(i){const e={};return i.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let Cn;function dn(i){Cn=i}function xo(){if(!Cn)throw new Error("Function called outside component initialization");return Cn}function Uc(i){xo().$$.on_mount.push(i)}function Fc(i){xo().$$.on_destroy.push(i)}const Ui=[],_s=[];let Bi=[];const Or=[],jc=Promise.resolve();let Rs=!1;function Bc(){Rs||(Rs=!0,jc.then(hi))}function Os(i){Bi.push(i)}const ps=new Set;let Mi=0;function hi(){if(Mi!==0)return;const i=Cn;do{try{for(;Mi<Ui.length;){const e=Ui[Mi];Mi++,dn(e),Jc(e.$$)}}catch(e){throw Ui.length=0,Mi=0,e}for(dn(null),Ui.length=0,Mi=0;_s.length;)_s.pop()();for(let e=0;e<Bi.length;e+=1){const t=Bi[e];ps.has(t)||(ps.add(t),t())}Bi.length=0}while(Ui.length);for(;Or.length;)Or.pop()();Rs=!1,ps.clear(),dn(i)}function Jc(i){if(i.fragment!==null){i.update(),On(i.before_update);const e=i.dirty;i.dirty=[-1],i.fragment&&i.fragment.p(i.ctx,e),i.after_update.forEach(Os)}}function Vc(i){const e=[],t=[];Bi.forEach(n=>i.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),Bi=e}const qc=new Set;function Io(i,e){i&&i.i&&(qc.delete(i),i.i(e))}function xr(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function $c(i,e){i.d(1),e.delete(i.key)}function Hc(i,e,t,n,s,r,o,a,c,u,l,h){let f=i.length,p=r.length,y=f;const v={};for(;y--;)v[i[y].key]=y;const w=[],S=new Map,E=new Map,J=[];for(y=p;y--;){const U=h(s,r,y),ee=t(U);let M=o.get(ee);M?n&&J.push(()=>M.p(U,e)):(M=u(ee,U),M.c()),S.set(ee,w[y]=M),ee in v&&E.set(ee,Math.abs(y-v[ee]))}const K=new Set,me=new Set;function de(U){Io(U,1),U.m(a,l),o.set(U.key,U),l=U.first,p--}for(;f&&p;){const U=w[p-1],ee=i[f-1],M=U.key,H=ee.key;U===ee?(l=U.first,f--,p--):S.has(H)?!o.has(M)||K.has(M)?de(U):me.has(H)?f--:E.get(M)>E.get(H)?(me.add(M),de(U)):(K.add(H),f--):(c(ee,o),f--)}for(;f--;){const U=i[f];S.has(U.key)||c(U,o)}for(;p;)de(w[p-1]);return On(J),w}function zc(i,e,t){const{fragment:n,after_update:s}=i.$$;n&&n.m(e,t),Os(()=>{const r=i.$$.on_mount.map(Ro).filter(Oo);i.$$.on_destroy?i.$$.on_destroy.push(...r):On(r),i.$$.on_mount=[]}),s.forEach(Os)}function Gc(i,e){const t=i.$$;t.fragment!==null&&(Vc(t.after_update),On(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function Wc(i,e){i.$$.dirty[0]===-1&&(Ui.push(i),Bc(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<<e%31}function Kc(i,e,t,n,s,r,o=null,a=[-1]){const c=Cn;dn(i);const u=i.$$={fragment:null,ctx:[],props:r,update:kn,not_equal:s,bound:_r(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:_r(),dirty:a,skip_bound:!1,root:e.target||c.$$.root};o&&o(u.root);let l=!1;if(u.ctx=t?t(i,e.props||{},(h,f,...p)=>{const y=p.length?p[0]:f;return u.ctx&&s(u.ctx[h],u.ctx[h]=y)&&(!u.skip_bound&&u.bound[h]&&u.bound[h](y),l&&Wc(i,h)),f}):[],u.update(),l=!0,On(u.before_update),u.fragment=n?n(u.ctx):!1,e.target){if(e.hydrate){const h=Mc(e.target);u.fragment&&u.fragment.l(h),h.forEach(yi)}else u.fragment&&u.fragment.c();e.intro&&Io(i.$$.fragment),zc(i,e.target,e.anchor),hi()}dn(c)}let No;typeof HTMLElement=="function"&&(No=class extends HTMLElement{constructor(e,t,n){super();A(this,"$$ctor");A(this,"$$s");A(this,"$$c");A(this,"$$cn",!1);A(this,"$$d",{});A(this,"$$r",!1);A(this,"$$p_d",{});A(this,"$$l",{});A(this,"$$l_u",new Map);this.$$ctor=e,this.$$s=t,n&&this.attachShadow({mode:"open"})}addEventListener(e,t,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const s=this.$$c.$on(e,t);this.$$l_u.set(t,s)}super.addEventListener(e,t,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),this.$$c){const s=this.$$l_u.get(t);s&&(s(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(r){return()=>{let o;return{c:function(){o=$e("slot"),r!=="default"&&q(o,"name",r)},m:function(u,l){Ti(u,o,l)},d:function(u){u&&yi(o)}}}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},n=Lc(this);for(const r of this.$$s)r in n&&(t[r]=[e(r)]);for(const r of this.attributes){const o=this.$$g_p(r.name);o in this.$$d||(this.$$d[o]=jn(o,r.value,this.$$p_d,"toProp"))}for(const r in this.$$p_d)!(r in this.$$d)&&this[r]!==void 0&&(this.$$d[r]=this[r],delete this[r]);this.$$c=new this.$$ctor({target:this.shadowRoot||this,props:{...this.$$d,$$slots:t,$$scope:{ctx:[]}}});const s=()=>{this.$$r=!0;for(const r in this.$$p_d)if(this.$$d[r]=this.$$c.$$.ctx[this.$$c.$$.props[r]],this.$$p_d[r].reflect){const o=jn(r,this.$$d[r],this.$$p_d,"toAttribute");o==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,o)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const o of this.$$l[r]){const a=this.$$c.$on(r,o);this.$$l_u.set(o,a)}this.$$l={}}}attributeChangedCallback(e,t,n){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=jn(e,n,this.$$p_d,"toProp"),(s=this.$$c)==null||s.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{this.$$cn||(this.$$c.$destroy(),this.$$c=void 0)})}$$g_p(e){return Object.keys(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function jn(i,e,t,n){var r;const s=(r=t[i])==null?void 0:r.type;if(e=s==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!t[i])return e;if(n==="toAttribute")switch(s){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(s){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function Yc(i,e,t,n,s,r){let o=class extends No{constructor(){super(i,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(a=>(e[a].attribute||a).toLowerCase())}};return Object.keys(e).forEach(a=>{Object.defineProperty(o.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(c){var u;c=jn(a,c,e),this.$$d[a]=c,(u=this.$$c)==null||u.$set({[a]:c})}})}),n.forEach(a=>{Object.defineProperty(o.prototype,a,{get(){var c;return(c=this.$$c)==null?void 0:c[a]}})}),r&&(o=r(o)),i.element=o,o}class Xc{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Gc(this,1),this.$destroy=kn}$on(e,t){if(!Oo(t))return kn;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const s=n.indexOf(t);s!==-1&&n.splice(s,1)}}$set(e){this.$$set&&!Oc(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Qc="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Qc);const{isArray:Zc}=Array,eu=Object.keys,Tn=i=>{if(!i)return i;if(Zc(i)){const e=[],t=i.length;for(let n=0;n<t;n++)e.push(Tn(i[n]));return e}else if(typeof i=="object"){const e=eu(i),t=e.length,n={};for(let s=0;s<t;s++){const r=e[s];n[r]=Tn(i[r])}return n}return i};class Ue{constructor(e){A(this,"path");A(this,"from");this.path=e}}const tu=/~1/g,iu=/~0/g,nu=/~/g,su=/\//g;function ru(i){return i.indexOf("~")===-1?i:i.replace(tu,"/").replace(iu,"~")}function ou(i){return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(nu,"~0").replace(su,"~1")}function au(i){return i?i.slice(1).split("/").map(ru):[]}function W(i){return cu(i)?"":"/"+i.map(e=>ou(String(e))).join("/")}const V=i=>typeof i=="string"?au(i):i,cu=i=>!i.length,uu=Object.prototype.hasOwnProperty;function lu(i,e){return uu.call(i,e)}const{isArray:Ao}=Array,ne=(i,e)=>{const t=e.length;if(!t)return{val:i};let n,s;for(let o=0;o<t;o++)if(n=i,s=e[o],Ao(n)){const a=n.length;if(s==="-")s=a;else if(typeof s=="string"){const c=~~s;if(""+c!==s)throw new Error("INVALID_INDEX");if(s=c,s<0)throw new Error("INVALID_INDEX")}i=n[s]}else if(typeof n=="object"&&n)i=lu(n,s)?n[s]:void 0;else throw new Error("NOT_FOUND");return{val:i,obj:n,key:s}},xn=i=>Ao(i.obj)&&typeof i.key=="number",os=i=>typeof i.obj=="object"&&typeof i.key=="string";class ar extends Ue{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"add"}code(){return 0}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path),o=Tn(this.value);if(!r)t=o;else if(typeof s=="string")r[s]=o;else{const a=r.length;if(s<a)r.splice(s,0,o);else{if(s>a)throw new Error("INVALID_INDEX");r.push(o)}}return{doc:t,old:n}}toJson(t){return{op:"add",path:W(this.path),value:this.value}}toCompact(t,n){return[n?"add":0,this.path,this.value]}encode(t){t.encodeArrayHeader(3),t.writer.u8(0),t.encodeArray(this.path),t.encodeAny(this.value)}}class Mo extends Ue{constructor(t,n){super(t);A(this,"oldValue");this.oldValue=n}op(){return"remove"}code(){return 1}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return os(n)?delete n.obj[n.key]:xn(n)?n.val!==void 0&&n.obj.splice(n.key,1):t=null,{doc:t,old:n.val}}toJson(t){const n={op:"remove",path:W(this.path)};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"remove":1;return this.oldValue===void 0?[s,this.path]:[s,this.path,this.oldValue]}encode(t,n){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?3:2),t.writer.u8(1),t.encodeArray(this.path),s&&t.encodeAny(this.oldValue)}}class du extends Ue{constructor(t,n,s){super(t);A(this,"value");A(this,"oldValue");this.value=n,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return os(n)?n.obj[n.key]=this.value:xn(n)?n.obj[n.key]=this.value:t=this.value,{doc:t,old:n.val}}toJson(t){const n={op:"replace",path:W(this.path),value:this.value};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"replace":2;return this.oldValue===void 0?[s,this.path,this.value]:[s,this.path,this.value,this.oldValue]}encode(t,n){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?4:3),t.writer.u8(2),t.encodeArray(this.path),t.encodeAny(this.value),s&&t.encodeAny(this.oldValue)}}class hu extends Ue{constructor(t,n){super(t);A(this,"from");this.from=n}op(){return"move"}code(){return 4}apply(t){const n=new Mo(V(this.from),void 0).apply(t);return new ar(this.path,n.old).apply(n.doc)}toJson(t){return{op:"move",path:W(this.path),from:W(this.from)}}toCompact(t,n){return[n?"move":4,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(4),t.encodeArray(this.path),t.encodeArray(this.from)}}class fu extends Ue{constructor(t,n){super(t);A(this,"from");this.from=n}op(){return"copy"}code(){return 3}apply(t){const{val:n}=ne(t,this.from);if(n===void 0)throw new Error("NOT_FOUND");return new ar(this.path,Tn(n)).apply(t)}toJson(t){return{op:"copy",path:W(this.path),from:W(this.from)}}toCompact(t,n){return[n?"copy":3,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(3),t.encodeArray(this.path),t.encodeArray(this.from)}}class Oe extends Ue{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const Xn=(i,e)=>{if(i===e)return!0;if(i&&e&&typeof i=="object"&&typeof e=="object"){if(i.constructor!==e.constructor)return!1;let t,n,s;if(Array.isArray(i)){if(t=i.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!Xn(i[n],e[n]))return!1;return!0}if(s=Object.keys(i),t=s.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;){const r=s[n];if(!Xn(i[r],e[r]))return!1}return!0}return!1};class pu extends Oe{constructor(t,n,s){super(t);A(this,"value");A(this,"not");this.value=n,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:n}=ne(t,this.path);if(n===void 0)return!!this.not;const s=Xn(n,this.value);return this.not?!s:s}toJson(t){const n={op:"test",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=t?this.path.slice(t.path.length):this.path,r=n?"test":5;return this.not?[r,s,this.value,1]:[r,s,this.value]}encode(t,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(5),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeAny(this.value),this.not&&t.writer.u8(1)}}class mu extends Ue{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=ne(e,this.path);return t.obj?t.obj[t.key]=!t.val:e=!t.val,{doc:e,old:t.val}}toJson(e){return{op:"flip",path:W(this.path)}}toCompact(e,t){return[t?"flip":8,this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(8),e.encodeArray(this.path)}}class gu extends Ue{constructor(t,n){super(t);A(this,"inc");this.inc=n}op(){return"inc"}code(){return 9}apply(t){const n=ne(t,this.path),s=this.inc+Number(n.val);return n.obj?n.obj[n.key]=s:t=s,{doc:t,old:n.val}}toJson(t){return{op:"inc",path:W(this.path),inc:this.inc}}toCompact(t,n){return[n?"inc":9,this.path,this.inc]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(9),t.encodeArray(this.path),t.encodeNumber(this.inc)}}class vu extends Ue{constructor(t,n,s){super(t);A(this,"pos");A(this,"str");this.pos=n,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path);if(typeof n!="string"){if(n!==void 0)throw new Error("NOT_A_STRING");if(this.pos!==0)throw new Error("POS")}const o=typeof n=="string"?n:"",a=Math.min(this.pos,o.length),c=o.slice(0,a),u=o.slice(a),l=c+this.str+u;return r?r[s]=l:t=l,{doc:t,old:n}}toJson(t){return{op:"str_ins",path:W(this.path),pos:this.pos,str:this.str}}toCompact(t,n){return[n?"str_ins":6,this.path,this.pos,this.str]}encode(t,n){t.encodeArrayHeader(4),t.writer.u8(6),t.encodeArray(this.path),t.encodeNumber(this.pos),t.encodeString(this.str)}}class yu extends Ue{constructor(t,n,s,r){super(t);A(this,"pos");A(this,"str");A(this,"len");this.pos=n,this.str=s,this.len=r}op(){return"str_del"}code(){return 7}deleteLength(){return typeof this.str=="string"?this.str.length:this.len}apply(t){const{val:n,key:s,obj:r}=ne(t,this.path);if(typeof n!="string")throw new Error("NOT_A_STRING");const o=n.length,a=Math.min(this.pos,n.length),c=Math.min(a,o),u=this.str!==void 0?this.str.length:this.len,l=Math.min(a+u,o),h=n.slice(0,c),f=n.substr(l),p=h+f;return r?r[s]=p:t=p,{doc:t,old:n}}toJson(t){return typeof this.str=="string"?{op:"str_del",path:W(this.path),pos:this.pos,str:this.str}:{op:"str_del",path:W(this.path),pos:this.pos,len:this.len}}toCompact(t,n){const s=n?"str_del":7;return typeof this.str=="string"?[s,this.path,this.pos,this.str]:[s,this.path,this.pos,0,this.len]}encode(t,n){const s=typeof this.str=="string";t.encodeArrayHeader(s?4:5),t.writer.u8(7),t.encodeArray(this.path),t.encodeNumber(this.pos),s?t.encodeString(this.str):(t.writer.u8(0),t.encodeNumber(this.len))}}const{isArray:bu}=Array,xs=i=>!!i&&typeof i=="object"&&typeof i.text=="string",Is=i=>!!i&&typeof i=="object"&&bu(i.children),ku=(i,e)=>{const t=new RegExp(i,e?"i":void 0);return n=>t.test(n)};class Cu extends Ue{constructor(t,n,s){super(t);A(this,"pos");A(this,"props");this.pos=n,this.props=s}op(){return"split"}code(){return 10}apply(t){const n=ne(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");const s=this.split(n.val);return os(n)?n.obj[n.key]=s:xn(n)?(n.obj[n.key]=s[0],n.obj.splice(n.key+1,0,s[1])):t=s,{doc:t,old:n.val}}split(t){if(typeof t=="string"){const{pos:n,props:s}=this,r=t.slice(0,n),o=t.slice(n);return s?[{...s,text:r},{...s,text:o}]:[r,o]}else if(xs(t)){const{pos:n,props:s}=this,r=t.text.slice(0,n),o=t.text.slice(n);return[{...t,...s,text:r},{...t,...s,text:o}]}else if(Is(t)){const{pos:n,props:s}=this,r=t.children.slice(0,n),o=t.children.slice(n);return[{...t,...s,children:r},{...t,...s,children:o}]}else if(typeof t=="number"){const{pos:n}=this;return[n,t-n]}else return[t,t]}toJson(t){const n={op:"split",path:W(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"split":10;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){t.encodeArrayHeader(this.props?4:3),t.writer.u8(10),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeObject(this.props)}}class Tu extends Ue{constructor(t,n,s){super(t);A(this,"pos");A(this,"props");this.pos=n,this.props=s}op(){return"merge"}code(){return 11}apply(t){const n=ne(t,this.path);if(!xn(n))throw new Error("INVALID_TARGET");if(n.key<=0)throw new Error("INVALID_KEY");const s=n.obj[n.key-1],r=n.obj[n.key],o=this.merge(s,r);return n.obj[n.key-1]=o,n.obj.splice(n.key,1),{doc:t,old:[s,r]}}merge(t,n){return typeof t=="string"&&typeof n=="string"||typeof t=="number"&&typeof n=="number"?t+n:xs(t)&&xs(n)?{...t,...n,text:t.text+n.text}:Is(t)&&Is(n)?{...t,...n,children:[...t.children,...n.children]}:[t,n]}toJson(t){const n={op:"merge",path:W(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"merge":11;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){t.encodeArrayHeader(this.props?4:3),t.writer.u8(11),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeAny(this.props)}}const{isArray:Su}=Array;class wu extends Ue{constructor(t,n,s){super(t);A(this,"props");A(this,"deleteNull");this.props=n,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const n=ne(t,this.path);return xn(n)?n.val!==void 0&&(n.obj[n.key]=this.extend(n.val)):os(n)?n.obj[n.key]=this.extend(n.val):t=this.extend(t),{doc:t}}extend(t){if(Su(t)||typeof t!="object"||!t)return t;for(const[n,s]of Object.entries(this.props)){if(n==="__proto__")throw new Error("NO_PROTO");if(s===null&&this.deleteNull){delete t[n];continue}t[n]=s}return t}toJson(t){const n={op:"extend",path:W(this.path),props:this.props};return this.deleteNull&&(n.deleteNull=this.deleteNull),n}toCompact(t,n){const s=n?"extend":12;return this.deleteNull?[s,this.path,this.props,1]:[s,this.path,this.props]}encode(t,n){const{deleteNull:s}=this;t.encodeArrayHeader(s?4:3),t.writer.u8(12),t.encodeArray(this.path),t.encodeObject(this.props),s&&t.writer.u8(1)}}class Eu extends Oe{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=ne(e,this.path);return t!==void 0}toJson(e){return{op:"defined",path:W(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"defined":31,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(31),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}class Pu extends Oe{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=ne(e,this.path);return t===void 0}catch(t){if(t.message==="NOT_FOUND")return!0;throw t}}toJson(e){return{op:"undefined",path:W(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"undefined":38,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(38),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}const{isArray:_u}=Array;class Ru extends Oe{constructor(t,n){super(t);A(this,"type");this.type=n}op(){return"test_type"}code(){return 39}test(t){const{val:n}=ne(t,this.path);return n===null?this.type.indexOf("null")>-1:_u(n)?this.type.indexOf("array")>-1:this.type.indexOf(typeof n)>-1||typeof n=="number"&&n===Math.round(n)&&this.type.indexOf("integer")>-1}toJson(t){return{op:"test_type",path:W(t?this.path.slice(t.path.length):this.path),type:this.type}}toCompact(t,n){return[n?"test_type":39,t?this.path.slice(t.path.length):this.path,this.type]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(39),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.type)}}class Ou extends Oe{constructor(t,n,s,r){super(t);A(this,"pos");A(this,"str");A(this,"not");this.pos=n,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=n.length,r=Math.min(this.pos,s),o=Math.min(this.pos+this.str.length,s),a=n.substring(r,o)===this.str;return this.not?!a:a}toJson(t){const n={op:"test_string",path:W(t?this.path.slice(t.path.length):this.path),pos:this.pos,str:this.str};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"test_string":40,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.pos,this.str,1]:[s,r,this.pos,this.str]}encode(t,n){t.encodeArrayHeader(this.not?5:4),t.writer.u8(40),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.pos),t.encodeString(this.str),this.not&&t.writer.u8(1)}}class xu extends Oe{constructor(t,n,s){super(t);A(this,"len");A(this,"not");this.len=n,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const r=n.length>=this.len;return this.not?!r:r}toJson(t){const n={op:"test_string_len",path:W(t?this.path.slice(t.path.length):this.path),len:this.len};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"test_string_len":41,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.len,1]:[s,r,this.len]}encode(t,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(41),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.len),this.not&&t.writer.u8(1)}}class Iu extends Oe{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.indexOf(r)>-1}toJson(t){const n={op:"contains",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"contains":30;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(30),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Nu extends Oe{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.endsWith(r)}toJson(t){const n={op:"ends",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"ends":32;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(32),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Au extends Oe{constructor(t,n,s){super(t);A(this,"value");A(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:n}=ne(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.startsWith(r)}toJson(t){const n={op:"starts",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"starts":37;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(37),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Mu extends Oe{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"in"}code(){return 33}test(t){const{val:n}=ne(t,this.path);for(const s of this.value)if(Xn(n,s))return!0;return!1}toJson(t){return{op:"in",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"in":33,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(33),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.value)}}class Du extends Oe{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"less"}code(){return 34}test(t){const{val:n}=ne(t,this.path);return typeof n!="number"?!1:n<this.value}toJson(t){return{op:"less",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"less":34,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(34),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class Lu extends Oe{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"more"}code(){return 36}test(t){const{val:n}=ne(t,this.path);return typeof n!="number"?!1:n>this.value}toJson(t){return{op:"more",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"more":36,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(36),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class cr extends Oe{constructor(t,n){super(t);A(this,"ops");this.ops=n}}class Uu extends cr{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"and"}code(){return 43}test(t){for(const n of this.ops)if(!n.test(t))return!1;return!0}toJson(t){return{op:"and",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"and":43,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){const s=n?this.path.slice(n.path.length):this.path;t.encodeArrayHeader(3),t.writer.u8(43),t.encodeArray(s);const r=this.ops.length;t.encodeArrayHeader(r);for(let o=0;o<r;o++)this.ops[o].encode(t,this)}}class Fu extends cr{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"or"}code(){return 45}test(t){for(const n of this.ops)if(n.test(t))return!0;return!1}toJson(t){return{op:"or",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"or":45,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(45),t.encodeArray(n?this.path.slice(n.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class ju extends cr{constructor(t,n){super(t,n);A(this,"ops");this.ops=n}op(){return"not"}code(){return 44}test(t){for(const n of this.ops)if(n.test(t))return!1;return!0}toJson(t){return{op:"not",path:W(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,n){return[n?"not":44,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(44),t.encodeArray(n?this.path.slice(n.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class Bu extends Oe{constructor(t,n,s,r){super(t);A(this,"value");A(this,"ignore_case");A(this,"matcher");this.value=n,this.ignore_case=s,this.matcher=r(n,s)}op(){return"matches"}code(){return 35}test(t){const{val:n}=ne(t,this.path);return typeof n!="string"?!1:this.matcher(n)}toJson(t){const n={op:"matches",path:W(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"matches":35;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(35),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}const{isArray:Ju}=Array;class Vu extends Oe{constructor(t,n){super(t);A(this,"value");this.value=n}op(){return"type"}code(){return 42}test(t){const{val:n}=ne(t,this.path);return n===null?this.value==="null":Ju(n)?this.value==="array":typeof n===this.value||typeof n=="number"&&n===Math.round(n)&&this.value==="integer"}toJson(t){return{op:"type",path:W(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"type":42,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(42),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value)}}const qu=(i,e)=>{switch(i.op){case"add":return new ar(V(i.path),i.value);case"remove":return new Mo(V(i.path),i.oldValue);case"replace":return new du(V(i.path),i.value,i.oldValue);case"move":return new hu(V(i.path),V(i.from));case"copy":return new fu(V(i.path),V(i.from));case"flip":return new mu(V(i.path));case"inc":return new gu(V(i.path),i.inc);case"str_ins":return new vu(V(i.path),i.pos,i.str);case"str_del":return new yu(V(i.path),i.pos,i.str,i.len);case"split":return new Cu(V(i.path),i.pos,i.props||null);case"merge":return new Tu(V(i.path),i.pos,i.props||null);case"extend":return new wu(V(i.path),i.props,!!i.deleteNull);default:return Bn(i,e)}},Bn=(i,e)=>{switch(i.op){case"test":return new pu(V(i.path),i.value,!!i.not);case"defined":return new Eu(V(i.path));case"undefined":return new Pu(V(i.path));case"type":return new Vu(V(i.path),i.value);case"test_type":return new Ru(V(i.path),i.type);case"test_string":return new Ou(V(i.path),i.pos,i.str,!!i.not);case"test_string_len":return new xu(V(i.path),i.len,!!i.not);case"contains":return new Iu(V(i.path),i.value,!!i.ignore_case);case"ends":return new Nu(V(i.path),i.value,!!i.ignore_case);case"starts":return new Au(V(i.path),i.value,!!i.ignore_case);case"matches":return new Bu(V(i.path),i.value,!!i.ignore_case,e.createMatcher||ku);case"in":return new Mu(V(i.path),i.value);case"less":return new Du(V(i.path),i.value);case"more":return new Lu(V(i.path),i.value);case"and":{const t=V(i.path);return new Uu(t,i.apply.map(n=>Bn({...n,path:[...t,...V(n.path)]},e)))}case"or":{const t=V(i.path);return new Fu(t,i.apply.map(n=>Bn({...n,path:[...t,...V(n.path)]},e)))}case"not":{const t=V(i.path);return new ju(t,i.apply.map(n=>Bn({...n,path:[...t,...V(n.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function $u(i,e,t){t.mutate||(i=Tn(i));const n=[],s=e.length;for(let r=0;r<s;r++){const a=qu(e[r],t).apply(i);i=a.doc,n.push(a)}return{doc:i,res:n}}var hn=i=>typeof i=="function"?i:function(){return i},Hu=typeof self<"u"?self:null,cn=typeof window<"u"?window:null,fn=Hu||cn||fn,zu="2.0.0",nt={connecting:0,open:1,closing:2,closed:3},Gu=1e4,Wu=1e3,Ae={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Rt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ns={longpoll:"longpoll",websocket:"websocket"},Ku={complete:4},Dn=class{constructor(i,e,t,n){this.channel=i,this.event=e,this.payload=t||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(i){this.timeout=i,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(i,e){return this.hasReceived(i)&&e(this.receivedResp.response),this.recHooks.push({status:i,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:i,response:e,_ref:t}){this.recHooks.filter(n=>n.status===i).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,i=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=i,this.matchReceive(i)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(i){return this.receivedResp&&this.receivedResp.status===i}trigger(i,e){this.channel.trigger(this.refEvent,{status:i,response:e})}},Do=class{constructor(i,e){this.callback=i,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Yu=class{constructor(i,e,t){this.state=Ae.closed,this.topic=i,this.params=hn(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Dn(this,Rt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Do(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Ae.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=Ae.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=Ae.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Ae.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new Dn(this,Rt.leave,hn({}),this.timeout).send(),this.state=Ae.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Rt.reply,(n,s)=>{this.trigger(this.replyEventName(s),n)})}join(i=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=i,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(i){this.on(Rt.close,i)}onError(i){return this.on(Rt.error,e=>i(e))}on(i,e){let t=this.bindingRef++;return this.bindings.push({event:i,ref:t,callback:e}),t}off(i,e){this.bindings=this.bindings.filter(t=>!(t.event===i&&(typeof e>"u"||e===t.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(i,e,t=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${i}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Dn(this,i,function(){return e},t);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(i=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Ae.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Rt.close,"leave")},t=new Dn(this,Rt.leave,hn({}),i);return t.receive("ok",()=>e()).receive("timeout",()=>e()),t.send(),this.canPush()||t.trigger("ok",{}),t}onMessage(i,e,t){return e}isMember(i,e,t,n){return this.topic!==i?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:i,event:e,payload:t,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(i=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Ae.joining,this.joinPush.resend(i))}trigger(i,e,t,n){let s=this.onMessage(i,e,t,n);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===i);for(let o=0;o<r.length;o++)r[o].callback(s,t,n||this.joinRef())}replyEventName(i){return`chan_reply_${i}`}isClosed(){return this.state===Ae.closed}isErrored(){return this.state===Ae.errored}isJoined(){return this.state===Ae.joined}isJoining(){return this.state===Ae.joining}isLeaving(){return this.state===Ae.leaving}},Qn=class{static request(i,e,t,n,s,r,o){if(fn.XDomainRequest){let a=new fn.XDomainRequest;return this.xdomainRequest(a,i,e,n,s,r,o)}else{let a=new fn.XMLHttpRequest;return this.xhrRequest(a,i,e,t,n,s,r,o)}}static xdomainRequest(i,e,t,n,s,r,o){return i.timeout=s,i.open(e,t),i.onload=()=>{let a=this.parseJSON(i.responseText);o&&o(a)},r&&(i.ontimeout=r),i.onprogress=()=>{},i.send(n),i}static xhrRequest(i,e,t,n,s,r,o,a){return i.open(e,t,!0),i.timeout=r,i.setRequestHeader("Content-Type",n),i.onerror=()=>a&&a(null),i.onreadystatechange=()=>{if(i.readyState===Ku.complete&&a){let c=this.parseJSON(i.responseText);a(c)}},o&&(i.ontimeout=o),i.send(s),i}static parseJSON(i){if(!i||i==="")return null;try{return JSON.parse(i)}catch{return console&&console.log("failed to parse JSON response",i),null}}static serialize(i,e){let t=[];for(var n in i){if(!Object.prototype.hasOwnProperty.call(i,n))continue;let s=e?`${e}[${n}]`:n,r=i[n];typeof r=="object"?t.push(this.serialize(r,s)):t.push(encodeURIComponent(s)+"="+encodeURIComponent(r))}return t.join("&")}static appendParams(i,e){if(Object.keys(e).length===0)return i;let t=i.match(/\?/)?"&":"?";return`${i}${t}${this.serialize(e)}`}},ms=class{constructor(i){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(i),this.readyState=nt.connecting,this.poll()}normalizeEndpoint(i){return i.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ns.websocket),"$1/"+Ns.longpoll)}endpointURL(){return Qn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(i,e,t){this.close(i,e,t),this.readyState=nt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===nt.open||this.readyState===nt.connecting}poll(){this.ajax("GET",null,()=>this.ontimeout(),i=>{if(i){var{status:e,token:t,messages:n}=i;this.token=t}else e=0;switch(e){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=nt.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(i){this.ajax("POST",i,()=>this.onerror("timeout"),e=>{(!e||e.status!==200)&&(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(i,e,t){for(let s of this.reqs)s.abort();this.readyState=nt.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:i,reason:e,wasClean:t});typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(i,e,t,n){let s,r=()=>{this.reqs.delete(s),t()};s=Qn.request(i,this.endpointURL(),"application/json",e,this.timeout,r,o=>{this.reqs.delete(s),this.isActive()&&n(o)}),this.reqs.add(s)}},Ln={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(i,e){if(i.payload.constructor===ArrayBuffer)return e(this.binaryEncode(i));{let t=[i.join_ref,i.ref,i.topic,i.event,i.payload];return e(JSON.stringify(t))}},decode(i,e){if(i.constructor===ArrayBuffer)return e(this.binaryDecode(i));{let[t,n,s,r,o]=JSON.parse(i);return e({join_ref:t,ref:n,topic:s,event:r,payload:o})}},binaryEncode(i){let{join_ref:e,ref:t,event:n,topic:s,payload:r}=i,o=this.META_LENGTH+e.length+t.length+s.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(a),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,e.length),c.setUint8(u++,t.length),c.setUint8(u++,s.length),c.setUint8(u++,n.length),Array.from(e,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(t,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(u++,h.charCodeAt(0)));var l=new Uint8Array(a.byteLength+r.byteLength);return l.set(new Uint8Array(a),0),l.set(new Uint8Array(r),a.byteLength),l.buffer},binaryDecode(i){let e=new DataView(i),t=e.getUint8(0),n=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(i,e,n);case this.KINDS.reply:return this.decodeReply(i,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(i,e,n)}},decodePush(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=t.decode(i.slice(o,o+n));o=o+n;let c=t.decode(i.slice(o,o+s));o=o+s;let u=t.decode(i.slice(o,o+r));o=o+r;let l=i.slice(o,i.byteLength);return{join_ref:a,ref:null,topic:c,event:u,payload:l}},decodeReply(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(i.slice(a,a+n));a=a+n;let u=t.decode(i.slice(a,a+s));a=a+s;let l=t.decode(i.slice(a,a+r));a=a+r;let h=t.decode(i.slice(a,a+o));a=a+o;let f=i.slice(a,i.byteLength),p={status:h,response:f};return{join_ref:c,ref:u,topic:l,event:Rt.reply,payload:p}},decodeBroadcast(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,o=t.decode(i.slice(r,r+n));r=r+n;let a=t.decode(i.slice(r,r+s));r=r+s;let c=i.slice(r,i.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},Xu=class{constructor(i,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||Gu,this.transport=e.transport||fn.WebSocket||ms,this.establishedConnections=0,this.defaultEncoder=Ln.encode.bind(Ln),this.defaultDecoder=Ln.decode.bind(Ln),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==ms?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;cn&&cn.addEventListener&&(cn.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),t=this.connectClock)}),cn.addEventListener("pageshow",n=>{t===this.connectClock&&(t=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=hn(e.params||{}),this.endPoint=`${i}/${Ns.websocket}`,this.vsn=e.vsn||zu,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Do(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return ms}replaceTransport(i){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.sendBuffer=[],this.conn&&(this.conn.close(),this.conn=null),this.transport=i}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let i=Qn.appendParams(Qn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return i.charAt(0)!=="/"?i:i.charAt(1)==="/"?`${this.protocol()}:${i}`:`${this.protocol()}://${location.host}${i}`}disconnect(i,e,t){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(i,e,t)}connect(i){i&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=hn(i)),!this.conn&&(this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e))}log(i,e,t){this.logger(i,e,t)}hasLogger(){return this.logger!==null}onOpen(i){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,i]),e}onClose(i){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,i]),e}onError(i){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,i]),e}onMessage(i){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,i]),e}ping(i){if(!this.isConnected())return!1;let e=this.makeRef(),t=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(s=>{s.ref===e&&(this.off([n]),i(Date.now()-t))});return!0}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,i])=>i())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Wu,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(i,e,t){if(!this.conn)return i&&i();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,t||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),i&&i()})})}waitForBufferDone(i,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){i();return}setTimeout(()=>{this.waitForBufferDone(i,e+1)},150*e)}waitForSocketClosed(i,e=1){if(e===5||!this.conn||this.conn.readyState===nt.closed){i();return}setTimeout(()=>{this.waitForSocketClosed(i,e+1)},150*e)}onConnClose(i){let e=i&&i.code;this.hasLogger()&&this.log("transport","close",i),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(i))}onConnError(i){this.hasLogger()&&this.log("transport",i);let e=this.transport,t=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,n])=>{n(i,e,t)}),(e===this.transport||t>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(i=>{i.isErrored()||i.isLeaving()||i.isClosed()||i.trigger(Rt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case nt.connecting:return"connecting";case nt.open:return"open";case nt.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(i){this.off(i.stateChangeRefs),this.channels=this.channels.filter(e=>e.joinRef()!==i.joinRef())}off(i){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([t])=>i.indexOf(t)===-1)}channel(i,e={}){let t=new Yu(i,e,this);return this.channels.push(t),t}push(i){if(this.hasLogger()){let{topic:e,event:t,payload:n,ref:s,join_ref:r}=i;this.log("push",`${e} ${t} (${r}, ${s})`,n)}this.isConnected()?this.encode(i,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(i,e=>this.conn.send(e)))}makeRef(){let i=this.ref+1;return i===this.ref?this.ref=0:this.ref=i,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(i=>i()),this.sendBuffer=[])}onConnMessage(i){this.decode(i.data,e=>{let{topic:t,event:n,payload:s,ref:r,join_ref:o}=e;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${n} ${r&&"("+r+")"||""}`,s);for(let a=0;a<this.channels.length;a++){const c=this.channels[a];c.isMember(t,n,s,o)&&c.trigger(n,s,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,c]=this.stateChangeCallbacks.message[a];c(e)}})}leaveOpenTopic(i){let e=this.channels.find(t=>t.topic===i&&(t.isJoined()||t.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${i}"`),e.leave())}};class Qu{constructor(e){this.connected=!1,this.config=e,this.socket=new Xu(this.config.url,this.config.socketOptions||{logger:(t,n,s)=>{console.debug(`${t}: ${n}`,s)}}),this.channel=this.socket.channel(this.config.topic,this.config.params),this.eventTarget=new EventTarget}connect(){this.connected||(this.socket.onError(e=>this.emitError("socket error",e)),this.socket.connect(),this.channel.onError(e=>this.emitError("channel error",e)),this.channel.join().receive("ok",e=>{console.debug("channel joined",e)}).receive("error",e=>{this.emitError("channel join error",e)}),this.channel.on("state:change",e=>this.handleChange(e)),this.channel.on("state:patch",e=>this.handlePatch(e)),this.channel.on("error",e=>this.emitServerError(e)),this.connected=!0)}disconnect(){this.channel&&this.channel.leave(),this.socket.disconnect(),this.connected=!1}addEventListener(e,t,n){var s;this.eventTarget.addEventListener(e,t,n),e.startsWith("livestate-")||(s=this.channel)==null||s.on(e,r=>{this.eventTarget.dispatchEvent(new CustomEvent(e,{detail:r}))})}removeEventListener(e,t,n){return this.eventTarget.removeEventListener(e,t,n)}subscribe(e){this.addEventListener("livestate-change",e)}unsubscribe(e){this.removeEventListener("livestate-change",e)}emitServerError(e){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:e}))}emitError(e,t){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:{type:e,message:this.extractMessage(t)}}))}extractMessage(e){if(e&&typeof(e=="object")){const t=[e.reason,e.name,e.message].find(n=>n);return console.log(t),t}else if(typeof e=="string")return e}handleChange({state:e,version:t}){this.state=e,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}handlePatch({patch:e,version:t}){if(this.eventTarget.dispatchEvent(new CustomEvent("livestate-patch",{detail:{patch:e,version:t}})),this.versionMatches(t)){const{doc:n,res:s}=$u(this.state,e,{mutate:!1});this.state=n,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}else this.channel.push("lvs_refresh")}versionMatches(e){return e===this.stateVersion+1||e===0}pushEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}dispatchEvent(e){return this.channel.push(`lvs_evt:${e.type}`,e.detail),!0}pushCustomEvent(e){this.dispatchEvent(e)}}const Lo=32;let le,He,Zn=i=>(le=0,He=i,i=ui(),He[le]?oi():i||""),oi=(i="Bad syntax",e=He[le],t=He.slice(0,le).split(`
|
|
2
2
|
`),n=t.pop())=>{let s=He.slice(le-108,le).split(`
|
|
3
3
|
`).pop(),r=He.slice(le+1,le+108).split(`
|
|
4
|
-
`).shift();throw EvalError(`${i} at ${t.length}:${n.length} \`${s+e+r}\``,"font-weight: bold")},pn=(i=1,e=le,t)=>{if(typeof i=="number")le+=i;else for(;t=i(He.charCodeAt(le));)le+=t;return He.slice(e,le)},
|
|
4
|
+
`).shift();throw EvalError(`${i} at ${t.length}:${n.length} \`${s+e+r}\``,"font-weight: bold")},pn=(i=1,e=le,t)=>{if(typeof i=="number")le+=i;else for(;t=i(He.charCodeAt(le));)le+=t;return He.slice(e,le)},ui=(i=0,e,t,n,s,r)=>{for(;(t=Zn.space())&&(s=((r=Hi[t])&&r(n,i))??(!n&&Zn.id()));)n=s;return e&&(t==e?le++:oi()),n},Uo=i=>i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||i==36||i==95||i>=192&&i!=215&&i!=247;Zn.space=i=>{for(;(i=He.charCodeAt(le))<=Lo;)le++;return i};Zn.id=i=>pn(Uo);let Hi=[],Ci=(i,e=Lo,t,n=i.charCodeAt(0),s=i.length,r=Hi[n],o=i.toUpperCase()!==i)=>Hi[n]=(a,c,u=le)=>c<e&&(s<2||He.substr(le,s)==i)&&(!o||!Uo(He.charCodeAt(le+s)))&&(le+=s,t(a,c))||(le=u,r==null?void 0:r(a,c)),Fo=(i,e,t=0)=>Ci(i,e,(n,s)=>n&&(s=ui(e-t/2))&&[i,n,s]),Zu=(i,e,t)=>Ci(i,e,n=>t?n&&[i,n]:!n&&(n=ui(e-.5))&&[i,n]),el=(i,e,t)=>{Ci(i,e,(n,s)=>(n||t)&&(s=ui(e),s||t)&&((!n||n[0]!==i)&&(n=[i,n]),(s||t)&&n.push(s),n))};const ue=i=>Array.isArray(i)?As[i[0]](...i.slice(1)):e=>e==null?void 0:e[i],As={},ni=(i,e,t=As[i])=>As[i]=(...n)=>e(...n)||t&&t(...n),jo=41,tl=93,Ir=34,Bo=46,Jo=48,il=57,nl=1,sl=4,rl=5,ol=6,al=7,cl=8,Vo=9,as=10,ur=11,qo=12,lr=13,In=15,Sn=18,se=(i,e,t)=>t.length?t.length>1?(Fo(i,Math.abs(e),e<0),ni(i,(n,s)=>s&&(n=ue(n),s=ue(s),!n.length&&!s.length?(n=t(n(),s()),()=>n):r=>t(n(r),s(r))))):(Zu(i,e),ni(i,(n,s)=>!s&&(n=ue(n),n.length?r=>t(n(r)):(n=t(n()),()=>n)))):(el(i,Math.abs(e),e<0),ni(i,(...n)=>(n=n.map(ue),s=>t(...n.map(r=>r(s)))))),$o=i=>i?oi():["",(i=+pn(e=>e===Bo||e>=Jo&&e<=il||(e===69||e===101?2:0)))!=i?oi():i],Ho=(i,e,t,n)=>(Ci(i,e,s=>s?[i==="++"?"-":"+",[i,s],["",1]]:[i,ui(e-1)]),ni(i,n=(s,r)=>s[0]==="("?n(s[1]):s[0]==="."?(r=s[2],s=ue(s[1]),o=>t(s(o),r)):s[0]==="["?([,s,r]=s,s=ue(s),r=ue(r),o=>t(s(o),r(o))):o=>t(o,s)));ni("",i=>()=>i);Hi[Ir]=i=>i?oi():["",(pn()+pn(e=>e-Ir?1:0)+(pn()||oi("Bad string"))).slice(1,-1)];Hi[Bo]=i=>!i&&$o();for(let i=0;i<=9;i++)Hi[Jo+i]=$o;se(",",nl,(...i)=>i[i.length-1]);se("||",sl,(...i)=>{let e=0,t;for(;!t&&e<i.length;)t=i[e++];return t});se("&&",rl,(...i)=>{let e=0,t=!0;for(;t&&e<i.length;)t=i[e++];return t});Fo("=",10,!0);ni("=",(i,e)=>{let t=ue(e),n,s,r=typeof i=="string"?(o,a)=>o[i]=a:i[0]==="."?(n=ue(i[1]),s=i[2],(o,a)=>n(o)[s]=a):i[0]==="["?(n=ue(i[1]),s=ue(i[2]),(o,a)=>n(o)[s(o)]=a):oi("Bad left value");return o=>r(o,t(o))});se("+",qo,(i,e)=>i+e);se("-",qo,(i,e)=>i-e);se("*",lr,(i,e)=>i*e);se("/",lr,(i,e)=>i/e);se("%",lr,(i,e)=>i%e);se("|",ol,(i,e)=>i|e);se("&",cl,(i,e)=>i&e);se("^",al,(i,e)=>i^e);se("==",Vo,(i,e)=>i==e);se("!=",Vo,(i,e)=>i!=e);se(">",as,(i,e)=>i>e);se(">=",as,(i,e)=>i>=e);se("<",as,(i,e)=>i<e);se("<=",as,(i,e)=>i<=e);se(">>",ur,(i,e)=>i>>e);se(">>>",ur,(i,e)=>i>>>e);se("<<",ur,(i,e)=>i<<e);se("+",In,i=>+i);se("-",In,i=>-i);se("!",In,i=>!i);Ho("++",In,(i,e)=>++i[e]);Ho("--",In,(i,e)=>--i[e]);Ci("[",Sn,i=>i&&["[",i,ui(0,tl)||oi()]);ni("[",(i,e)=>e&&(i=ue(i),e=ue(e),t=>i(t)[e(t)]));Ci(".",Sn,(i,e)=>i&&(e=ui(Sn))&&[".",i,e]);ni(".",(i,e)=>(i=ue(i),e=e[0]?e:e[1],t=>i(t)[e]));Ci("(",Sn,i=>!i&&["(",ui(0,jo)||oi()]);Ci("(",Sn,(i,e)=>i&&(e=ui(0,jo),e?["(",i,e]:["(",i,""]));ni("(",(i,e,t,n,s)=>e==null?ue(i):(s=e==""?()=>[]:e[0]===","?(e=e.slice(1).map(ue),r=>e.map(o=>o(r))):(e=ue(e),r=>[e(r)]),i[0]==="."?(t=i[2],i=ue(i[1]),r=>i(r)[t](...s(r))):i[0]==="["?(t=ue(i[2]),i=ue(i[1]),r=>i(r)[t(r)](...s(r))):(i=ue(i),r=>i(r)(...s(r)))));Promise.resolve();var Nr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};/*! *****************************************************************************
|
|
5
5
|
Copyright (C) Microsoft. All rights reserved.
|
|
6
6
|
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
7
7
|
this file except in compliance with the License. You may obtain a copy of the
|
|
@@ -14,8 +14,8 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
|
14
14
|
|
|
15
15
|
See the Apache Version 2.0 License for specific language governing permissions
|
|
16
16
|
and limitations under the License.
|
|
17
|
-
***************************************************************************** */var Nr;(function(i){(function(e){var t=typeof Ir=="object"?Ir:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),n=s(i);typeof t.Reflect>"u"?t.Reflect=i:n=s(t.Reflect,n),e(n);function s(r,o){return function(a,c){typeof r[a]!="function"&&Object.defineProperty(r,a,{configurable:!0,writable:!0,value:c}),o&&o(a,c)}}})(function(e){var t=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",s=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",r=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",a={__proto__:[]}instanceof Array,c=!o&&!a,u={create:o?function(){return hs(Object.create(null))}:a?function(){return hs({__proto__:null})}:function(){return hs({})},has:c?function(g,b){return t.call(g,b)}:function(g,b){return b in g},get:c?function(g,b){return t.call(g,b)?g[b]:void 0}:function(g,b){return g[b]}},l=Object.getPrototypeOf(Function),h=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",f=!h&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Sc(),p=!h&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:wc(),v=!h&&typeof WeakMap=="function"?WeakMap:Ec(),y=new v;function R(g,b,T,E){if(Y(T)){if(!Cr(g))throw new TypeError;if(!Tr(b))throw new TypeError;return H(g,b)}else{if(!Cr(g))throw new TypeError;if(!oe(b))throw new TypeError;if(!oe(E)&&!Y(E)&&!Je(E))throw new TypeError;return Je(E)&&(E=void 0),T=Rt(T),Pt(g,b,T,E)}}e("decorate",R);function S(g,b){function T(E,D){if(!oe(E))throw new TypeError;if(!Y(D)&&!yc(D))throw new TypeError;I(g,b,E,D)}return T}e("metadata",S);function w(g,b,T,E){if(!oe(T))throw new TypeError;return Y(E)||(E=Rt(E)),I(g,b,T,E)}e("defineMetadata",w);function $(g,b,T){if(!oe(b))throw new TypeError;return Y(T)||(T=Rt(T)),Xi(g,b,T)}e("hasMetadata",$);function K(g,b,T){if(!oe(b))throw new TypeError;return Y(T)||(T=Rt(T)),Qi(g,b,T)}e("hasOwnMetadata",K);function me(g,b,T){if(!oe(b))throw new TypeError;return Y(T)||(T=Rt(T)),Zi(g,b,T)}e("getMetadata",me);function de(g,b,T){if(!oe(b))throw new TypeError;return Y(T)||(T=Rt(T)),Nn(g,b,T)}e("getOwnMetadata",de);function U(g,b){if(!oe(g))throw new TypeError;return Y(b)||(b=Rt(b)),Ce(g,b)}e("getMetadataKeys",U);function ee(g,b){if(!oe(g))throw new TypeError;return Y(b)||(b=Rt(b)),Te(g,b)}e("getOwnMetadataKeys",ee);function M(g,b,T){if(!oe(b))throw new TypeError;Y(T)||(T=Rt(T));var E=tt(b,T,!1);if(Y(E)||!E.delete(g))return!1;if(E.size>0)return!0;var D=y.get(b);return D.delete(T),D.size>0||y.delete(b),!0}e("deleteMetadata",M);function H(g,b){for(var T=g.length-1;T>=0;--T){var E=g[T],D=E(b);if(!Y(D)&&!Je(D)){if(!Tr(D))throw new TypeError;b=D}}return b}function Pt(g,b,T,E){for(var D=g.length-1;D>=0;--D){var ve=g[D],j=ve(b,T,E);if(!Y(j)&&!Je(j)){if(!oe(j))throw new TypeError;E=j}}return E}function tt(g,b,T){var E=y.get(g);if(Y(E)){if(!T)return;E=new f,y.set(g,E)}var D=E.get(b);if(Y(D)){if(!T)return;D=new f,E.set(b,D)}return D}function Xi(g,b,T){var E=Qi(g,b,T);if(E)return!0;var D=ds(b);return Je(D)?!1:Xi(g,D,T)}function Qi(g,b,T){var E=tt(b,T,!1);return Y(E)?!1:gc(E.has(g))}function Zi(g,b,T){var E=Qi(g,b,T);if(E)return Nn(g,b,T);var D=ds(b);if(!Je(D))return Zi(g,D,T)}function Nn(g,b,T){var E=tt(b,T,!1);if(!Y(E))return E.get(g)}function I(g,b,T,E){var D=tt(T,E,!0);D.set(g,b)}function Ce(g,b){var T=Te(g,b),E=ds(g);if(E===null)return T;var D=Ce(E,b);if(D.length<=0)return T;if(T.length<=0)return D;for(var ve=new p,j=[],B=0,L=T;B<L.length;B++){var z=L[B],G=ve.has(z);G||(ve.add(z),j.push(z))}for(var di=0,wr=D;di<wr.length;di++){var z=wr[di],G=ve.has(z);G||(ve.add(z),j.push(z))}return j}function Te(g,b){var T=[],E=tt(g,b,!1);if(Y(E))return T;for(var D=E.keys(),ve=bc(D),j=0;;){var B=Cc(ve);if(!B)return T.length=j,T;var L=kc(B);try{T[j]=L}catch(z){try{Tc(ve)}finally{throw z}}j++}}function it(g){if(g===null)return 1;switch(typeof g){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return g===null?1:6;default:return 6}}function Y(g){return g===void 0}function Je(g){return g===null}function An(g){return typeof g=="symbol"}function oe(g){return typeof g=="object"?g!==null:typeof g=="function"}function Ii(g,b){switch(it(g)){case 0:return g;case 1:return g;case 2:return g;case 3:return g;case 4:return g;case 5:return g}var T=b===3?"string":b===5?"number":"default",E=Sr(g,s);if(E!==void 0){var D=E.call(g,T);if(oe(D))throw new TypeError;return D}return _t(g,T==="default"?"number":T)}function _t(g,b){if(b==="string"){var T=g.toString;if(Ni(T)){var E=T.call(g);if(!oe(E))return E}var D=g.valueOf;if(Ni(D)){var E=D.call(g);if(!oe(E))return E}}else{var D=g.valueOf;if(Ni(D)){var E=D.call(g);if(!oe(E))return E}var ve=g.toString;if(Ni(ve)){var E=ve.call(g);if(!oe(E))return E}}throw new TypeError}function gc(g){return!!g}function vc(g){return""+g}function Rt(g){var b=Ii(g,3);return An(b)?b:vc(b)}function Cr(g){return Array.isArray?Array.isArray(g):g instanceof Object?g instanceof Array:Object.prototype.toString.call(g)==="[object Array]"}function Ni(g){return typeof g=="function"}function Tr(g){return typeof g=="function"}function yc(g){switch(it(g)){case 3:return!0;case 4:return!0;default:return!1}}function Sr(g,b){var T=g[b];if(T!=null){if(!Ni(T))throw new TypeError;return T}}function bc(g){var b=Sr(g,r);if(!Ni(b))throw new TypeError;var T=b.call(g);if(!oe(T))throw new TypeError;return T}function kc(g){return g.value}function Cc(g){var b=g.next();return b.done?!1:b}function Tc(g){var b=g.return;b&&b.call(g)}function ds(g){var b=Object.getPrototypeOf(g);if(typeof g!="function"||g===l||b!==l)return b;var T=g.prototype,E=T&&Object.getPrototypeOf(T);if(E==null||E===Object.prototype)return b;var D=E.constructor;return typeof D!="function"||D===g?b:D}function Sc(){var g={},b=[],T=function(){function j(B,L,z){this._index=0,this._keys=B,this._values=L,this._selector=z}return j.prototype["@@iterator"]=function(){return this},j.prototype[r]=function(){return this},j.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var L=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=b,this._values=b):this._index++,{value:L,done:!1}}return{value:void 0,done:!0}},j.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=b,this._values=b),B},j.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=b,this._values=b),{value:B,done:!0}},j}();return function(){function j(){this._keys=[],this._values=[],this._cacheKey=g,this._cacheIndex=-2}return Object.defineProperty(j.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),j.prototype.has=function(B){return this._find(B,!1)>=0},j.prototype.get=function(B){var L=this._find(B,!1);return L>=0?this._values[L]:void 0},j.prototype.set=function(B,L){var z=this._find(B,!0);return this._values[z]=L,this},j.prototype.delete=function(B){var L=this._find(B,!1);if(L>=0){for(var z=this._keys.length,G=L+1;G<z;G++)this._keys[G-1]=this._keys[G],this._values[G-1]=this._values[G];return this._keys.length--,this._values.length--,B===this._cacheKey&&(this._cacheKey=g,this._cacheIndex=-2),!0}return!1},j.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=g,this._cacheIndex=-2},j.prototype.keys=function(){return new T(this._keys,this._values,E)},j.prototype.values=function(){return new T(this._keys,this._values,D)},j.prototype.entries=function(){return new T(this._keys,this._values,ve)},j.prototype["@@iterator"]=function(){return this.entries()},j.prototype[r]=function(){return this.entries()},j.prototype._find=function(B,L){return this._cacheKey!==B&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=B)),this._cacheIndex<0&&L&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},j}();function E(j,B){return j}function D(j,B){return B}function ve(j,B){return[j,B]}}function wc(){return function(){function g(){this._map=new f}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(b){return this._map.has(b)},g.prototype.add=function(b){return this._map.set(b,b),this},g.prototype.delete=function(b){return this._map.delete(b)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.values()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[r]=function(){return this.keys()},g}()}function Ec(){var g=16,b=u.create(),T=E();return function(){function L(){this._key=E()}return L.prototype.has=function(z){var G=D(z,!1);return G!==void 0?u.has(G,this._key):!1},L.prototype.get=function(z){var G=D(z,!1);return G!==void 0?u.get(G,this._key):void 0},L.prototype.set=function(z,G){var di=D(z,!0);return di[this._key]=G,this},L.prototype.delete=function(z){var G=D(z,!1);return G!==void 0?delete G[this._key]:!1},L.prototype.clear=function(){this._key=E()},L}();function E(){var L;do L="@@WeakMap@@"+B();while(u.has(b,L));return b[L]=!0,L}function D(L,z){if(!t.call(L,T)){if(!z)return;Object.defineProperty(L,T,{value:u.create()})}return L[T]}function ve(L,z){for(var G=0;G<z;++G)L[G]=Math.random()*255|0;return L}function j(L){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(L)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(L)):ve(new Uint8Array(L),L):ve(new Array(L),L)}function B(){var L=j(g);L[6]=L[6]&79|64,L[8]=L[8]&191|128;for(var z="",G=0;G<g;++G){var di=L[G];(G===4||G===6||G===8)&&(z+="-"),di<16&&(z+="0"),z+=di.toString(16).toLowerCase()}return z}}function hs(g){return g.__=void 0,delete g.__,g}})})(Nr||(Nr={}));function ul(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var ll=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dl(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ho={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(ll,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function r(y,R){var S=y[R];if(typeof S.bind=="function")return S.bind(y);try{return Function.prototype.bind.call(S,y)}catch{return function(){return Function.prototype.apply.apply(S,[y,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(y){return y==="debug"&&(y="log"),typeof console===t?!1:y==="trace"&&n?o:console[y]!==void 0?r(console,y):console.log!==void 0?r(console,"log"):e}function c(y,R){for(var S=0;S<s.length;S++){var w=s[S];this[w]=S<y?e:this.methodFactory(w,y,R)}this.log=this.debug}function u(y,R,S){return function(){typeof console!==t&&(c.call(this,R,S),this[y].apply(this,arguments))}}function l(y,R,S){return a(y)||u.apply(this,arguments)}function h(y,R,S){var w=this,$;R=R??"WARN";var K="loglevel";typeof y=="string"?K+=":"+y:typeof y=="symbol"&&(K=void 0);function me(M){var H=(s[M]||"silent").toUpperCase();if(!(typeof window===t||!K)){try{window.localStorage[K]=H;return}catch{}try{window.document.cookie=encodeURIComponent(K)+"="+H+";"}catch{}}}function de(){var M;if(!(typeof window===t||!K)){try{M=window.localStorage[K]}catch{}if(typeof M===t)try{var H=window.document.cookie,Pt=H.indexOf(encodeURIComponent(K)+"=");Pt!==-1&&(M=/^([^;]+)/.exec(H.slice(Pt))[1])}catch{}return w.levels[M]===void 0&&(M=void 0),M}}function U(){if(!(typeof window===t||!K)){try{window.localStorage.removeItem(K);return}catch{}try{window.document.cookie=encodeURIComponent(K)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}w.name=y,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=S||l,w.getLevel=function(){return $},w.setLevel=function(M,H){if(typeof M=="string"&&w.levels[M.toUpperCase()]!==void 0&&(M=w.levels[M.toUpperCase()]),typeof M=="number"&&M>=0&&M<=w.levels.SILENT){if($=M,H!==!1&&me(M),c.call(w,M,y),typeof console===t&&M<w.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+M},w.setDefaultLevel=function(M){R=M,de()||w.setLevel(M,!1)},w.resetLevel=function(){w.setLevel(R,!1),U()},w.enableAll=function(M){w.setLevel(w.levels.TRACE,M)},w.disableAll=function(M){w.setLevel(w.levels.SILENT,M)};var ee=de();ee==null&&(ee=R),w.setLevel(ee,!1)}var f=new h,p={};f.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var S=p[R];return S||(S=p[R]=new h(R,f.getLevel(),f.methodFactory)),S};var v=typeof window!==t?window.log:void 0;return f.noConflict=function(){return typeof window!==t&&window.log===f&&(window.log=v),f},f.getLoggers=function(){return p},f.default=f,f})})(Ho);var lr=Ho.exports,As;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(As||(As={}));var wt;(function(i){i.Default="livekit",i.Room="livekit-room",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(wt||(wt={}));let q=lr.getLogger("livekit");q.setDefaultLevel(As.info);function ci(i){const e=lr.getLogger(i);return e.setDefaultLevel(q.getLevel()),e}lr.getLogger("lk-e2ee");function Oe(i,e){if(!i)throw new Error(e)}const hl=34028234663852886e22,fl=-34028234663852886e22,pl=4294967295,ml=2147483647,gl=-2147483648;function Bn(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>ml||i<gl)throw new Error("invalid int 32: "+i)}function Ms(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>pl||i<0)throw new Error("invalid uint 32: "+i)}function zo(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>hl||i<fl))throw new Error("invalid float 32: "+i)}const Go=Symbol("@bufbuild/protobuf/enum-type");function vl(i){const e=i[Go];return Oe(e,"missing enum type on enum object"),e}function Wo(i,e,t,n){i[Go]=Ko(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Ko(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=Yo(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function yl(i,e,t){const n={};for(const s of e){const r=Yo(s);n[r.localName]=r.no,n[r.no]=r.localName}return Wo(n,i,e),n}function Yo(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class O{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,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 bl(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new O),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function kl(i,e,t,n){return{syntax:i,json:e,bin:t,util:n,makeMessageType(s,r,o){return bl(this,s,r,o)},makeEnum:yl,makeEnumType:Ko,getEnumType:vl}}var k;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(k||(k={}));var Ei;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Ei||(Ei={}));function Cl(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function ms(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Jn=4294967296;function Ar(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Jn&&(s=s+(n/Jn|0),n=n%Jn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Qo(n,s):dr(n,s)}function Tl(i,e){let t=dr(i,e);const n=t.hi&2147483648;n&&(t=Qo(t.lo,t.hi));const s=Xo(t.lo,t.hi);return n?"-"+s:s}function Xo(i,e){if({lo:i,hi:e}=Sl(i,e),e<=2097151)return String(Jn*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Mr(o)+Mr(r)}function Sl(i,e){return{lo:i>>>0,hi:e>>>0}}function dr(i,e){return{lo:i|0,hi:e|0}}function Qo(i,e){return e=~e,i?i=~i+1:e+=1,dr(i,e)}const Mr=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Dr(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function wl(){let i=this.buf[this.pos++],e=i&127;if(!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,!(i&128))return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;i&128&&t<10;t++)i=this.buf[this.pos++];if(i&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function El(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const u=typeof c=="bigint"?c:BigInt(c);if(u>r||u<s)throw new Error("int64 invalid: ".concat(c));return u},uParse(c){const u=typeof c=="bigint"?c:BigInt(c);if(u>a||u<o)throw new Error("uint64 invalid: ".concat(c));return u},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,u){return i.setInt32(0,c,!0),i.setInt32(4,u,!0),i.getBigInt64(0,!0)},uDec(c,u){return i.setInt32(0,c,!0),i.setInt32(4,u,!0),i.getBigUint64(0,!0)}}}const t=s=>Oe(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Oe(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Ar(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Ar(s)},dec(s,r){return Tl(s,r)},uDec(s,r){return Xo(s,r)}}}const F=El();var ae;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(ae||(ae={}));class Pl{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].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(Ms(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Bn(e),Dr(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){zo(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){Ms(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Bn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Bn(e),e=(e<<1^e>>31)>>>0,Dr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=F.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=F.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=F.enc(e);return ms(t.lo,t.hi,this.buf),this}sint64(e){let t=F.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return ms(s,r,this.buf),this}uint64(e){let t=F.uEnc(e);return ms(t.lo,t.hi,this.buf),this}}class _l{constructor(e,t){this.varint64=Cl,this.uint32=wl,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,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case ae.Varint:for(;this.buf[this.pos++]&128;);break;case ae.Bit64:this.pos+=4;case ae.Bit32:this.pos+=4;break;case ae.LengthDelimited:let n=this.uint32();this.pos+=n;break;case ae.StartGroup:let s;for(;(s=this.tag()[1])!==ae.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,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 F.dec(...this.varint64())}uint64(){return F.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,F.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return F.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return F.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 Ds(i,e){return e instanceof O||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;function hi(i,e,t){if(e===t)return!0;if(i==k.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==t}return!1}function Ls(i,e){switch(i){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==0?F.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function Zo(i,e){const t=e===void 0;let n=ae.Varint,s=e===0;switch(i){case k.STRING:s=t||!e.length,n=ae.LengthDelimited;break;case k.BOOL:s=e===!1;break;case k.DOUBLE:n=ae.Bit64;break;case k.FLOAT:n=ae.Bit32;break;case k.INT64:s=t||e==0;break;case k.UINT64:s=t||e==0;break;case k.FIXED64:s=t||e==0,n=ae.Bit64;break;case k.BYTES:s=t||!e.byteLength,n=ae.LengthDelimited;break;case k.FIXED32:n=ae.Bit32;break;case k.SFIXED32:n=ae.Bit32;break;case k.SFIXED64:s=t||e==0,n=ae.Bit64;break;case k.SINT64:s=t||e==0;break}const r=k[i].toLowerCase();return[n,r,t||s]}const Mi=Symbol("@bufbuild/protobuf/unknown-fields"),Lr={readUnknownFields:!0,readerFactory:i=>new _l(i)},Ur={writeUnknownFields:!0,writerFactory:()=>new Pl};function Rl(i){return i?Object.assign(Object.assign({},Lr),i):Lr}function Ol(i){return i?Object.assign(Object.assign({},Ur),i):Ur}function xl(){return{makeReadOptions:Rl,makeWriteOptions:Ol,listUnknownFields(i){var e;return(e=i[Mi])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Mi]},writeUnknownFields(i,e){const n=i[Mi];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Mi])||(s[Mi]=[]),s[Mi].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n){const s=i.getType(),r=t===void 0?e.len:e.pos+t;for(;e.pos<r;){const[o,a]=e.tag(),c=s.fields.find(o);if(!c){const f=e.skip(a);n.readUnknownFields&&this.onUnknownField(i,o,a,f);continue}let u=i,l=c.repeated,h=c.localName;switch(c.oneof&&(u=u[c.oneof.localName],u.case!=h&&delete u.value,u.case=h,h="value"),c.kind){case"scalar":case"enum":const f=c.kind=="enum"?k.INT32:c.T;let p=Zn;if(c.kind=="scalar"&&c.L>0&&(p=Nl),l){let S=u[h];if(a==ae.LengthDelimited&&f!=k.STRING&&f!=k.BYTES){let w=e.uint32()+e.pos;for(;e.pos<w;)S.push(p(e,f))}else S.push(p(e,f))}else u[h]=p(e,f);break;case"message":const v=c.T;l?u[h].push(Vn(e,new v,n)):u[h]instanceof O?Vn(e,u[h],n):(u[h]=Vn(e,new v,n),v.fieldWrapper&&!c.oneof&&!c.repeated&&(u[h]=v.fieldWrapper.unwrapField(u[h])));break;case"map":let[y,R]=Il(c,e,n);u[h][y]=R;break}}}}}function Vn(i,e,t){return e.getType().runtime.bin.readMessage(e,i,i.uint32(),t),e}function Il(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){let[a]=e.tag();switch(a){case 1:r=Zn(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=Zn(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Vn(e,new i.V.T,t);break}break}}if(r===void 0){let a=Ls(i.K,Ei.BIGINT);r=i.K==k.BOOL?a.toString():a}if(typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Ls(i.V.T,Ei.BIGINT);break;case"enum":o=0;break;case"message":o=new i.V.T;break}return[r,o]}function Nl(i,e){const t=Zn(i,e);return typeof t=="bigint"?t.toString():t}function Zn(i,e){switch(e){case k.STRING:return i.string();case k.BOOL:return i.bool();case k.DOUBLE:return i.double();case k.FLOAT:return i.float();case k.INT32:return i.int32();case k.INT64:return i.int64();case k.UINT64:return i.uint64();case k.FIXED64:return i.fixed64();case k.BYTES:return i.bytes();case k.FIXED32:return i.fixed32();case k.SFIXED32:return i.sfixed32();case k.SFIXED64:return i.sfixed64();case k.SINT64:return i.sint64();case k.UINT32:return i.uint32();case k.SINT32:return i.sint32()}}function Al(i,e,t,n,s){i.tag(t.no,ae.LengthDelimited),i.fork();let r=n;switch(t.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:r=Number.parseInt(n);break;case k.BOOL:Oe(n=="true"||n=="false"),r=n=="true";break}switch(mn(i,t.K,1,r,!0),t.V.kind){case"scalar":mn(i,t.V.T,2,s,!0);break;case"enum":mn(i,k.INT32,2,s,!0);break;case"message":Us(i,e,t.V.T,2,s);break}i.join()}function Us(i,e,t,n,s){if(s!==void 0){const r=Ds(t,s);i.tag(n,ae.LengthDelimited).bytes(r.toBinary(e))}}function mn(i,e,t,n,s){let[r,o,a]=Zo(e,n);(!a||s)&&i.tag(t,r)[o](n)}function Ml(i,e,t,n){if(!n.length)return;i.tag(t,ae.LengthDelimited).fork();let[,s]=Zo(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Dl(){return Object.assign(Object.assign({},xl()),{writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){let r,o=s.repeated,a=s.localName;if(s.oneof){const c=i[s.oneof.localName];if(c.case!==a)continue;r=c.value}else r=i[a];switch(s.kind){case"scalar":case"enum":let c=s.kind=="enum"?k.INT32:s.T;if(o)if(s.packed)Ml(e,c,s.no,r);else for(const u of r)mn(e,c,s.no,u,!0);else r!==void 0&&mn(e,c,s.no,r,!!s.oneof||s.opt);break;case"message":if(o)for(const u of r)Us(e,t,s.T,s.no,u);else Us(e,t,s.T,s.no,r);break;case"map":for(const[u,l]of Object.entries(r))Al(e,t,s,u,l);break}}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e}})}let Nt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),as=[];for(let i=0;i<Nt.length;i++)as[Nt[i].charCodeAt(0)]=i;as[45]=Nt.indexOf("+");as[95]=Nt.indexOf("/");const ea={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=as[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
|
|
18
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=Nt[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=Nt[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=Nt[s|n>>6],e+=Nt[n&63],t=0;break}return t&&(e+=Nt[s],e+="=",t==1&&(e+="=")),e}},Fr={ignoreUnknownFields:!1},jr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ll(i){return i?Object.assign(Object.assign({},Fr),i):Fr}function Ul(i){return i?Object.assign(Object.assign({},jr),i):jr}function Fl(i){const e=i(jl,Br);return{makeReadOptions:Ll,makeWriteOptions:Ul,readMessage(t,n,s,r){if(n==null||Array.isArray(n)||typeof n!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(this.debug(n)));r=r??new t;const o={};for(const[a,c]of Object.entries(n)){const u=t.fields.findJsonName(a);if(!u){if(!s.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(a,'" is unknown'));continue}let l=u.localName,h=r;if(u.oneof){if(c===null&&u.kind=="scalar")continue;const f=o[u.oneof.localName];if(f)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(u.oneof.name,'" present: "').concat(f,'", "').concat(a,'"'));o[u.oneof.localName]=a,h=h[u.oneof.localName]={case:l},l="value"}if(u.repeated){if(c===null)continue;if(!Array.isArray(c))throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c)));const f=h[l];for(const p of c){if(p===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(p)));let v;switch(u.kind){case"message":v=u.T.fromJson(p,s);break;case"enum":if(v=gs(u.T,p,s.ignoreUnknownFields),v===void 0)continue;break;case"scalar":try{v=en(u.T,p,u.L)}catch(y){let R="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(p));throw y instanceof Error&&y.message.length>0&&(R+=": ".concat(y.message)),new Error(R)}break}f.push(v)}}else if(u.kind=="map"){if(c===null)continue;if(Array.isArray(c)||typeof c!="object")throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c)));const f=h[l];for(const[p,v]of Object.entries(c)){if(v===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: map value null"));let y;switch(u.V.kind){case"message":y=u.V.T.fromJson(v,s);break;case"enum":if(y=gs(u.V.T,v,s.ignoreUnknownFields),y===void 0)continue;break;case"scalar":try{y=en(u.V.T,v,Ei.BIGINT)}catch(R){let S="cannot decode map value for field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw R instanceof Error&&R.message.length>0&&(S+=": ".concat(R.message)),new Error(S)}break}try{f[en(u.K,u.K==k.BOOL?p=="true"?!0:p=="false"?!1:p:p,Ei.BIGINT).toString()]=y}catch(R){let S="cannot decode map key for field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw R instanceof Error&&R.message.length>0&&(S+=": ".concat(R.message)),new Error(S)}}}else switch(u.kind){case"message":const f=u.T;if(c===null&&f.typeName!="google.protobuf.Value"){if(u.oneof)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name,' from JSON: null is invalid for oneof field "').concat(a,'"'));continue}h[l]instanceof O?h[l].fromJson(c,s):(h[l]=f.fromJson(c,s),f.fieldWrapper&&!u.oneof&&(h[l]=f.fieldWrapper.unwrapField(h[l])));break;case"enum":const p=gs(u.T,c,s.ignoreUnknownFields);p!==void 0&&(h[l]=p);break;case"scalar":try{h[l]=en(u.T,c,u.L)}catch(v){let y="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw v instanceof Error&&v.message.length>0&&(y+=": ".concat(v.message)),new Error(y)}break}}return r},writeMessage(t,n){const s=t.getType(),r={};let o;try{for(const a of s.fields.byMember()){let c;if(a.kind=="oneof"){const u=t[a.localName];if(u.value===void 0)continue;if(o=a.findField(u.case),!o)throw"oneof case not found: "+u.case;c=e(o,u.value,n)}else o=a,c=e(o,t[o.localName],n);c!==void 0&&(r[n.useProtoFieldName?o.name:o.jsonName]=c)}}catch(a){const c=o?"cannot encode field ".concat(s.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(s.typeName," to JSON"),u=a instanceof Error?a.message:String(a);throw new Error(c+(u.length>0?": ".concat(u):""))}return r},readScalar:en,writeScalar:Br,debug:ta}}function ta(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function en(i,e,t){switch(i){case k.DOUBLE:case k.FLOAT:if(e===null)return 0;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 n=Number(e);if(Number.isNaN(n)||!Number.isFinite(n))break;return i==k.FLOAT&&zo(n),n;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(e===null)return 0;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 i==k.UINT32?Ms(s):Bn(s),s;case k.INT64:case k.SFIXED64:case k.SINT64:if(e===null)return F.zero;if(typeof e!="number"&&typeof e!="string")break;const r=F.parse(e);return t?r.toString():r;case k.FIXED64:case k.UINT64:if(e===null)return F.zero;if(typeof e!="number"&&typeof e!="string")break;const o=F.uParse(e);return t?o.toString():o;case k.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case k.STRING:if(e===null)return"";if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case k.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return ea.dec(e)}throw new Error}function gs(i,e,t){if(e===null)return 0;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const n=i.findName(e);if(n||t)return n==null?void 0:n.no;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(ta(e)))}function jl(i,e,t,n){var s;if(e===void 0)return e;if(e===0&&!t)return;if(n)return e;if(i.typeName=="google.protobuf.NullValue")return null;const r=i.findNumber(e);return(s=r==null?void 0:r.name)!==null&&s!==void 0?s:e}function Br(i,e,t){if(e!==void 0)switch(i){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return Oe(typeof e=="number"),e!=0||t?e:void 0;case k.FLOAT:case k.DOUBLE:return Oe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e!==0||t?e:void 0;case k.STRING:return Oe(typeof e=="string"),e.length>0||t?e:void 0;case k.BOOL:return Oe(typeof e=="boolean"),e||t?e:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return Oe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case k.BYTES:return Oe(e instanceof Uint8Array),t||e.byteLength>0?ea.enc(e):void 0}}function Bl(){return Fl((i,e)=>function(n,s,r){if(n.kind=="map"){const o={};switch(n.V.kind){case"scalar":for(const[c,u]of Object.entries(s)){const l=e(n.V.T,u,!0);Oe(l!==void 0),o[c.toString()]=l}break;case"message":for(const[c,u]of Object.entries(s))o[c.toString()]=u.toJson(r);break;case"enum":const a=n.V.T;for(const[c,u]of Object.entries(s)){Oe(u===void 0||typeof u=="number");const l=i(a,u,!0,r.enumAsInteger);Oe(l!==void 0),o[c.toString()]=l}break}return r.emitDefaultValues||Object.keys(o).length>0?o:void 0}else if(n.repeated){const o=[];switch(n.kind){case"scalar":for(let a=0;a<s.length;a++)o.push(e(n.T,s[a],!0));break;case"enum":for(let a=0;a<s.length;a++)o.push(i(n.T,s[a],!0,r.enumAsInteger));break;case"message":for(let a=0;a<s.length;a++)o.push(Ds(n.T,s[a]).toJson(r));break}return r.emitDefaultValues||o.length>0?o:void 0}else switch(n.kind){case"scalar":return e(n.T,s,!!n.oneof||n.opt||r.emitDefaultValues);case"enum":return i(n.T,s,!!n.oneof||n.opt||r.emitDefaultValues,r.enumAsInteger);case"message":return s!==void 0?Ds(n.T,s).toJson(r):void 0}})}function Jl(){return{setEnumType:Wo,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!==void 0)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let u=o[s].value;c&&c.kind=="message"&&!(u instanceof c.T)?u=new c.T(u):c&&c.kind==="scalar"&&c.T===k.BYTES&&(u=tn(u)),r[s]={case:a,value:u};break;case"scalar":case"enum":let l=o[s];n.T===k.BYTES&&(l=n.repeated?l.map(tn):tn(l)),r[s]=l;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===k.BYTES)for(const[p,v]of Object.entries(o[s]))r[s][p]=tn(v);else Object.assign(r[s],o[s]);break;case"message":const f=n.V.T;for(const p of Object.keys(o[s])){let v=o[s][p];f.fieldWrapper||(v=new f(v)),r[s][p]=v}break}break;case"message":const h=n.T;if(n.repeated)r[s]=o[s].map(f=>f instanceof h?f:new h(f));else if(o[s]!==void 0){const f=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?r[s]=tn(f):r[s]=f:r[s]=f instanceof h?f:new h(f)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>hi(n.T,o,r[a]));case"enum":return s.every((o,a)=>hi(k.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(s,r);case"enum":return hi(k.INT32,s,r);case"scalar":return hi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const o=n.findField(s.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(s.value,r.value);case"enum":return hi(k.INT32,s.value,r.value);case"scalar":return hi(o.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const a=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const c=n.V.T;return a.every(l=>c.equals(s[l],r[l]));case"enum":return a.every(l=>hi(k.INT32,s[l],r[l]));case"scalar":const u=n.V.T;return a.every(l=>hi(u,s[l],r[l]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Ln);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Ln(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Ln(r.value)}:{case:void 0}:o=Ln(r);n[s.localName]=o}return t}}}function Ln(i){if(i===void 0)return i;if(i instanceof O)return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function tn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}class Vl{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function ia(i,e){const t=na(i);return e?t:Wl(Gl(t))}function ql(i){return ia(i,!1)}const $l=na;function na(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){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(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Hl=new Set(["constructor","toString","toJSON","valueOf"]),zl=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),sa=i=>"".concat(i,"$"),Gl=i=>zl.has(i)?sa(i):i,Wl=i=>Hl.has(i)?sa(i):i;class Kl{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ql(e)}addField(e){Oe(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]}}const d=kl("proto3",Bl(),Dl(),Object.assign(Object.assign({},Jl()),{newFieldList(i){return new Vl(i,Yl)},initFields(i){for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Ls(e.T,e.L);break}}}}));function Yl(i){var e,t,n,s;const r=[];let o;for(const a of typeof i=="function"?i():i){const c=a;if(c.localName=ia(a.name,a.oneof!==void 0),c.jsonName=(e=a.jsonName)!==null&&e!==void 0?e:$l(a.name),c.repeated=(t=a.repeated)!==null&&t!==void 0?t:!1,a.kind=="scalar"&&(c.L=(n=a.L)!==null&&n!==void 0?n:Ei.BIGINT),c.packed=(s=a.packed)!==null&&s!==void 0?s:a.kind=="enum"||a.kind=="scalar"&&a.T!=k.BYTES&&a.T!=k.STRING,a.oneof!==void 0){const u=typeof a.oneof=="string"?a.oneof:a.oneof.name;(!o||o.name!=u)&&(o=new Kl(u)),c.oneof=o,o.addField(c)}r.push(c)}return r}class ge extends O{constructor(e){super(),this.seconds=F.zero,this.nanos=0,d.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(d.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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=F.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[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 n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ge.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ge({seconds:F.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ge().fromBinary(e,t)}static fromJson(e,t){return new ge().fromJson(e,t)}static fromJsonString(e,t){return new ge().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ge,e,t)}}ge.runtime=d;ge.typeName="google.protobuf.Timestamp";ge.fields=d.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var Fs;(function(i){i[i.DEFAULT_AC=0]="DEFAULT_AC",i[i.OPUS=1]="OPUS",i[i.AAC=2]="AAC"})(Fs||(Fs={}));d.util.setEnumType(Fs,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]);var js;(function(i){i[i.DEFAULT_VC=0]="DEFAULT_VC",i[i.H264_BASELINE=1]="H264_BASELINE",i[i.H264_MAIN=2]="H264_MAIN",i[i.H264_HIGH=3]="H264_HIGH",i[i.VP8=4]="VP8"})(js||(js={}));d.util.setEnumType(js,"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"}]);var Bs;(function(i){i[i.IC_DEFAULT=0]="IC_DEFAULT",i[i.IC_JPEG=1]="IC_JPEG"})(Bs||(Bs={}));d.util.setEnumType(Bs,"livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]);var Se;(function(i){i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.DATA=2]="DATA"})(Se||(Se={}));d.util.setEnumType(Se,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]);var ce;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.CAMERA=1]="CAMERA",i[i.MICROPHONE=2]="MICROPHONE",i[i.SCREEN_SHARE=3]="SCREEN_SHARE",i[i.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO"})(ce||(ce={}));d.util.setEnumType(ce,"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"}]);var ui;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH",i[i.OFF=3]="OFF"})(ui||(ui={}));d.util.setEnumType(ui,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]);var At;(function(i){i[i.POOR=0]="POOR",i[i.GOOD=1]="GOOD",i[i.EXCELLENT=2]="EXCELLENT",i[i.LOST=3]="LOST"})(At||(At={}));d.util.setEnumType(At,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]);var et;(function(i){i[i.UNSET=0]="UNSET",i[i.DISABLED=1]="DISABLED",i[i.ENABLED=2]="ENABLED"})(et||(et={}));d.util.setEnumType(et,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]);var ri;(function(i){i[i.UNKNOWN_REASON=0]="UNKNOWN_REASON",i[i.CLIENT_INITIATED=1]="CLIENT_INITIATED",i[i.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",i[i.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",i[i.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",i[i.ROOM_DELETED=5]="ROOM_DELETED",i[i.STATE_MISMATCH=6]="STATE_MISMATCH",i[i.JOIN_FAILURE=7]="JOIN_FAILURE",i[i.MIGRATION=8]="MIGRATION",i[i.SIGNAL_CLOSE=9]="SIGNAL_CLOSE"})(ri||(ri={}));d.util.setEnumType(ri,"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"}]);var xt;(function(i){i[i.RR_UNKNOWN=0]="RR_UNKNOWN",i[i.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",i[i.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",i[i.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",i[i.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE"})(xt||(xt={}));d.util.setEnumType(xt,"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"}]);var wn;(function(i){i[i.SE_UNKNOWN=0]="SE_UNKNOWN",i[i.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",i[i.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND"})(wn||(wn={}));d.util.setEnumType(wn,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let Wi=class un extends O{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=F.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new un().fromBinary(e,t)}static fromJson(e,t){return new un().fromJson(e,t)}static fromJsonString(e,t){return new un().fromJsonString(e,t)}static equals(e,t){return d.util.equals(un,e,t)}};Wi.runtime=d;Wi.typeName="livekit.Room";Wi.fields=d.util.newFieldList(()=>[{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:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ze,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:ft}]);class ze extends O{constructor(e){super(),this.mime="",this.fmtpLine="",d.util.initPartial(e,this)}static fromBinary(e,t){return new ze().fromBinary(e,t)}static fromJson(e,t){return new ze().fromJson(e,t)}static fromJsonString(e,t){return new ze().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ze,e,t)}}ze.runtime=d;ze.typeName="livekit.Codec";ze.fields=d.util.newFieldList(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);class pi extends O{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new pi().fromBinary(e,t)}static fromJson(e,t){return new pi().fromJson(e,t)}static fromJsonString(e,t){return new pi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(pi,e,t)}}pi.runtime=d;pi.typeName="livekit.PlayoutDelay";pi.fields=d.util.newFieldList(()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]);class Mt extends O{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,this.agent=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Mt().fromBinary(e,t)}static fromJson(e,t){return new Mt().fromJson(e,t)}static fromJsonString(e,t){return new Mt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Mt,e,t)}}Mt.runtime=d;Mt.typeName="livekit.ParticipantPermission";Mt.fields=d.util.newFieldList(()=>[{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:d.getEnumType(ce),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}]);class De extends O{constructor(e){super(),this.sid="",this.identity="",this.state=Pi.JOINING,this.tracks=[],this.metadata="",this.joinedAt=F.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,this.kind=En.STANDARD,d.util.initPartial(e,this)}static fromBinary(e,t){return new De().fromBinary(e,t)}static fromJson(e,t){return new De().fromJson(e,t)}static fromJsonString(e,t){return new De().fromJsonString(e,t)}static equals(e,t){return d.util.equals(De,e,t)}}De.runtime=d;De.typeName="livekit.ParticipantInfo";De.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:d.getEnumType(Pi)},{no:4,name:"tracks",kind:"message",T:xe,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",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:Mt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:d.getEnumType(En)}]);var Pi;(function(i){i[i.JOINING=0]="JOINING",i[i.JOINED=1]="JOINED",i[i.ACTIVE=2]="ACTIVE",i[i.DISCONNECTED=3]="DISCONNECTED"})(Pi||(Pi={}));d.util.setEnumType(Pi,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);var En;(function(i){i[i.STANDARD=0]="STANDARD",i[i.INGRESS=1]="INGRESS",i[i.EGRESS=2]="EGRESS",i[i.SIP=3]="SIP",i[i.AGENT=4]="AGENT"})(En||(En={}));d.util.setEnumType(En,"livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]);class mi extends O{constructor(e){super(),d.util.initPartial(e,this)}static fromBinary(e,t){return new mi().fromBinary(e,t)}static fromJson(e,t){return new mi().fromJson(e,t)}static fromJsonString(e,t){return new mi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(mi,e,t)}}mi.runtime=d;mi.typeName="livekit.Encryption";mi.fields=d.util.newFieldList(()=>[]);var be;(function(i){i[i.NONE=0]="NONE",i[i.GCM=1]="GCM",i[i.CUSTOM=2]="CUSTOM"})(be||(be={}));d.util.setEnumType(be,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class Dt extends O{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Dt().fromBinary(e,t)}static fromJson(e,t){return new Dt().fromJson(e,t)}static fromJsonString(e,t){return new Dt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Dt,e,t)}}Dt.runtime=d;Dt.typeName="livekit.SimulcastCodecInfo";Dt.fields=d.util.newFieldList(()=>[{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:Pe,repeated:!0}]);class xe extends O{constructor(e){super(),this.sid="",this.type=Se.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=ce.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=be.NONE,this.stream="",d.util.initPartial(e,this)}static fromBinary(e,t){return new xe().fromBinary(e,t)}static fromJson(e,t){return new xe().fromJson(e,t)}static fromJsonString(e,t){return new xe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(xe,e,t)}}xe.runtime=d;xe.typeName="livekit.TrackInfo";xe.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:d.getEnumType(Se)},{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:d.getEnumType(ce)},{no:10,name:"layers",kind:"message",T:Pe,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:Dt,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:d.getEnumType(be)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ft}]);class Pe extends O{constructor(e){super(),this.quality=ui.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new Pe().fromBinary(e,t)}static fromJson(e,t){return new Pe().fromJson(e,t)}static fromJsonString(e,t){return new Pe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Pe,e,t)}}Pe.runtime=d;Pe.typeName="livekit.VideoLayer";Pe.fields=d.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:d.getEnumType(ui)},{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}]);class ot extends O{constructor(e){super(),this.kind=fe.RELIABLE,this.value={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new ot().fromBinary(e,t)}static fromJson(e,t){return new ot().fromJson(e,t)}static fromJsonString(e,t){return new ot().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ot,e,t)}}ot.runtime=d;ot.typeName="livekit.DataPacket";ot.fields=d.util.newFieldList(()=>[{no:1,name:"kind",kind:"enum",T:d.getEnumType(fe)},{no:2,name:"user",kind:"message",T:ct,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Lt,oneof:"value"}]);var fe;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY"})(fe||(fe={}));d.util.setEnumType(fe,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class Lt extends O{constructor(e){super(),this.speakers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Lt().fromBinary(e,t)}static fromJson(e,t){return new Lt().fromJson(e,t)}static fromJsonString(e,t){return new Lt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Lt,e,t)}}Lt.runtime=d;Lt.typeName="livekit.ActiveSpeakerUpdate";Lt.fields=d.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:at,repeated:!0}]);class at extends O{constructor(e){super(),this.sid="",this.level=0,this.active=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new at().fromBinary(e,t)}static fromJson(e,t){return new at().fromJson(e,t)}static fromJsonString(e,t){return new at().fromJsonString(e,t)}static equals(e,t){return d.util.equals(at,e,t)}}at.runtime=d;at.typeName="livekit.SpeakerInfo";at.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]);class ct extends O{constructor(e){super(),this.participantSid="",this.participantIdentity="",this.payload=new Uint8Array(0),this.destinationSids=[],this.destinationIdentities=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new ct().fromBinary(e,t)}static fromJson(e,t){return new ct().fromJson(e,t)}static fromJsonString(e,t){return new ct().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ct,e,t)}}ct.runtime=d;ct.typeName="livekit.UserPacket";ct.fields=d.util.newFieldList(()=>[{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}]);class ut extends O{constructor(e){super(),this.participantSid="",this.trackSids=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new ut().fromBinary(e,t)}static fromJson(e,t){return new ut().fromJson(e,t)}static fromJsonString(e,t){return new ut().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ut,e,t)}}ut.runtime=d;ut.typeName="livekit.ParticipantTracks";ut.fields=d.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]);class Ut extends O{constructor(e){super(),this.edition=Hi.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ut().fromBinary(e,t)}static fromJson(e,t){return new Ut().fromJson(e,t)}static fromJsonString(e,t){return new Ut().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ut,e,t)}}Ut.runtime=d;Ut.typeName="livekit.ServerInfo";Ut.fields=d.util.newFieldList(()=>[{no:1,name:"edition",kind:"enum",T:d.getEnumType(Hi)},{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}]);var Hi;(function(i){i[i.Standard=0]="Standard",i[i.Cloud=1]="Cloud"})(Hi||(Hi={}));d.util.setEnumType(Hi,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class Ft extends O{constructor(e){super(),this.sdk=zi.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ft().fromBinary(e,t)}static fromJson(e,t){return new Ft().fromJson(e,t)}static fromJsonString(e,t){return new Ft().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ft,e,t)}}Ft.runtime=d;Ft.typeName="livekit.ClientInfo";Ft.fields=d.util.newFieldList(()=>[{no:1,name:"sdk",kind:"enum",T:d.getEnumType(zi)},{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}]);var zi;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.JS=1]="JS",i[i.SWIFT=2]="SWIFT",i[i.ANDROID=3]="ANDROID",i[i.FLUTTER=4]="FLUTTER",i[i.GO=5]="GO",i[i.UNITY=6]="UNITY",i[i.REACT_NATIVE=7]="REACT_NATIVE",i[i.RUST=8]="RUST",i[i.PYTHON=9]="PYTHON",i[i.CPP=10]="CPP"})(zi||(zi={}));d.util.setEnumType(zi,"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"}]);class lt extends O{constructor(e){super(),this.resumeConnection=et.UNSET,this.forceRelay=et.UNSET,d.util.initPartial(e,this)}static fromBinary(e,t){return new lt().fromBinary(e,t)}static fromJson(e,t){return new lt().fromJson(e,t)}static fromJsonString(e,t){return new lt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(lt,e,t)}}lt.runtime=d;lt.typeName="livekit.ClientConfiguration";lt.fields=d.util.newFieldList(()=>[{no:1,name:"video",kind:"message",T:dt},{no:2,name:"screen",kind:"message",T:dt},{no:3,name:"resume_connection",kind:"enum",T:d.getEnumType(et)},{no:4,name:"disabled_codecs",kind:"message",T:jt},{no:5,name:"force_relay",kind:"enum",T:d.getEnumType(et)}]);class dt extends O{constructor(e){super(),this.hardwareEncoder=et.UNSET,d.util.initPartial(e,this)}static fromBinary(e,t){return new dt().fromBinary(e,t)}static fromJson(e,t){return new dt().fromJson(e,t)}static fromJsonString(e,t){return new dt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(dt,e,t)}}dt.runtime=d;dt.typeName="livekit.VideoConfiguration";dt.fields=d.util.newFieldList(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:d.getEnumType(et)}]);class jt extends O{constructor(e){super(),this.codecs=[],this.publish=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new jt().fromBinary(e,t)}static fromJson(e,t){return new jt().fromJson(e,t)}static fromJsonString(e,t){return new jt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(jt,e,t)}}jt.runtime=d;jt.typeName="livekit.DisabledCodecs";jt.fields=d.util.newFieldList(()=>[{no:1,name:"codecs",kind:"message",T:ze,repeated:!0},{no:2,name:"publish",kind:"message",T:ze,repeated:!0}]);class ht extends O{constructor(e){super(),this.duration=0,this.startTimestamp=F.zero,this.endTimestamp=F.zero,this.rtpClockTicks=F.zero,this.driftSamples=F.zero,this.driftMs=0,this.clockRate=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new ht().fromBinary(e,t)}static fromJson(e,t){return new ht().fromJson(e,t)}static fromJsonString(e,t){return new ht().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ht,e,t)}}ht.runtime=d;ht.typeName="livekit.RTPDrift";ht.fields=d.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:ge},{no:2,name:"end_time",kind:"message",T:ge},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]);class gi extends O{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=F.zero,this.headerBytes=F.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=F.zero,this.headerBytesDuplicate=F.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=F.zero,this.headerBytesPadding=F.zero,this.bitratePadding=0,this.packetsOutOfOrder=0,this.frames=0,this.frameRate=0,this.jitterCurrent=0,this.jitterMax=0,this.gapHistogram={},this.nacks=0,this.nackAcks=0,this.nackMisses=0,this.nackRepeated=0,this.plis=0,this.firs=0,this.rttCurrent=0,this.rttMax=0,this.keyFrames=0,this.layerLockPlis=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new gi().fromBinary(e,t)}static fromJson(e,t){return new gi().fromJson(e,t)}static fromJsonString(e,t){return new gi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(gi,e,t)}}gi.runtime=d;gi.typeName="livekit.RTPStats";gi.fields=d.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:ge},{no:2,name:"end_time",kind:"message",T:ge},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:ge},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:ge},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:ge},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:ge},{no:44,name:"packet_drift",kind:"message",T:ht},{no:45,name:"report_drift",kind:"message",T:ht}]);class ft extends O{constructor(e){super(),this.unixMicro=F.zero,this.ticks=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new ft().fromBinary(e,t)}static fromJson(e,t){return new ft().fromJson(e,t)}static fromJsonString(e,t){return new ft().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ft,e,t)}}ft.runtime=d;ft.typeName="livekit.TimedVersion";ft.fields=d.util.newFieldList(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]);const nn=7e3,Xl=[0,300,2*2*300,3*3*300,4*4*300,nn,nn,nn,nn,nn];class Ql{constructor(e){this._retryDelays=e!==void 0?[...e]:Xl}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 m(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?r(l.value):s(l.value).then(a,c)}u((n=n.apply(i,e||[])).next())})}function Jr(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ui(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Jr=="function"?Jr(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(u){r({value:u,done:a})},o)}}var hr={exports:{}},Bi=typeof Reflect=="object"?Reflect:null,Vr=Bi&&typeof Bi.apply=="function"?Bi.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},qn;Bi&&typeof Bi.ownKeys=="function"?qn=Bi.ownKeys:Object.getOwnPropertySymbols?qn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:qn=function(e){return Object.getOwnPropertyNames(e)};function Zl(i){console&&console.warn&&console.warn(i)}var ra=Number.isNaN||function(e){return e!==e};function Z(){Z.init.call(this)}hr.exports=Z;hr.exports.once=nd;Z.EventEmitter=Z;Z.prototype._events=void 0;Z.prototype._eventsCount=0;Z.prototype._maxListeners=void 0;var qr=10;function cs(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(Z,"defaultMaxListeners",{enumerable:!0,get:function(){return qr},set:function(i){if(typeof i!="number"||i<0||ra(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");qr=i}});Z.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};Z.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ra(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function oa(i){return i._maxListeners===void 0?Z.defaultMaxListeners:i._maxListeners}Z.prototype.getMaxListeners=function(){return oa(this)};Z.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s=e==="error",r=this._events;if(r!==void 0)s=s&&r.error===void 0;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(c===void 0)return!1;if(typeof c=="function")Vr(c,this,t);else for(var u=c.length,l=da(c,u),n=0;n<u;++n)Vr(l[n],this,t);return!0};function aa(i,e,t,n){var s,r,o;if(cs(t),r=i._events,r===void 0?(r=i._events=Object.create(null),i._eventsCount=0):(r.newListener!==void 0&&(i.emit("newListener",e,t.listener?t.listener:t),r=i._events),o=r[e]),o===void 0)o=r[e]=t,++i._eventsCount;else if(typeof o=="function"?o=r[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),s=oa(i),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=i,a.type=e,a.count=o.length,Zl(a)}return i}Z.prototype.addListener=function(e,t){return aa(this,e,t,!1)};Z.prototype.on=Z.prototype.addListener;Z.prototype.prependListener=function(e,t){return aa(this,e,t,!0)};function ed(){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 ca(i,e,t){var n={fired:!1,wrapFn:void 0,target:i,type:e,listener:t},s=ed.bind(n);return s.listener=t,n.wrapFn=s,s}Z.prototype.once=function(e,t){return cs(t),this.on(e,ca(this,e,t)),this};Z.prototype.prependOnceListener=function(e,t){return cs(t),this.prependListener(e,ca(this,e,t)),this};Z.prototype.removeListener=function(e,t){var n,s,r,o,a;if(cs(t),s=this._events,s===void 0)return this;if(n=s[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(r=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,r=o;break}if(r<0)return this;r===0?n.shift():td(n,r),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};Z.prototype.off=Z.prototype.removeListener;Z.prototype.removeAllListeners=function(e){var t,n,s;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var r=Object.keys(n),o;for(s=0;s<r.length;++s)o=r[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function ua(i,e,t){var n=i._events;if(n===void 0)return[];var s=n[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?id(s):da(s,s.length)}Z.prototype.listeners=function(e){return ua(this,e,!0)};Z.prototype.rawListeners=function(e){return ua(this,e,!1)};Z.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):la.call(i,e)};Z.prototype.listenerCount=la;function la(i){var e=this._events;if(e!==void 0){var t=e[i];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Z.prototype.eventNames=function(){return this._eventsCount>0?qn(this._events):[]};function da(i,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=i[n];return t}function td(i,e){for(;e+1<i.length;e++)i[e]=i[e+1];i.pop()}function id(i){for(var e=new Array(i.length),t=0;t<e.length;++t)e[t]=i[t].listener||i[t];return e}function nd(i,e){return new Promise(function(t,n){function s(o){i.removeListener(e,r),n(o)}function r(){typeof i.removeListener=="function"&&i.removeListener("error",s),t([].slice.call(arguments))}ha(i,e,r,{once:!0}),e!=="error"&&sd(i,s,{once:!0})})}function sd(i,e,t){typeof i.on=="function"&&ha(i,"error",e,t)}function ha(i,e,t,n){if(typeof i.on=="function")n.once?i.once(e,t):i.on(e,t);else if(typeof i.addEventListener=="function")i.addEventListener(e,function s(r){n.once&&i.removeEventListener(e,s),t(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof i)}var Et=hr.exports;let fa=!0,pa=!0;function $n(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function xi(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=u=>{const l=t(u);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"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 rd(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(fa=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function od(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(pa=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function ma(){if(typeof window=="object"){if(fa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function fr(i,e){pa&&console.warn(i+" is deprecated, please use "+e+" instead.")}function ad(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.mozGetUserMedia)e.browser="firefox",e.version=$n(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=$n(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=$n(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function $r(i){return Object.prototype.toString.call(i)==="[object Object]"}function ga(i){return $r(i)?Object.keys(i).reduce(function(e,t){const n=$r(i[t]),s=n?ga(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function Js(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Js(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{Js(i,i.get(s),t)})}))}function Hr(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&Js(i,a,s)})}),s}const zr=ma;function va(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(u=>{if(u==="require"||u==="advanced"||u==="mediaSource")return;const l=typeof a[u]=="object"?a[u]:{ideal:a[u]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const h=function(f,p){return f?f+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let f={};typeof l.ideal=="number"?(f[h("min",u)]=l.ideal,c.optional.push(f),f={},f[h("max",u)]=l.ideal,c.optional.push(f)):(f[h("",u)]=l.ideal,c.optional.push(f))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",u)]=l.exact):["min","max"].forEach(f=>{l[f]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(f,u)]=l[f])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const u=function(l,h,f){h in l&&!(f in l)&&(l[f]=l[h],delete l[h])};a=JSON.parse(JSON.stringify(a)),u(a.audio,"autoGainControl","googAutoGainControl"),u(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let u=a.video.facingMode;u=u&&(typeof u=="object"?u:{ideal:u});const l=e.version<66;if(u&&(u.exact==="user"||u.exact==="environment"||u.ideal==="user"||u.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let h;if(u.exact==="environment"||u.ideal==="environment"?h=["back","rear"]:(u.exact==="user"||u.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(f=>{f=f.filter(v=>v.kind==="videoinput");let p=f.find(v=>h.some(y=>v.label.toLowerCase().includes(y)));return!p&&f.length&&h.includes("back")&&(p=f[f.length-1]),p&&(a.video.deviceId=u.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=n(a.video),zr("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return zr("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,u){s(a,l=>{t.webkitGetUserMedia(l,c,h=>{u&&u(r(h))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,u=>a(u).then(l=>{if(u.audio&&!l.getAudioTracks().length||u.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function cd(i,e){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&i.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(n){return e(n).then(s=>{const r=n.video&&n.video.width,o=n.video&&n.video.height,a=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:a||3}},r&&(n.video.mandatory.maxWidth=r),o&&(n.video.mandatory.maxHeight=o),i.navigator.mediaDevices.getUserMedia(n)})}}}function ya(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function ba(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else xi(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function ka(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let u=s.apply(this,arguments);return u||(u=e(this,a),this._senders.push(u)),u};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.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 Ca(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[n,s,r]=arguments;if(arguments.length>0&&typeof n=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof n!="function"))return e.apply(this,[]);const o=function(c){const u={};return c.result().forEach(h=>{const f={id:h.id,timestamp:h.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type};h.names().forEach(p=>{f[p]=h.stat(p)}),u[f.id]=f}),u},a=function(c){return new Map(Object.keys(c).map(u=>[u,c[u]]))};if(arguments.length>=2){const c=function(u){s(a(o(u)))};return e.apply(this,[c,n])}return new Promise((c,u)=>{e.apply(this,[function(l){c(a(o(l)))},u])}).then(s,r)}}function Ta(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Hr(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),xi(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Hr(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Sa(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(u=>a.indexOf(u)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function wa(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Sa(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(h=>{if(this.getSenders().find(p=>p.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const h=new i.MediaStream(l.getTracks());this._streams[l.id]=h,this._reverseStreams[h.id]=l,l=h}n.apply(this,[l])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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]},i.RTCPeerConnection.prototype.addTrack=function(l,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const f=[].slice.call(arguments,1);if(f.length!==1||!f[0].getTracks().find(y=>y===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(y=>y.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const v=this._streams[h.id];if(v)v.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const y=new i.MediaStream([l]);this._streams[h.id]=y,this._reverseStreams[y.id]=h,this.addStream(y)}return this.getSenders().find(y=>y.track===l)};function r(u,l){let h=l.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],v=u._streams[p.id];h=h.replace(new RegExp(v.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:h})}function o(u,l){let h=l.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],v=u._streams[p.id];h=h.replace(new RegExp(p.id,"g"),v.id)}),new RTCSessionDescription({type:l.type,sdp:h})}["createOffer","createAnswer"].forEach(function(u){const l=i.RTCPeerConnection.prototype[u],h={[u](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[v=>{const y=r(this,v);f[0].apply(null,[y])},v=>{f[1]&&f[1].apply(null,v)},arguments[2]]):l.apply(this,arguments).then(v=>r(this,v))}};i.RTCPeerConnection.prototype[u]=h[u]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const u=c.get.apply(this);return u.type===""?u:r(this,u)}}),i.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 f;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(y=>l.track===y)&&(f=this._streams[p])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Vs(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function Ea(i,e){xi(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Gr=Object.freeze({__proto__:null,fixNegotiationNeeded:Ea,shimAddTrackRemoveTrack:wa,shimAddTrackRemoveTrackWithNative:Sa,shimGetDisplayMedia:cd,shimGetSendersWithDtmf:ka,shimGetStats:Ca,shimGetUserMedia:va,shimMediaStream:ya,shimOnTrack:ba,shimPeerConnection:Vs,shimSenderReceiverGetStats:Ta});function Pa(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){fr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function ud(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function _a(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function qs(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(u=>{u.type=t[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;c.forEach((l,h)=>{c.set(h,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function Ra(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Oa(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),xi(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function xa(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){fr("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ia(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Na(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function Aa(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Ma(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.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 Da(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.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 Wr=Object.freeze({__proto__:null,shimAddTransceiver:Na,shimCreateAnswer:Da,shimCreateOffer:Ma,shimGetDisplayMedia:ud,shimGetParameters:Aa,shimGetUserMedia:Pa,shimOnTrack:_a,shimPeerConnection:qs,shimRTCDataChannel:Ia,shimReceiverGetStats:Oa,shimRemoveStream:xa,shimSenderGetStats:Ra});function La(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Ua(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.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=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function Fa(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(u,l){const h=arguments.length>=2?arguments[2]:arguments[0],f=t.apply(this,[h]);return l?(f.then(u,l),Promise.resolve()):f},e.createAnswer=function(u,l){const h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return l?(f.then(u,l),Promise.resolve()):f};let a=function(c,u,l){const h=s.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h};e.setLocalDescription=a,a=function(c,u,l){const h=r.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h},e.setRemoteDescription=a,a=function(c,u,l){const h=o.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h},e.addIceCandidate=a}function ja(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Ba(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Ba(i){return i&&i.video!==void 0?Object.assign({},i,{video:ga(i.video)}):i}function Ja(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(fr("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Va(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function qa(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function $a(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Kr=Object.freeze({__proto__:null,shimAudioContext:$a,shimCallbacksAPI:Fa,shimConstraints:Ba,shimCreateOfferLegacy:qa,shimGetUserMedia:ja,shimLocalStreamsAPI:La,shimRTCIceServerUrls:Ja,shimRemoteStreamsAPI:Ua,shimTrackEventTransceiver:Va}),Ha={exports:{}};(function(i){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(`
|
|
17
|
+
***************************************************************************** */var Ar;(function(i){(function(e){var t=typeof Nr=="object"?Nr:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),n=s(i);typeof t.Reflect>"u"?t.Reflect=i:n=s(t.Reflect,n),e(n);function s(r,o){return function(a,c){typeof r[a]!="function"&&Object.defineProperty(r,a,{configurable:!0,writable:!0,value:c}),o&&o(a,c)}}})(function(e){var t=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",s=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",r=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",a={__proto__:[]}instanceof Array,c=!o&&!a,u={create:o?function(){return fs(Object.create(null))}:a?function(){return fs({__proto__:null})}:function(){return fs({})},has:c?function(g,b){return t.call(g,b)}:function(g,b){return b in g},get:c?function(g,b){return t.call(g,b)?g[b]:void 0}:function(g,b){return g[b]}},l=Object.getPrototypeOf(Function),h=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",f=!h&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Sc(),p=!h&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:wc(),y=!h&&typeof WeakMap=="function"?WeakMap:Ec(),v=new y;function w(g,b,T,P){if(Z(T)){if(!Tr(g))throw new TypeError;if(!Sr(b))throw new TypeError;return H(g,b)}else{if(!Tr(g))throw new TypeError;if(!oe(b))throw new TypeError;if(!oe(P)&&!Z(P)&&!Ee(P))throw new TypeError;return Ee(P)&&(P=void 0),T=_t(T),Et(g,b,T,P)}}e("decorate",w);function S(g,b){function T(P,D){if(!oe(P))throw new TypeError;if(!Z(D)&&!yc(D))throw new TypeError;An(g,b,P,D)}return T}e("metadata",S);function E(g,b,T,P){if(!oe(T))throw new TypeError;return Z(P)||(P=_t(P)),An(g,b,T,P)}e("defineMetadata",E);function J(g,b,T){if(!oe(b))throw new TypeError;return Z(T)||(T=_t(T)),Qi(g,b,T)}e("hasMetadata",J);function K(g,b,T){if(!oe(b))throw new TypeError;return Z(T)||(T=_t(T)),xi(g,b,T)}e("hasOwnMetadata",K);function me(g,b,T){if(!oe(b))throw new TypeError;return Z(T)||(T=_t(T)),Nn(g,b,T)}e("getMetadata",me);function de(g,b,T){if(!oe(b))throw new TypeError;return Z(T)||(T=_t(T)),Zi(g,b,T)}e("getOwnMetadata",de);function U(g,b){if(!oe(g))throw new TypeError;return Z(b)||(b=_t(b)),O(g,b)}e("getMetadataKeys",U);function ee(g,b){if(!oe(g))throw new TypeError;return Z(b)||(b=_t(b)),ge(g,b)}e("getOwnMetadataKeys",ee);function M(g,b,T){if(!oe(b))throw new TypeError;Z(T)||(T=_t(T));var P=tt(b,T,!1);if(Z(P)||!P.delete(g))return!1;if(P.size>0)return!0;var D=v.get(b);return D.delete(T),D.size>0||v.delete(b),!0}e("deleteMetadata",M);function H(g,b){for(var T=g.length-1;T>=0;--T){var P=g[T],D=P(b);if(!Z(D)&&!Ee(D)){if(!Sr(D))throw new TypeError;b=D}}return b}function Et(g,b,T,P){for(var D=g.length-1;D>=0;--D){var be=g[D],j=be(b,T,P);if(!Z(j)&&!Ee(j)){if(!oe(j))throw new TypeError;P=j}}return P}function tt(g,b,T){var P=v.get(g);if(Z(P)){if(!T)return;P=new f,v.set(g,P)}var D=P.get(b);if(Z(D)){if(!T)return;D=new f,P.set(b,D)}return D}function Qi(g,b,T){var P=xi(g,b,T);if(P)return!0;var D=hs(b);return Ee(D)?!1:Qi(g,D,T)}function xi(g,b,T){var P=tt(b,T,!1);return Z(P)?!1:Pt(P.has(g))}function Nn(g,b,T){var P=xi(g,b,T);if(P)return Zi(g,b,T);var D=hs(b);if(!Ee(D))return Nn(g,D,T)}function Zi(g,b,T){var P=tt(b,T,!1);if(!Z(P))return P.get(g)}function An(g,b,T,P){var D=tt(T,P,!0);D.set(g,b)}function O(g,b){var T=ge(g,b),P=hs(g);if(P===null)return T;var D=O(P,b);if(D.length<=0)return T;if(T.length<=0)return D;for(var be=new p,j=[],B=0,L=T;B<L.length;B++){var z=L[B],G=be.has(z);G||(be.add(z),j.push(z))}for(var li=0,Er=D;li<Er.length;li++){var z=Er[li],G=be.has(z);G||(be.add(z),j.push(z))}return j}function ge(g,b){var T=[],P=tt(g,b,!1);if(Z(P))return T;for(var D=P.keys(),be=bc(D),j=0;;){var B=Cc(be);if(!B)return T.length=j,T;var L=kc(B);try{T[j]=L}catch(z){try{Tc(be)}finally{throw z}}j++}}function ve(g){if(g===null)return 1;switch(typeof g){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return g===null?1:6;default:return 6}}function Z(g){return g===void 0}function Ee(g){return g===null}function Ii(g){return typeof g=="symbol"}function oe(g){return typeof g=="object"?g!==null:typeof g=="function"}function Mn(g,b){switch(ve(g)){case 0:return g;case 1:return g;case 2:return g;case 3:return g;case 4:return g;case 5:return g}var T=b===3?"string":b===5?"number":"default",P=wr(g,s);if(P!==void 0){var D=P.call(g,T);if(oe(D))throw new TypeError;return D}return Ni(g,T==="default"?"number":T)}function Ni(g,b){if(b==="string"){var T=g.toString;if(Ai(T)){var P=T.call(g);if(!oe(P))return P}var D=g.valueOf;if(Ai(D)){var P=D.call(g);if(!oe(P))return P}}else{var D=g.valueOf;if(Ai(D)){var P=D.call(g);if(!oe(P))return P}var be=g.toString;if(Ai(be)){var P=be.call(g);if(!oe(P))return P}}throw new TypeError}function Pt(g){return!!g}function vc(g){return""+g}function _t(g){var b=Mn(g,3);return Ii(b)?b:vc(b)}function Tr(g){return Array.isArray?Array.isArray(g):g instanceof Object?g instanceof Array:Object.prototype.toString.call(g)==="[object Array]"}function Ai(g){return typeof g=="function"}function Sr(g){return typeof g=="function"}function yc(g){switch(ve(g)){case 3:return!0;case 4:return!0;default:return!1}}function wr(g,b){var T=g[b];if(T!=null){if(!Ai(T))throw new TypeError;return T}}function bc(g){var b=wr(g,r);if(!Ai(b))throw new TypeError;var T=b.call(g);if(!oe(T))throw new TypeError;return T}function kc(g){return g.value}function Cc(g){var b=g.next();return b.done?!1:b}function Tc(g){var b=g.return;b&&b.call(g)}function hs(g){var b=Object.getPrototypeOf(g);if(typeof g!="function"||g===l||b!==l)return b;var T=g.prototype,P=T&&Object.getPrototypeOf(T);if(P==null||P===Object.prototype)return b;var D=P.constructor;return typeof D!="function"||D===g?b:D}function Sc(){var g={},b=[],T=function(){function j(B,L,z){this._index=0,this._keys=B,this._values=L,this._selector=z}return j.prototype["@@iterator"]=function(){return this},j.prototype[r]=function(){return this},j.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var L=this._selector(this._keys[B],this._values[B]);return B+1>=this._keys.length?(this._index=-1,this._keys=b,this._values=b):this._index++,{value:L,done:!1}}return{value:void 0,done:!0}},j.prototype.throw=function(B){throw this._index>=0&&(this._index=-1,this._keys=b,this._values=b),B},j.prototype.return=function(B){return this._index>=0&&(this._index=-1,this._keys=b,this._values=b),{value:B,done:!0}},j}();return function(){function j(){this._keys=[],this._values=[],this._cacheKey=g,this._cacheIndex=-2}return Object.defineProperty(j.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),j.prototype.has=function(B){return this._find(B,!1)>=0},j.prototype.get=function(B){var L=this._find(B,!1);return L>=0?this._values[L]:void 0},j.prototype.set=function(B,L){var z=this._find(B,!0);return this._values[z]=L,this},j.prototype.delete=function(B){var L=this._find(B,!1);if(L>=0){for(var z=this._keys.length,G=L+1;G<z;G++)this._keys[G-1]=this._keys[G],this._values[G-1]=this._values[G];return this._keys.length--,this._values.length--,B===this._cacheKey&&(this._cacheKey=g,this._cacheIndex=-2),!0}return!1},j.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=g,this._cacheIndex=-2},j.prototype.keys=function(){return new T(this._keys,this._values,P)},j.prototype.values=function(){return new T(this._keys,this._values,D)},j.prototype.entries=function(){return new T(this._keys,this._values,be)},j.prototype["@@iterator"]=function(){return this.entries()},j.prototype[r]=function(){return this.entries()},j.prototype._find=function(B,L){return this._cacheKey!==B&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=B)),this._cacheIndex<0&&L&&(this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0)),this._cacheIndex},j}();function P(j,B){return j}function D(j,B){return B}function be(j,B){return[j,B]}}function wc(){return function(){function g(){this._map=new f}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(b){return this._map.has(b)},g.prototype.add=function(b){return this._map.set(b,b),this},g.prototype.delete=function(b){return this._map.delete(b)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.values()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[r]=function(){return this.keys()},g}()}function Ec(){var g=16,b=u.create(),T=P();return function(){function L(){this._key=P()}return L.prototype.has=function(z){var G=D(z,!1);return G!==void 0?u.has(G,this._key):!1},L.prototype.get=function(z){var G=D(z,!1);return G!==void 0?u.get(G,this._key):void 0},L.prototype.set=function(z,G){var li=D(z,!0);return li[this._key]=G,this},L.prototype.delete=function(z){var G=D(z,!1);return G!==void 0?delete G[this._key]:!1},L.prototype.clear=function(){this._key=P()},L}();function P(){var L;do L="@@WeakMap@@"+B();while(u.has(b,L));return b[L]=!0,L}function D(L,z){if(!t.call(L,T)){if(!z)return;Object.defineProperty(L,T,{value:u.create()})}return L[T]}function be(L,z){for(var G=0;G<z;++G)L[G]=Math.random()*255|0;return L}function j(L){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(L)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(L)):be(new Uint8Array(L),L):be(new Array(L),L)}function B(){var L=j(g);L[6]=L[6]&79|64,L[8]=L[8]&191|128;for(var z="",G=0;G<g;++G){var li=L[G];(G===4||G===6||G===8)&&(z+="-"),li<16&&(z+="0"),z+=li.toString(16).toLowerCase()}return z}}function fs(g){return g.__=void 0,delete g.__,g}})})(Ar||(Ar={}));function ul(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var ll=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dl(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var zo={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(ll,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function r(v,w){var S=v[w];if(typeof S.bind=="function")return S.bind(v);try{return Function.prototype.bind.call(S,v)}catch{return function(){return Function.prototype.apply.apply(S,[v,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?o:console[v]!==void 0?r(console,v):console.log!==void 0?r(console,"log"):e}function c(v,w){for(var S=0;S<s.length;S++){var E=s[S];this[E]=S<v?e:this.methodFactory(E,v,w)}this.log=this.debug}function u(v,w,S){return function(){typeof console!==t&&(c.call(this,w,S),this[v].apply(this,arguments))}}function l(v,w,S){return a(v)||u.apply(this,arguments)}function h(v,w,S){var E=this,J;w=w??"WARN";var K="loglevel";typeof v=="string"?K+=":"+v:typeof v=="symbol"&&(K=void 0);function me(M){var H=(s[M]||"silent").toUpperCase();if(!(typeof window===t||!K)){try{window.localStorage[K]=H;return}catch{}try{window.document.cookie=encodeURIComponent(K)+"="+H+";"}catch{}}}function de(){var M;if(!(typeof window===t||!K)){try{M=window.localStorage[K]}catch{}if(typeof M===t)try{var H=window.document.cookie,Et=H.indexOf(encodeURIComponent(K)+"=");Et!==-1&&(M=/^([^;]+)/.exec(H.slice(Et))[1])}catch{}return E.levels[M]===void 0&&(M=void 0),M}}function U(){if(!(typeof window===t||!K)){try{window.localStorage.removeItem(K);return}catch{}try{window.document.cookie=encodeURIComponent(K)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}E.name=v,E.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},E.methodFactory=S||l,E.getLevel=function(){return J},E.setLevel=function(M,H){if(typeof M=="string"&&E.levels[M.toUpperCase()]!==void 0&&(M=E.levels[M.toUpperCase()]),typeof M=="number"&&M>=0&&M<=E.levels.SILENT){if(J=M,H!==!1&&me(M),c.call(E,M,v),typeof console===t&&M<E.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+M},E.setDefaultLevel=function(M){w=M,de()||E.setLevel(M,!1)},E.resetLevel=function(){E.setLevel(w,!1),U()},E.enableAll=function(M){E.setLevel(E.levels.TRACE,M)},E.disableAll=function(M){E.setLevel(E.levels.SILENT,M)};var ee=de();ee==null&&(ee=w),E.setLevel(ee,!1)}var f=new h,p={};f.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var S=p[w];return S||(S=p[w]=new h(w,f.getLevel(),f.methodFactory)),S};var y=typeof window!==t?window.log:void 0;return f.noConflict=function(){return typeof window!==t&&window.log===f&&(window.log=y),f},f.getLoggers=function(){return p},f.default=f,f})})(zo);var dr=zo.exports,Ms;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Ms||(Ms={}));var St;(function(i){i.Default="livekit",i.Room="livekit-room",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(St||(St={}));let $=dr.getLogger("livekit");$.setDefaultLevel(Ms.info);function ai(i){const e=dr.getLogger(i);return e.setDefaultLevel($.getLevel()),e}dr.getLogger("lk-e2ee");function xe(i,e){if(!i)throw new Error(e)}const hl=34028234663852886e22,fl=-34028234663852886e22,pl=4294967295,ml=2147483647,gl=-2147483648;function Jn(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>ml||i<gl)throw new Error("invalid int 32: "+i)}function Ds(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>pl||i<0)throw new Error("invalid uint 32: "+i)}function Go(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>hl||i<fl))throw new Error("invalid float 32: "+i)}const Wo=Symbol("@bufbuild/protobuf/enum-type");function vl(i){const e=i[Wo];return xe(e,"missing enum type on enum object"),e}function Ko(i,e,t,n){i[Wo]=Yo(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Yo(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=Xo(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function yl(i,e,t){const n={};for(const s of e){const r=Xo(s);n[r.localName]=r.no,n[r.no]=r.localName}return Ko(n,i,e),n}function Xo(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class x{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,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 bl(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new x),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function kl(i,e,t,n){return{syntax:i,json:e,bin:t,util:n,makeMessageType(s,r,o){return bl(this,s,r,o)},makeEnum:yl,makeEnumType:Yo,getEnumType:vl}}var k;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(k||(k={}));var wi;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(wi||(wi={}));function Cl(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function gs(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Vn=4294967296;function Mr(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Vn&&(s=s+(n/Vn|0),n=n%Vn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Zo(n,s):hr(n,s)}function Tl(i,e){let t=hr(i,e);const n=t.hi&2147483648;n&&(t=Zo(t.lo,t.hi));const s=Qo(t.lo,t.hi);return n?"-"+s:s}function Qo(i,e){if({lo:i,hi:e}=Sl(i,e),e<=2097151)return String(Vn*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Dr(o)+Dr(r)}function Sl(i,e){return{lo:i>>>0,hi:e>>>0}}function hr(i,e){return{lo:i|0,hi:e|0}}function Zo(i,e){return e=~e,i?i=~i+1:e+=1,hr(i,e)}const Dr=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Lr(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function wl(){let i=this.buf[this.pos++],e=i&127;if(!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,!(i&128))return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;i&128&&t<10;t++)i=this.buf[this.pos++];if(i&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function El(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const u=typeof c=="bigint"?c:BigInt(c);if(u>r||u<s)throw new Error("int64 invalid: ".concat(c));return u},uParse(c){const u=typeof c=="bigint"?c:BigInt(c);if(u>a||u<o)throw new Error("uint64 invalid: ".concat(c));return u},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,u){return i.setInt32(0,c,!0),i.setInt32(4,u,!0),i.getBigInt64(0,!0)},uDec(c,u){return i.setInt32(0,c,!0),i.setInt32(4,u,!0),i.getBigUint64(0,!0)}}}const t=s=>xe(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>xe(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Mr(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Mr(s)},dec(s,r){return Tl(s,r)},uDec(s,r){return Qo(s,r)}}}const F=El();var ae;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(ae||(ae={}));class Pl{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].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(Ds(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Jn(e),Lr(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){Go(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){Ds(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Jn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Jn(e),e=(e<<1^e>>31)>>>0,Lr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=F.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=F.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=F.enc(e);return gs(t.lo,t.hi,this.buf),this}sint64(e){let t=F.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return gs(s,r,this.buf),this}uint64(e){let t=F.uEnc(e);return gs(t.lo,t.hi,this.buf),this}}class _l{constructor(e,t){this.varint64=Cl,this.uint32=wl,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,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case ae.Varint:for(;this.buf[this.pos++]&128;);break;case ae.Bit64:this.pos+=4;case ae.Bit32:this.pos+=4;break;case ae.LengthDelimited:let n=this.uint32();this.pos+=n;break;case ae.StartGroup:let s;for(;(s=this.tag()[1])!==ae.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,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 F.dec(...this.varint64())}uint64(){return F.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,F.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return F.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return F.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 Ls(i,e){return e instanceof x||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;function di(i,e,t){if(e===t)return!0;if(i==k.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==t}return!1}function Us(i,e){switch(i){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==0?F.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function ea(i,e){const t=e===void 0;let n=ae.Varint,s=e===0;switch(i){case k.STRING:s=t||!e.length,n=ae.LengthDelimited;break;case k.BOOL:s=e===!1;break;case k.DOUBLE:n=ae.Bit64;break;case k.FLOAT:n=ae.Bit32;break;case k.INT64:s=t||e==0;break;case k.UINT64:s=t||e==0;break;case k.FIXED64:s=t||e==0,n=ae.Bit64;break;case k.BYTES:s=t||!e.byteLength,n=ae.LengthDelimited;break;case k.FIXED32:n=ae.Bit32;break;case k.SFIXED32:n=ae.Bit32;break;case k.SFIXED64:s=t||e==0,n=ae.Bit64;break;case k.SINT64:s=t||e==0;break}const r=k[i].toLowerCase();return[n,r,t||s]}const Di=Symbol("@bufbuild/protobuf/unknown-fields"),Ur={readUnknownFields:!0,readerFactory:i=>new _l(i)},Fr={writeUnknownFields:!0,writerFactory:()=>new Pl};function Rl(i){return i?Object.assign(Object.assign({},Ur),i):Ur}function Ol(i){return i?Object.assign(Object.assign({},Fr),i):Fr}function xl(){return{makeReadOptions:Rl,makeWriteOptions:Ol,listUnknownFields(i){var e;return(e=i[Di])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Di]},writeUnknownFields(i,e){const n=i[Di];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Di])||(s[Di]=[]),s[Di].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n){const s=i.getType(),r=t===void 0?e.len:e.pos+t;for(;e.pos<r;){const[o,a]=e.tag(),c=s.fields.find(o);if(!c){const f=e.skip(a);n.readUnknownFields&&this.onUnknownField(i,o,a,f);continue}let u=i,l=c.repeated,h=c.localName;switch(c.oneof&&(u=u[c.oneof.localName],u.case!=h&&delete u.value,u.case=h,h="value"),c.kind){case"scalar":case"enum":const f=c.kind=="enum"?k.INT32:c.T;let p=es;if(c.kind=="scalar"&&c.L>0&&(p=Nl),l){let S=u[h];if(a==ae.LengthDelimited&&f!=k.STRING&&f!=k.BYTES){let E=e.uint32()+e.pos;for(;e.pos<E;)S.push(p(e,f))}else S.push(p(e,f))}else u[h]=p(e,f);break;case"message":const y=c.T;l?u[h].push(qn(e,new y,n)):u[h]instanceof x?qn(e,u[h],n):(u[h]=qn(e,new y,n),y.fieldWrapper&&!c.oneof&&!c.repeated&&(u[h]=y.fieldWrapper.unwrapField(u[h])));break;case"map":let[v,w]=Il(c,e,n);u[h][v]=w;break}}}}}function qn(i,e,t){return e.getType().runtime.bin.readMessage(e,i,i.uint32(),t),e}function Il(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){let[a]=e.tag();switch(a){case 1:r=es(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=es(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=qn(e,new i.V.T,t);break}break}}if(r===void 0){let a=Us(i.K,wi.BIGINT);r=i.K==k.BOOL?a.toString():a}if(typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Us(i.V.T,wi.BIGINT);break;case"enum":o=0;break;case"message":o=new i.V.T;break}return[r,o]}function Nl(i,e){const t=es(i,e);return typeof t=="bigint"?t.toString():t}function es(i,e){switch(e){case k.STRING:return i.string();case k.BOOL:return i.bool();case k.DOUBLE:return i.double();case k.FLOAT:return i.float();case k.INT32:return i.int32();case k.INT64:return i.int64();case k.UINT64:return i.uint64();case k.FIXED64:return i.fixed64();case k.BYTES:return i.bytes();case k.FIXED32:return i.fixed32();case k.SFIXED32:return i.sfixed32();case k.SFIXED64:return i.sfixed64();case k.SINT64:return i.sint64();case k.UINT32:return i.uint32();case k.SINT32:return i.sint32()}}function Al(i,e,t,n,s){i.tag(t.no,ae.LengthDelimited),i.fork();let r=n;switch(t.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:r=Number.parseInt(n);break;case k.BOOL:xe(n=="true"||n=="false"),r=n=="true";break}switch(mn(i,t.K,1,r,!0),t.V.kind){case"scalar":mn(i,t.V.T,2,s,!0);break;case"enum":mn(i,k.INT32,2,s,!0);break;case"message":Fs(i,e,t.V.T,2,s);break}i.join()}function Fs(i,e,t,n,s){if(s!==void 0){const r=Ls(t,s);i.tag(n,ae.LengthDelimited).bytes(r.toBinary(e))}}function mn(i,e,t,n,s){let[r,o,a]=ea(e,n);(!a||s)&&i.tag(t,r)[o](n)}function Ml(i,e,t,n){if(!n.length)return;i.tag(t,ae.LengthDelimited).fork();let[,s]=ea(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Dl(){return Object.assign(Object.assign({},xl()),{writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){let r,o=s.repeated,a=s.localName;if(s.oneof){const c=i[s.oneof.localName];if(c.case!==a)continue;r=c.value}else r=i[a];switch(s.kind){case"scalar":case"enum":let c=s.kind=="enum"?k.INT32:s.T;if(o)if(s.packed)Ml(e,c,s.no,r);else for(const u of r)mn(e,c,s.no,u,!0);else r!==void 0&&mn(e,c,s.no,r,!!s.oneof||s.opt);break;case"message":if(o)for(const u of r)Fs(e,t,s.T,s.no,u);else Fs(e,t,s.T,s.no,r);break;case"map":for(const[u,l]of Object.entries(r))Al(e,t,s,u,l);break}}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e}})}let It="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),cs=[];for(let i=0;i<It.length;i++)cs[It[i].charCodeAt(0)]=i;cs[45]=It.indexOf("+");cs[95]=It.indexOf("/");const ta={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=cs[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
|
|
18
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=It[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=It[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=It[s|n>>6],e+=It[n&63],t=0;break}return t&&(e+=It[s],e+="=",t==1&&(e+="=")),e}},jr={ignoreUnknownFields:!1},Br={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ll(i){return i?Object.assign(Object.assign({},jr),i):jr}function Ul(i){return i?Object.assign(Object.assign({},Br),i):Br}function Fl(i){const e=i(jl,Jr);return{makeReadOptions:Ll,makeWriteOptions:Ul,readMessage(t,n,s,r){if(n==null||Array.isArray(n)||typeof n!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(this.debug(n)));r=r??new t;const o={};for(const[a,c]of Object.entries(n)){const u=t.fields.findJsonName(a);if(!u){if(!s.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(a,'" is unknown'));continue}let l=u.localName,h=r;if(u.oneof){if(c===null&&u.kind=="scalar")continue;const f=o[u.oneof.localName];if(f)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(u.oneof.name,'" present: "').concat(f,'", "').concat(a,'"'));o[u.oneof.localName]=a,h=h[u.oneof.localName]={case:l},l="value"}if(u.repeated){if(c===null)continue;if(!Array.isArray(c))throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c)));const f=h[l];for(const p of c){if(p===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(p)));let y;switch(u.kind){case"message":y=u.T.fromJson(p,s);break;case"enum":if(y=vs(u.T,p,s.ignoreUnknownFields),y===void 0)continue;break;case"scalar":try{y=en(u.T,p,u.L)}catch(v){let w="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(p));throw v instanceof Error&&v.message.length>0&&(w+=": ".concat(v.message)),new Error(w)}break}f.push(y)}}else if(u.kind=="map"){if(c===null)continue;if(Array.isArray(c)||typeof c!="object")throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c)));const f=h[l];for(const[p,y]of Object.entries(c)){if(y===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: map value null"));let v;switch(u.V.kind){case"message":v=u.V.T.fromJson(y,s);break;case"enum":if(v=vs(u.V.T,y,s.ignoreUnknownFields),v===void 0)continue;break;case"scalar":try{v=en(u.V.T,y,wi.BIGINT)}catch(w){let S="cannot decode map value for field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw w instanceof Error&&w.message.length>0&&(S+=": ".concat(w.message)),new Error(S)}break}try{f[en(u.K,u.K==k.BOOL?p=="true"?!0:p=="false"?!1:p:p,wi.BIGINT).toString()]=v}catch(w){let S="cannot decode map key for field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw w instanceof Error&&w.message.length>0&&(S+=": ".concat(w.message)),new Error(S)}}}else switch(u.kind){case"message":const f=u.T;if(c===null&&f.typeName!="google.protobuf.Value"){if(u.oneof)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name,' from JSON: null is invalid for oneof field "').concat(a,'"'));continue}h[l]instanceof x?h[l].fromJson(c,s):(h[l]=f.fromJson(c,s),f.fieldWrapper&&!u.oneof&&(h[l]=f.fieldWrapper.unwrapField(h[l])));break;case"enum":const p=vs(u.T,c,s.ignoreUnknownFields);p!==void 0&&(h[l]=p);break;case"scalar":try{h[l]=en(u.T,c,u.L)}catch(y){let v="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw y instanceof Error&&y.message.length>0&&(v+=": ".concat(y.message)),new Error(v)}break}}return r},writeMessage(t,n){const s=t.getType(),r={};let o;try{for(const a of s.fields.byMember()){let c;if(a.kind=="oneof"){const u=t[a.localName];if(u.value===void 0)continue;if(o=a.findField(u.case),!o)throw"oneof case not found: "+u.case;c=e(o,u.value,n)}else o=a,c=e(o,t[o.localName],n);c!==void 0&&(r[n.useProtoFieldName?o.name:o.jsonName]=c)}}catch(a){const c=o?"cannot encode field ".concat(s.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(s.typeName," to JSON"),u=a instanceof Error?a.message:String(a);throw new Error(c+(u.length>0?": ".concat(u):""))}return r},readScalar:en,writeScalar:Jr,debug:ia}}function ia(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function en(i,e,t){switch(i){case k.DOUBLE:case k.FLOAT:if(e===null)return 0;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 n=Number(e);if(Number.isNaN(n)||!Number.isFinite(n))break;return i==k.FLOAT&&Go(n),n;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(e===null)return 0;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 i==k.UINT32?Ds(s):Jn(s),s;case k.INT64:case k.SFIXED64:case k.SINT64:if(e===null)return F.zero;if(typeof e!="number"&&typeof e!="string")break;const r=F.parse(e);return t?r.toString():r;case k.FIXED64:case k.UINT64:if(e===null)return F.zero;if(typeof e!="number"&&typeof e!="string")break;const o=F.uParse(e);return t?o.toString():o;case k.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case k.STRING:if(e===null)return"";if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case k.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return ta.dec(e)}throw new Error}function vs(i,e,t){if(e===null)return 0;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const n=i.findName(e);if(n||t)return n==null?void 0:n.no;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(ia(e)))}function jl(i,e,t,n){var s;if(e===void 0)return e;if(e===0&&!t)return;if(n)return e;if(i.typeName=="google.protobuf.NullValue")return null;const r=i.findNumber(e);return(s=r==null?void 0:r.name)!==null&&s!==void 0?s:e}function Jr(i,e,t){if(e!==void 0)switch(i){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return xe(typeof e=="number"),e!=0||t?e:void 0;case k.FLOAT:case k.DOUBLE:return xe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e!==0||t?e:void 0;case k.STRING:return xe(typeof e=="string"),e.length>0||t?e:void 0;case k.BOOL:return xe(typeof e=="boolean"),e||t?e:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return xe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case k.BYTES:return xe(e instanceof Uint8Array),t||e.byteLength>0?ta.enc(e):void 0}}function Bl(){return Fl((i,e)=>function(n,s,r){if(n.kind=="map"){const o={};switch(n.V.kind){case"scalar":for(const[c,u]of Object.entries(s)){const l=e(n.V.T,u,!0);xe(l!==void 0),o[c.toString()]=l}break;case"message":for(const[c,u]of Object.entries(s))o[c.toString()]=u.toJson(r);break;case"enum":const a=n.V.T;for(const[c,u]of Object.entries(s)){xe(u===void 0||typeof u=="number");const l=i(a,u,!0,r.enumAsInteger);xe(l!==void 0),o[c.toString()]=l}break}return r.emitDefaultValues||Object.keys(o).length>0?o:void 0}else if(n.repeated){const o=[];switch(n.kind){case"scalar":for(let a=0;a<s.length;a++)o.push(e(n.T,s[a],!0));break;case"enum":for(let a=0;a<s.length;a++)o.push(i(n.T,s[a],!0,r.enumAsInteger));break;case"message":for(let a=0;a<s.length;a++)o.push(Ls(n.T,s[a]).toJson(r));break}return r.emitDefaultValues||o.length>0?o:void 0}else switch(n.kind){case"scalar":return e(n.T,s,!!n.oneof||n.opt||r.emitDefaultValues);case"enum":return i(n.T,s,!!n.oneof||n.opt||r.emitDefaultValues,r.enumAsInteger);case"message":return s!==void 0?Ls(n.T,s).toJson(r):void 0}})}function Jl(){return{setEnumType:Ko,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!==void 0)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let u=o[s].value;c&&c.kind=="message"&&!(u instanceof c.T)?u=new c.T(u):c&&c.kind==="scalar"&&c.T===k.BYTES&&(u=tn(u)),r[s]={case:a,value:u};break;case"scalar":case"enum":let l=o[s];n.T===k.BYTES&&(l=n.repeated?l.map(tn):tn(l)),r[s]=l;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===k.BYTES)for(const[p,y]of Object.entries(o[s]))r[s][p]=tn(y);else Object.assign(r[s],o[s]);break;case"message":const f=n.V.T;for(const p of Object.keys(o[s])){let y=o[s][p];f.fieldWrapper||(y=new f(y)),r[s][p]=y}break}break;case"message":const h=n.T;if(n.repeated)r[s]=o[s].map(f=>f instanceof h?f:new h(f));else if(o[s]!==void 0){const f=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?r[s]=tn(f):r[s]=f:r[s]=f instanceof h?f:new h(f)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>di(n.T,o,r[a]));case"enum":return s.every((o,a)=>di(k.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(s,r);case"enum":return di(k.INT32,s,r);case"scalar":return di(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const o=n.findField(s.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(s.value,r.value);case"enum":return di(k.INT32,s.value,r.value);case"scalar":return di(o.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const a=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const c=n.V.T;return a.every(l=>c.equals(s[l],r[l]));case"enum":return a.every(l=>di(k.INT32,s[l],r[l]));case"scalar":const u=n.V.T;return a.every(l=>di(u,s[l],r[l]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Un);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Un(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Un(r.value)}:{case:void 0}:o=Un(r);n[s.localName]=o}return t}}}function Un(i){if(i===void 0)return i;if(i instanceof x)return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function tn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}class Vl{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function na(i,e){const t=sa(i);return e?t:Wl(Gl(t))}function ql(i){return na(i,!1)}const $l=sa;function sa(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){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(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Hl=new Set(["constructor","toString","toJSON","valueOf"]),zl=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ra=i=>"".concat(i,"$"),Gl=i=>zl.has(i)?ra(i):i,Wl=i=>Hl.has(i)?ra(i):i;class Kl{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ql(e)}addField(e){xe(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]}}const d=kl("proto3",Bl(),Dl(),Object.assign(Object.assign({},Jl()),{newFieldList(i){return new Vl(i,Yl)},initFields(i){for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Us(e.T,e.L);break}}}}));function Yl(i){var e,t,n,s;const r=[];let o;for(const a of typeof i=="function"?i():i){const c=a;if(c.localName=na(a.name,a.oneof!==void 0),c.jsonName=(e=a.jsonName)!==null&&e!==void 0?e:$l(a.name),c.repeated=(t=a.repeated)!==null&&t!==void 0?t:!1,a.kind=="scalar"&&(c.L=(n=a.L)!==null&&n!==void 0?n:wi.BIGINT),c.packed=(s=a.packed)!==null&&s!==void 0?s:a.kind=="enum"||a.kind=="scalar"&&a.T!=k.BYTES&&a.T!=k.STRING,a.oneof!==void 0){const u=typeof a.oneof=="string"?a.oneof:a.oneof.name;(!o||o.name!=u)&&(o=new Kl(u)),c.oneof=o,o.addField(c)}r.push(c)}return r}class ye extends x{constructor(e){super(),this.seconds=F.zero,this.nanos=0,d.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(d.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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=F.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[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 n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ye.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ye({seconds:F.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ye().fromBinary(e,t)}static fromJson(e,t){return new ye().fromJson(e,t)}static fromJsonString(e,t){return new ye().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ye,e,t)}}ye.runtime=d;ye.typeName="google.protobuf.Timestamp";ye.fields=d.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var js;(function(i){i[i.DEFAULT_AC=0]="DEFAULT_AC",i[i.OPUS=1]="OPUS",i[i.AAC=2]="AAC"})(js||(js={}));d.util.setEnumType(js,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]);var Bs;(function(i){i[i.DEFAULT_VC=0]="DEFAULT_VC",i[i.H264_BASELINE=1]="H264_BASELINE",i[i.H264_MAIN=2]="H264_MAIN",i[i.H264_HIGH=3]="H264_HIGH",i[i.VP8=4]="VP8"})(Bs||(Bs={}));d.util.setEnumType(Bs,"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"}]);var Js;(function(i){i[i.IC_DEFAULT=0]="IC_DEFAULT",i[i.IC_JPEG=1]="IC_JPEG"})(Js||(Js={}));d.util.setEnumType(Js,"livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]);var Se;(function(i){i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.DATA=2]="DATA"})(Se||(Se={}));d.util.setEnumType(Se,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]);var ce;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.CAMERA=1]="CAMERA",i[i.MICROPHONE=2]="MICROPHONE",i[i.SCREEN_SHARE=3]="SCREEN_SHARE",i[i.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO"})(ce||(ce={}));d.util.setEnumType(ce,"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"}]);var ci;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH",i[i.OFF=3]="OFF"})(ci||(ci={}));d.util.setEnumType(ci,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]);var Nt;(function(i){i[i.POOR=0]="POOR",i[i.GOOD=1]="GOOD",i[i.EXCELLENT=2]="EXCELLENT",i[i.LOST=3]="LOST"})(Nt||(Nt={}));d.util.setEnumType(Nt,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]);var et;(function(i){i[i.UNSET=0]="UNSET",i[i.DISABLED=1]="DISABLED",i[i.ENABLED=2]="ENABLED"})(et||(et={}));d.util.setEnumType(et,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]);var si;(function(i){i[i.UNKNOWN_REASON=0]="UNKNOWN_REASON",i[i.CLIENT_INITIATED=1]="CLIENT_INITIATED",i[i.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",i[i.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",i[i.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",i[i.ROOM_DELETED=5]="ROOM_DELETED",i[i.STATE_MISMATCH=6]="STATE_MISMATCH",i[i.JOIN_FAILURE=7]="JOIN_FAILURE",i[i.MIGRATION=8]="MIGRATION",i[i.SIGNAL_CLOSE=9]="SIGNAL_CLOSE"})(si||(si={}));d.util.setEnumType(si,"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"}]);var Ot;(function(i){i[i.RR_UNKNOWN=0]="RR_UNKNOWN",i[i.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",i[i.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",i[i.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",i[i.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE"})(Ot||(Ot={}));d.util.setEnumType(Ot,"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"}]);var wn;(function(i){i[i.SE_UNKNOWN=0]="SE_UNKNOWN",i[i.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",i[i.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND"})(wn||(wn={}));d.util.setEnumType(wn,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let Ki=class un extends x{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=F.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new un().fromBinary(e,t)}static fromJson(e,t){return new un().fromJson(e,t)}static fromJsonString(e,t){return new un().fromJsonString(e,t)}static equals(e,t){return d.util.equals(un,e,t)}};Ki.runtime=d;Ki.typeName="livekit.Room";Ki.fields=d.util.newFieldList(()=>[{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:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ze,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:ht}]);class ze extends x{constructor(e){super(),this.mime="",this.fmtpLine="",d.util.initPartial(e,this)}static fromBinary(e,t){return new ze().fromBinary(e,t)}static fromJson(e,t){return new ze().fromJson(e,t)}static fromJsonString(e,t){return new ze().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ze,e,t)}}ze.runtime=d;ze.typeName="livekit.Codec";ze.fields=d.util.newFieldList(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);class pi extends x{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new pi().fromBinary(e,t)}static fromJson(e,t){return new pi().fromJson(e,t)}static fromJsonString(e,t){return new pi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(pi,e,t)}}pi.runtime=d;pi.typeName="livekit.PlayoutDelay";pi.fields=d.util.newFieldList(()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]);class At extends x{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,this.agent=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new At().fromBinary(e,t)}static fromJson(e,t){return new At().fromJson(e,t)}static fromJsonString(e,t){return new At().fromJsonString(e,t)}static equals(e,t){return d.util.equals(At,e,t)}}At.runtime=d;At.typeName="livekit.ParticipantPermission";At.fields=d.util.newFieldList(()=>[{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:d.getEnumType(ce),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}]);class Le extends x{constructor(e){super(),this.sid="",this.identity="",this.state=Ei.JOINING,this.tracks=[],this.metadata="",this.joinedAt=F.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,this.kind=En.STANDARD,d.util.initPartial(e,this)}static fromBinary(e,t){return new Le().fromBinary(e,t)}static fromJson(e,t){return new Le().fromJson(e,t)}static fromJsonString(e,t){return new Le().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Le,e,t)}}Le.runtime=d;Le.typeName="livekit.ParticipantInfo";Le.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:d.getEnumType(Ei)},{no:4,name:"tracks",kind:"message",T:Ie,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",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:At},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:d.getEnumType(En)}]);var Ei;(function(i){i[i.JOINING=0]="JOINING",i[i.JOINED=1]="JOINED",i[i.ACTIVE=2]="ACTIVE",i[i.DISCONNECTED=3]="DISCONNECTED"})(Ei||(Ei={}));d.util.setEnumType(Ei,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);var En;(function(i){i[i.STANDARD=0]="STANDARD",i[i.INGRESS=1]="INGRESS",i[i.EGRESS=2]="EGRESS",i[i.SIP=3]="SIP",i[i.AGENT=4]="AGENT"})(En||(En={}));d.util.setEnumType(En,"livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]);class mi extends x{constructor(e){super(),d.util.initPartial(e,this)}static fromBinary(e,t){return new mi().fromBinary(e,t)}static fromJson(e,t){return new mi().fromJson(e,t)}static fromJsonString(e,t){return new mi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(mi,e,t)}}mi.runtime=d;mi.typeName="livekit.Encryption";mi.fields=d.util.newFieldList(()=>[]);var Ce;(function(i){i[i.NONE=0]="NONE",i[i.GCM=1]="GCM",i[i.CUSTOM=2]="CUSTOM"})(Ce||(Ce={}));d.util.setEnumType(Ce,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class Mt extends x{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Mt().fromBinary(e,t)}static fromJson(e,t){return new Mt().fromJson(e,t)}static fromJsonString(e,t){return new Mt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Mt,e,t)}}Mt.runtime=d;Mt.typeName="livekit.SimulcastCodecInfo";Mt.fields=d.util.newFieldList(()=>[{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:_e,repeated:!0}]);class Ie extends x{constructor(e){super(),this.sid="",this.type=Se.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=ce.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=Ce.NONE,this.stream="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ie().fromBinary(e,t)}static fromJson(e,t){return new Ie().fromJson(e,t)}static fromJsonString(e,t){return new Ie().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ie,e,t)}}Ie.runtime=d;Ie.typeName="livekit.TrackInfo";Ie.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:d.getEnumType(Se)},{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:d.getEnumType(ce)},{no:10,name:"layers",kind:"message",T:_e,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:Mt,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:d.getEnumType(Ce)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ht}]);class _e extends x{constructor(e){super(),this.quality=ci.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new _e().fromBinary(e,t)}static fromJson(e,t){return new _e().fromJson(e,t)}static fromJsonString(e,t){return new _e().fromJsonString(e,t)}static equals(e,t){return d.util.equals(_e,e,t)}}_e.runtime=d;_e.typeName="livekit.VideoLayer";_e.fields=d.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:d.getEnumType(ci)},{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}]);class rt extends x{constructor(e){super(),this.kind=fe.RELIABLE,this.value={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new rt().fromBinary(e,t)}static fromJson(e,t){return new rt().fromJson(e,t)}static fromJsonString(e,t){return new rt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(rt,e,t)}}rt.runtime=d;rt.typeName="livekit.DataPacket";rt.fields=d.util.newFieldList(()=>[{no:1,name:"kind",kind:"enum",T:d.getEnumType(fe)},{no:2,name:"user",kind:"message",T:at,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Dt,oneof:"value"}]);var fe;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY"})(fe||(fe={}));d.util.setEnumType(fe,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class Dt extends x{constructor(e){super(),this.speakers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Dt().fromBinary(e,t)}static fromJson(e,t){return new Dt().fromJson(e,t)}static fromJsonString(e,t){return new Dt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Dt,e,t)}}Dt.runtime=d;Dt.typeName="livekit.ActiveSpeakerUpdate";Dt.fields=d.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:ot,repeated:!0}]);class ot extends x{constructor(e){super(),this.sid="",this.level=0,this.active=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new ot().fromBinary(e,t)}static fromJson(e,t){return new ot().fromJson(e,t)}static fromJsonString(e,t){return new ot().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ot,e,t)}}ot.runtime=d;ot.typeName="livekit.SpeakerInfo";ot.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]);class at extends x{constructor(e){super(),this.participantSid="",this.participantIdentity="",this.payload=new Uint8Array(0),this.destinationSids=[],this.destinationIdentities=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new at().fromBinary(e,t)}static fromJson(e,t){return new at().fromJson(e,t)}static fromJsonString(e,t){return new at().fromJsonString(e,t)}static equals(e,t){return d.util.equals(at,e,t)}}at.runtime=d;at.typeName="livekit.UserPacket";at.fields=d.util.newFieldList(()=>[{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}]);class ct extends x{constructor(e){super(),this.participantSid="",this.trackSids=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new ct().fromBinary(e,t)}static fromJson(e,t){return new ct().fromJson(e,t)}static fromJsonString(e,t){return new ct().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ct,e,t)}}ct.runtime=d;ct.typeName="livekit.ParticipantTracks";ct.fields=d.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]);class Lt extends x{constructor(e){super(),this.edition=zi.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Lt().fromBinary(e,t)}static fromJson(e,t){return new Lt().fromJson(e,t)}static fromJsonString(e,t){return new Lt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Lt,e,t)}}Lt.runtime=d;Lt.typeName="livekit.ServerInfo";Lt.fields=d.util.newFieldList(()=>[{no:1,name:"edition",kind:"enum",T:d.getEnumType(zi)},{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}]);var zi;(function(i){i[i.Standard=0]="Standard",i[i.Cloud=1]="Cloud"})(zi||(zi={}));d.util.setEnumType(zi,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class Ut extends x{constructor(e){super(),this.sdk=Gi.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ut().fromBinary(e,t)}static fromJson(e,t){return new Ut().fromJson(e,t)}static fromJsonString(e,t){return new Ut().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ut,e,t)}}Ut.runtime=d;Ut.typeName="livekit.ClientInfo";Ut.fields=d.util.newFieldList(()=>[{no:1,name:"sdk",kind:"enum",T:d.getEnumType(Gi)},{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}]);var Gi;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.JS=1]="JS",i[i.SWIFT=2]="SWIFT",i[i.ANDROID=3]="ANDROID",i[i.FLUTTER=4]="FLUTTER",i[i.GO=5]="GO",i[i.UNITY=6]="UNITY",i[i.REACT_NATIVE=7]="REACT_NATIVE",i[i.RUST=8]="RUST",i[i.PYTHON=9]="PYTHON",i[i.CPP=10]="CPP"})(Gi||(Gi={}));d.util.setEnumType(Gi,"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"}]);class ut extends x{constructor(e){super(),this.resumeConnection=et.UNSET,this.forceRelay=et.UNSET,d.util.initPartial(e,this)}static fromBinary(e,t){return new ut().fromBinary(e,t)}static fromJson(e,t){return new ut().fromJson(e,t)}static fromJsonString(e,t){return new ut().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ut,e,t)}}ut.runtime=d;ut.typeName="livekit.ClientConfiguration";ut.fields=d.util.newFieldList(()=>[{no:1,name:"video",kind:"message",T:lt},{no:2,name:"screen",kind:"message",T:lt},{no:3,name:"resume_connection",kind:"enum",T:d.getEnumType(et)},{no:4,name:"disabled_codecs",kind:"message",T:Ft},{no:5,name:"force_relay",kind:"enum",T:d.getEnumType(et)}]);class lt extends x{constructor(e){super(),this.hardwareEncoder=et.UNSET,d.util.initPartial(e,this)}static fromBinary(e,t){return new lt().fromBinary(e,t)}static fromJson(e,t){return new lt().fromJson(e,t)}static fromJsonString(e,t){return new lt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(lt,e,t)}}lt.runtime=d;lt.typeName="livekit.VideoConfiguration";lt.fields=d.util.newFieldList(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:d.getEnumType(et)}]);class Ft extends x{constructor(e){super(),this.codecs=[],this.publish=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Ft().fromBinary(e,t)}static fromJson(e,t){return new Ft().fromJson(e,t)}static fromJsonString(e,t){return new Ft().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ft,e,t)}}Ft.runtime=d;Ft.typeName="livekit.DisabledCodecs";Ft.fields=d.util.newFieldList(()=>[{no:1,name:"codecs",kind:"message",T:ze,repeated:!0},{no:2,name:"publish",kind:"message",T:ze,repeated:!0}]);class dt extends x{constructor(e){super(),this.duration=0,this.startTimestamp=F.zero,this.endTimestamp=F.zero,this.rtpClockTicks=F.zero,this.driftSamples=F.zero,this.driftMs=0,this.clockRate=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new dt().fromBinary(e,t)}static fromJson(e,t){return new dt().fromJson(e,t)}static fromJsonString(e,t){return new dt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(dt,e,t)}}dt.runtime=d;dt.typeName="livekit.RTPDrift";dt.fields=d.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:ye},{no:2,name:"end_time",kind:"message",T:ye},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]);class gi extends x{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=F.zero,this.headerBytes=F.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=F.zero,this.headerBytesDuplicate=F.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=F.zero,this.headerBytesPadding=F.zero,this.bitratePadding=0,this.packetsOutOfOrder=0,this.frames=0,this.frameRate=0,this.jitterCurrent=0,this.jitterMax=0,this.gapHistogram={},this.nacks=0,this.nackAcks=0,this.nackMisses=0,this.nackRepeated=0,this.plis=0,this.firs=0,this.rttCurrent=0,this.rttMax=0,this.keyFrames=0,this.layerLockPlis=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new gi().fromBinary(e,t)}static fromJson(e,t){return new gi().fromJson(e,t)}static fromJsonString(e,t){return new gi().fromJsonString(e,t)}static equals(e,t){return d.util.equals(gi,e,t)}}gi.runtime=d;gi.typeName="livekit.RTPStats";gi.fields=d.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:ye},{no:2,name:"end_time",kind:"message",T:ye},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:ye},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:ye},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:ye},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:ye},{no:44,name:"packet_drift",kind:"message",T:dt},{no:45,name:"report_drift",kind:"message",T:dt}]);class ht extends x{constructor(e){super(),this.unixMicro=F.zero,this.ticks=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new ht().fromBinary(e,t)}static fromJson(e,t){return new ht().fromJson(e,t)}static fromJsonString(e,t){return new ht().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ht,e,t)}}ht.runtime=d;ht.typeName="livekit.TimedVersion";ht.fields=d.util.newFieldList(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]);const nn=7e3,Xl=[0,300,2*2*300,3*3*300,4*4*300,nn,nn,nn,nn,nn];class Ql{constructor(e){this._retryDelays=e!==void 0?[...e]:Xl}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 m(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?r(l.value):s(l.value).then(a,c)}u((n=n.apply(i,e||[])).next())})}function Vr(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Fi(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Vr=="function"?Vr(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(u){r({value:u,done:a})},o)}}var fr={exports:{}},Ji=typeof Reflect=="object"?Reflect:null,qr=Ji&&typeof Ji.apply=="function"?Ji.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},$n;Ji&&typeof Ji.ownKeys=="function"?$n=Ji.ownKeys:Object.getOwnPropertySymbols?$n=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:$n=function(e){return Object.getOwnPropertyNames(e)};function Zl(i){console&&console.warn&&console.warn(i)}var oa=Number.isNaN||function(e){return e!==e};function Q(){Q.init.call(this)}fr.exports=Q;fr.exports.once=nd;Q.EventEmitter=Q;Q.prototype._events=void 0;Q.prototype._eventsCount=0;Q.prototype._maxListeners=void 0;var $r=10;function us(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(Q,"defaultMaxListeners",{enumerable:!0,get:function(){return $r},set:function(i){if(typeof i!="number"||i<0||oa(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");$r=i}});Q.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};Q.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||oa(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function aa(i){return i._maxListeners===void 0?Q.defaultMaxListeners:i._maxListeners}Q.prototype.getMaxListeners=function(){return aa(this)};Q.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s=e==="error",r=this._events;if(r!==void 0)s=s&&r.error===void 0;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(c===void 0)return!1;if(typeof c=="function")qr(c,this,t);else for(var u=c.length,l=ha(c,u),n=0;n<u;++n)qr(l[n],this,t);return!0};function ca(i,e,t,n){var s,r,o;if(us(t),r=i._events,r===void 0?(r=i._events=Object.create(null),i._eventsCount=0):(r.newListener!==void 0&&(i.emit("newListener",e,t.listener?t.listener:t),r=i._events),o=r[e]),o===void 0)o=r[e]=t,++i._eventsCount;else if(typeof o=="function"?o=r[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),s=aa(i),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=i,a.type=e,a.count=o.length,Zl(a)}return i}Q.prototype.addListener=function(e,t){return ca(this,e,t,!1)};Q.prototype.on=Q.prototype.addListener;Q.prototype.prependListener=function(e,t){return ca(this,e,t,!0)};function ed(){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 ua(i,e,t){var n={fired:!1,wrapFn:void 0,target:i,type:e,listener:t},s=ed.bind(n);return s.listener=t,n.wrapFn=s,s}Q.prototype.once=function(e,t){return us(t),this.on(e,ua(this,e,t)),this};Q.prototype.prependOnceListener=function(e,t){return us(t),this.prependListener(e,ua(this,e,t)),this};Q.prototype.removeListener=function(e,t){var n,s,r,o,a;if(us(t),s=this._events,s===void 0)return this;if(n=s[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(r=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,r=o;break}if(r<0)return this;r===0?n.shift():td(n,r),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};Q.prototype.off=Q.prototype.removeListener;Q.prototype.removeAllListeners=function(e){var t,n,s;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var r=Object.keys(n),o;for(s=0;s<r.length;++s)o=r[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function la(i,e,t){var n=i._events;if(n===void 0)return[];var s=n[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?id(s):ha(s,s.length)}Q.prototype.listeners=function(e){return la(this,e,!0)};Q.prototype.rawListeners=function(e){return la(this,e,!1)};Q.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):da.call(i,e)};Q.prototype.listenerCount=da;function da(i){var e=this._events;if(e!==void 0){var t=e[i];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Q.prototype.eventNames=function(){return this._eventsCount>0?$n(this._events):[]};function ha(i,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=i[n];return t}function td(i,e){for(;e+1<i.length;e++)i[e]=i[e+1];i.pop()}function id(i){for(var e=new Array(i.length),t=0;t<e.length;++t)e[t]=i[t].listener||i[t];return e}function nd(i,e){return new Promise(function(t,n){function s(o){i.removeListener(e,r),n(o)}function r(){typeof i.removeListener=="function"&&i.removeListener("error",s),t([].slice.call(arguments))}fa(i,e,r,{once:!0}),e!=="error"&&sd(i,s,{once:!0})})}function sd(i,e,t){typeof i.on=="function"&&fa(i,"error",e,t)}function fa(i,e,t,n){if(typeof i.on=="function")n.once?i.once(e,t):i.on(e,t);else if(typeof i.addEventListener=="function")i.addEventListener(e,function s(r){n.once&&i.removeEventListener(e,s),t(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof i)}var wt=fr.exports;let pa=!0,ma=!0;function Hn(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function Oi(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=u=>{const l=t(u);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"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 rd(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(pa=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function od(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(ma=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function ga(){if(typeof window=="object"){if(pa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function pr(i,e){ma&&console.warn(i+" is deprecated, please use "+e+" instead.")}function ad(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.mozGetUserMedia)e.browser="firefox",e.version=Hn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=Hn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Hn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Hr(i){return Object.prototype.toString.call(i)==="[object Object]"}function va(i){return Hr(i)?Object.keys(i).reduce(function(e,t){const n=Hr(i[t]),s=n?va(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function Vs(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Vs(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{Vs(i,i.get(s),t)})}))}function zr(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&Vs(i,a,s)})}),s}const Gr=ga;function ya(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(u=>{if(u==="require"||u==="advanced"||u==="mediaSource")return;const l=typeof a[u]=="object"?a[u]:{ideal:a[u]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const h=function(f,p){return f?f+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let f={};typeof l.ideal=="number"?(f[h("min",u)]=l.ideal,c.optional.push(f),f={},f[h("max",u)]=l.ideal,c.optional.push(f)):(f[h("",u)]=l.ideal,c.optional.push(f))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",u)]=l.exact):["min","max"].forEach(f=>{l[f]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(f,u)]=l[f])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const u=function(l,h,f){h in l&&!(f in l)&&(l[f]=l[h],delete l[h])};a=JSON.parse(JSON.stringify(a)),u(a.audio,"autoGainControl","googAutoGainControl"),u(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let u=a.video.facingMode;u=u&&(typeof u=="object"?u:{ideal:u});const l=e.version<66;if(u&&(u.exact==="user"||u.exact==="environment"||u.ideal==="user"||u.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let h;if(u.exact==="environment"||u.ideal==="environment"?h=["back","rear"]:(u.exact==="user"||u.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(f=>{f=f.filter(y=>y.kind==="videoinput");let p=f.find(y=>h.some(v=>y.label.toLowerCase().includes(v)));return!p&&f.length&&h.includes("back")&&(p=f[f.length-1]),p&&(a.video.deviceId=u.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=n(a.video),Gr("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Gr("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,u){s(a,l=>{t.webkitGetUserMedia(l,c,h=>{u&&u(r(h))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,u=>a(u).then(l=>{if(u.audio&&!l.getAudioTracks().length||u.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function cd(i,e){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&i.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(n){return e(n).then(s=>{const r=n.video&&n.video.width,o=n.video&&n.video.height,a=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:a||3}},r&&(n.video.mandatory.maxWidth=r),o&&(n.video.mandatory.maxHeight=o),i.navigator.mediaDevices.getUserMedia(n)})}}}function ba(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function ka(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Oi(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ca(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let u=s.apply(this,arguments);return u||(u=e(this,a),this._senders.push(u)),u};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.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 Ta(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[n,s,r]=arguments;if(arguments.length>0&&typeof n=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof n!="function"))return e.apply(this,[]);const o=function(c){const u={};return c.result().forEach(h=>{const f={id:h.id,timestamp:h.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type};h.names().forEach(p=>{f[p]=h.stat(p)}),u[f.id]=f}),u},a=function(c){return new Map(Object.keys(c).map(u=>[u,c[u]]))};if(arguments.length>=2){const c=function(u){s(a(o(u)))};return e.apply(this,[c,n])}return new Promise((c,u)=>{e.apply(this,[function(l){c(a(o(l)))},u])}).then(s,r)}}function Sa(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>zr(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),Oi(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>zr(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function wa(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(u=>a.indexOf(u)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function Ea(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return wa(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(h=>{if(this.getSenders().find(p=>p.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const h=new i.MediaStream(l.getTracks());this._streams[l.id]=h,this._reverseStreams[h.id]=l,l=h}n.apply(this,[l])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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]},i.RTCPeerConnection.prototype.addTrack=function(l,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const f=[].slice.call(arguments,1);if(f.length!==1||!f[0].getTracks().find(v=>v===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(v=>v.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[h.id];if(y)y.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([l]);this._streams[h.id]=v,this._reverseStreams[v.id]=h,this.addStream(v)}return this.getSenders().find(v=>v.track===l)};function r(u,l){let h=l.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],y=u._streams[p.id];h=h.replace(new RegExp(y.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:h})}function o(u,l){let h=l.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],y=u._streams[p.id];h=h.replace(new RegExp(p.id,"g"),y.id)}),new RTCSessionDescription({type:l.type,sdp:h})}["createOffer","createAnswer"].forEach(function(u){const l=i.RTCPeerConnection.prototype[u],h={[u](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[y=>{const v=r(this,y);f[0].apply(null,[v])},y=>{f[1]&&f[1].apply(null,y)},arguments[2]]):l.apply(this,arguments).then(y=>r(this,y))}};i.RTCPeerConnection.prototype[u]=h[u]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const u=c.get.apply(this);return u.type===""?u:r(this,u)}}),i.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 f;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(v=>l.track===v)&&(f=this._streams[p])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qs(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function Pa(i,e){Oi(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Wr=Object.freeze({__proto__:null,fixNegotiationNeeded:Pa,shimAddTrackRemoveTrack:Ea,shimAddTrackRemoveTrackWithNative:wa,shimGetDisplayMedia:cd,shimGetSendersWithDtmf:Ca,shimGetStats:Ta,shimGetUserMedia:ya,shimMediaStream:ba,shimOnTrack:ka,shimPeerConnection:qs,shimSenderReceiverGetStats:Sa});function _a(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){pr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function ud(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function Ra(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function $s(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(u=>{u.type=t[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;c.forEach((l,h)=>{c.set(h,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function Oa(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function xa(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),Oi(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ia(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){pr("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Na(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Aa(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function Ma(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Da(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.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 La(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.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 Kr=Object.freeze({__proto__:null,shimAddTransceiver:Aa,shimCreateAnswer:La,shimCreateOffer:Da,shimGetDisplayMedia:ud,shimGetParameters:Ma,shimGetUserMedia:_a,shimOnTrack:Ra,shimPeerConnection:$s,shimRTCDataChannel:Na,shimReceiverGetStats:xa,shimRemoveStream:Ia,shimSenderGetStats:Oa});function Ua(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Fa(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.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=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function ja(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(u,l){const h=arguments.length>=2?arguments[2]:arguments[0],f=t.apply(this,[h]);return l?(f.then(u,l),Promise.resolve()):f},e.createAnswer=function(u,l){const h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return l?(f.then(u,l),Promise.resolve()):f};let a=function(c,u,l){const h=s.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h};e.setLocalDescription=a,a=function(c,u,l){const h=r.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h},e.setRemoteDescription=a,a=function(c,u,l){const h=o.apply(this,[c]);return l?(h.then(u,l),Promise.resolve()):h},e.addIceCandidate=a}function Ba(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Ja(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Ja(i){return i&&i.video!==void 0?Object.assign({},i,{video:va(i.video)}):i}function Va(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(pr("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function qa(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function $a(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ha(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Yr=Object.freeze({__proto__:null,shimAudioContext:Ha,shimCallbacksAPI:ja,shimConstraints:Ja,shimCreateOfferLegacy:$a,shimGetUserMedia:Ba,shimLocalStreamsAPI:Ua,shimRTCIceServerUrls:Va,shimRemoteStreamsAPI:Fa,shimTrackEventTransceiver:qa}),za={exports:{}};(function(i){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(`
|
|
19
19
|
`).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
20
20
|
m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
|
|
21
21
|
`)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let r=8;r<n.length;r+=2)switch(n[r]){case"raddr":s.relatedAddress=n[r+1];break;case"rport":s.relatedPort=parseInt(n[r+1],10);break;case"tcptype":s.tcpType=n[r+1];break;case"ufrag":s.ufrag=n[r+1],s.usernameFragment=n[r+1];break;default:s[n[r]]===void 0&&(s[n[r]]=n[r+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const r=t.type;return n.push("typ"),n.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
|
|
@@ -32,7 +32,7 @@ a=ice-pwd:`+t.password+`\r
|
|
|
32
32
|
`,s+=`c=IN IP4 0.0.0.0\r
|
|
33
33
|
`,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
34
34
|
`,n.codecs.forEach(o=>{s+=e.writeRtpMap(o),s+=e.writeFmtp(o),s+=e.writeRtcpFb(o)});let r=0;return n.codecs.forEach(o=>{o.maxptime>r&&(r=o.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r
|
|
35
|
-
`),n.headerExtensions&&n.headerExtensions.forEach(o=>{s+=e.writeExtmap(o)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,o=s.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.attribute==="cname"),c=a.length>0&&a[0].ssrc;let u;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(f=>f.substring(17).split(" ").map(
|
|
35
|
+
`),n.headerExtensions&&n.headerExtensions.forEach(o=>{s+=e.writeExtmap(o)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,o=s.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.attribute==="cname"),c=a.length>0&&a[0].ssrc;let u;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(f=>f.substring(17).split(" ").map(y=>parseInt(y,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(u=l[0][1]),s.codecs.forEach(f=>{if(f.name.toUpperCase()==="RTX"&&f.parameters.apt){let p={ssrc:c,codecPayloadType:parseInt(f.parameters.apt,10)};c&&u&&(p.rtx={ssrc:u}),n.push(p),r&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},n.push(p))}}),n.length===0&&c&&n.push({ssrc:c});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,n.forEach(f=>{f.maxBitrate=h})),n},e.parseRtcpParameters=function(t){const n={},s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];s&&(n.cname=s.value,n.ssrc=s.ssrc);const r=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=r.length===0;const o=e.matchPrefix(t,"a=rtcp-mux");return n.mux=o.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
|
|
36
36
|
`),t.mux&&(n+=`a=rtcp-mux\r
|
|
37
37
|
`),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
38
38
|
`),n},e.parseMsid=function(t){let n;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return n=s[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(r.length>0)return n=r[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let r;s.length>0&&(r=parseInt(s[0].substring(19),10)),isNaN(r)&&(r=65536);const o=e.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:r}}},e.writeSctpDescription=function(t,n){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
|
|
@@ -46,12 +46,12 @@ a=ice-pwd:`+t.password+`\r
|
|
|
46
46
|
o=`+(s||"thisisadapterortc")+" "+r+" "+o+` IN IP4 127.0.0.1\r
|
|
47
47
|
s=-\r
|
|
48
48
|
t=0 0\r
|
|
49
|
-
`},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return n?e.getDirection(n):"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 s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(
|
|
49
|
+
`},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return n?e.getDirection(n):"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 s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(za);var Ga=za.exports,Vi=dl(Ga),ld=ul({__proto__:null,default:Vi},[Ga]);function zn(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),r=Vi.parseCandidate(n.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,Oi(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Hs(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Oi(i,"icecandidate",e=>{if(e.candidate){const t=Vi.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Gn(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Vi.splitSections(a.sdp);return c.shift(),c.some(u=>{const l=Vi.parseMLine(u);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const u=parseInt(c[1],10);return u!==u?-1:u},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(a,c){let u=65536;e.browser==="firefox"&&e.version===57&&(u=65535);const l=Vi.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?u=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(u=2147483637),u},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),u=s(c),l=r(arguments[0],c);let h;u===0&&l===0?h=Number.POSITIVE_INFINITY:u===0||l===0?h=Math.max(u,l):h=Math.min(u,l);const f={};Object.defineProperty(f,"maxMessageSize",{get(){return h}}),this._sctp=f}return o.apply(this,arguments)}}function Wn(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},Oi(i,"datachannel",n=>(e(n.channel,n.target),n))}function zs(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.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 n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Gs(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
|
|
50
50
|
a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
51
51
|
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
|
|
52
|
-
`);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Wn(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.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 Kn(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var dd=Object.freeze({__proto__:null,removeExtmapAllowMixed:zs,shimAddIceCandidateNullOrEmpty:Wn,shimConnectionState:Hs,shimMaxMessageSize:zn,shimParameterlessSetLocalDescription:Kn,shimRTCIceCandidate:Hn,shimRTCIceCandidateRelayProtocol:$s,shimSendThrowTypeError:Gn});function hd(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=ma,n=ad(i),s={browserDetails:n,commonShim:dd,extractVersion:$n,disableLog:rd,disableWarnings:od,sdp:ld};switch(n.browser){case"chrome":if(!Gr||!Vs||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Gr,Wn(i,n),Kn(i),va(i,n),ya(i),Vs(i,n),ba(i),wa(i,n),ka(i),Ca(i),Ta(i),Ea(i,n),Hn(i),$s(i),Hs(i),zn(i,n),Gn(i),zs(i,n);break;case"firefox":if(!Wr||!qs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=Wr,Wn(i,n),Kn(i),Pa(i,n),qs(i,n),_a(i),xa(i),Ra(i),Oa(i),Ia(i),Na(i),Aa(i),Ma(i),Da(i),Hn(i),Hs(i),zn(i,n),Gn(i);break;case"safari":if(!Kr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Kr,Wn(i,n),Kn(i),Ja(i),qa(i),Fa(i),La(i),Ua(i),Va(i),ja(i),$a(i),Hn(i),$s(i),zn(i,n),Gn(i),zs(i,n);break;default:t("Unsupported browser!");break}return s}hd({window:typeof window>"u"?void 0:window});const fd=10,Un="lk_e2ee",pd="LKFrameEncryptionKey",md={sharedKey:!1,ratchetSalt:pd,ratchetWindowSize:8,failureTolerance:fd};var bi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(bi||(bi={}));var Yr;(function(i){i.KeyRatcheted="keyRatcheted"})(Yr||(Yr={}));var vi;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(vi||(vi={}));var Xr;(function(i){i.Error="cryptorError"})(Xr||(Xr={}));function gd(){return vd()||Gs()}function Gs(){return typeof window.RTCRtpScriptTransform<"u"}function vd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Bh extends Et.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{q.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},md),e),this.on(bi.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(bi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(bi.RatchetRequest,e,t)}}class Ki extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class te extends Ki{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class pr extends Ki{constructor(e){super(21,e??"device is unsupported")}}class rt extends Ki{constructor(e){super(20,e??"track is invalid")}}class yd extends Ki{constructor(e){super(10,e??"unsupported server")}}class he extends Ki{constructor(e){super(12,e??"unexpected connection state")}}class Ws extends Ki{constructor(e){super(13,e??"unable to negotiate")}}var es;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(es||(es={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(es||(es={}));var P;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged"})(P||(P={}));var N;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded"})(N||(N={}));var x;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished"})(x||(x={}));var _;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed"})(_||(_={}));function mr(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,u=Date.now(),l=[];function h(){if(c!==void 0){var p=Date.now()-u;if(p+e>=c)return c-p}return e}var f=function(){var p=[].slice.call(arguments),v=this;return new Promise(function(y,R){var S=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,u=Date.now(),!o){var $=i.apply(v,p);a&&a($),l.forEach(function(K){return(0,K.resolve)($)}),l=[]}},h()),S){var w=i.apply(v,p);return a&&a(w),y(w)}l.push({resolve:y,reject:R})})};return f.cancel=function(p){r!==void 0&&clearTimeout(r),l.forEach(function(v){return(0,v.reject)(p)}),l=[]},f}const bd=/version\/(\d+(\.?_?\d+)+)/i;let vs;function ki(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;const t=(i??navigator.userAgent).toLowerCase();if(vs===void 0||e){const n=kd.find(s=>{let{test:r}=s;return r.test(t)});vs=n==null?void 0:n.describe(t)}return vs}const kd=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:ys(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:ys(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:ys(bd,i),os:i.includes("mobile/")?"iOS":"macOS"}}}];function ys(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}var Cd="2.0.2";const Td=Cd,Sd=12;class ke{}ke.setTimeout=function(){return setTimeout(...arguments)};ke.setInterval=function(){return setInterval(...arguments)};ke.clearTimeout=function(){return clearTimeout(...arguments)};ke.clearInterval=function(){return clearInterval(...arguments)};class Q{constructor(e,t,n,s,r){this.width=e,this.height=t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const wd=["vp8","h264"],Ga=["vp8","h264","vp9","av1"];function Ed(i){return!!wd.find(e=>e===i)}var Ks;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:2e4},i.music={maxBitrate:32e3},i.musicStereo={maxBitrate:48e3},i.musicHighQuality={maxBitrate:64e3},i.musicHighQualityStereo={maxBitrate:96e3}})(Ks||(Ks={}));const Pn={h90:new Q(160,90,9e4,20),h180:new Q(320,180,16e4,20),h216:new Q(384,216,18e4,20),h360:new Q(640,360,45e4,20),h540:new Q(960,540,8e5,25),h720:new Q(1280,720,17e5,30),h1080:new Q(1920,1080,3e6,30),h1440:new Q(2560,1440,5e6,30),h2160:new Q(3840,2160,8e6,30)},Ys={h120:new Q(160,120,7e4,20),h180:new Q(240,180,125e3,20),h240:new Q(320,240,14e4,20),h360:new Q(480,360,33e4,20),h480:new Q(640,480,5e5,20),h540:new Q(720,540,6e5,25),h720:new Q(960,720,13e5,30),h1080:new Q(1440,1080,23e5,30),h1440:new Q(1920,1440,38e5,30)},gr={h360fps3:new Q(640,360,2e5,3,"medium"),h360fps15:new Q(640,360,4e5,15,"medium"),h720fps5:new Q(1280,720,8e5,5,"medium"),h720fps15:new Q(1280,720,15e5,15,"medium"),h720fps30:new Q(1280,720,2e6,30,"medium"),h1080fps15:new Q(1920,1080,25e5,15,"medium"),h1080fps30:new Q(1920,1080,5e6,30,"medium"),original:new Q(0,0,7e6,30,"medium")};var we;(function(i){i[i.PUBLISHER=0]="PUBLISHER",i[i.SUBSCRIBER=1]="SUBSCRIBER"})(we||(we={}));d.util.setEnumType(we,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]);var _i;(function(i){i[i.ACTIVE=0]="ACTIVE",i[i.PAUSED=1]="PAUSED"})(_i||(_i={}));d.util.setEnumType(_i,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);var ts;(function(i){i[i.UDP=0]="UDP",i[i.TCP=1]="TCP",i[i.TLS=2]="TLS"})(ts||(ts={}));d.util.setEnumType(ts,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class Bt extends O{constructor(e){super(),this.message={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new Bt().fromBinary(e,t)}static fromJson(e,t){return new Bt().fromJson(e,t)}static fromJsonString(e,t){return new Bt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Bt,e,t)}}Bt.runtime=d;Bt.typeName="livekit.SignalRequest";Bt.fields=d.util.newFieldList(()=>[{no:1,name:"offer",kind:"message",T:_e,oneof:"message"},{no:2,name:"answer",kind:"message",T:_e,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ke,oneof:"message"},{no:4,name:"add_track",kind:"message",T:We,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ye,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Fe,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:mt,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:gt,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:kt,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ct,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ye,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:vt,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:St,oneof:"message"}]);class pt extends O{constructor(e){super(),this.message={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new pt().fromBinary(e,t)}static fromJson(e,t){return new pt().fromJson(e,t)}static fromJsonString(e,t){return new pt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(pt,e,t)}}pt.runtime=d;pt.typeName="livekit.SignalResponse";pt.fields=d.util.newFieldList(()=>[{no:1,name:"join",kind:"message",T:Jt,oneof:"message"},{no:2,name:"answer",kind:"message",T:_e,oneof:"message"},{no:3,name:"offer",kind:"message",T:_e,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ke,oneof:"message"},{no:5,name:"update",kind:"message",T:$t,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xe,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ye,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ht,oneof:"message"},{no:11,name:"room_update",kind:"message",T:zt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Wt,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Yt,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Qt,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Zt,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:qt,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Vt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ei,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ni,oneof:"message"}]);class Ge extends O{constructor(e){super(),this.codec="",this.cid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ge().fromBinary(e,t)}static fromJson(e,t){return new Ge().fromJson(e,t)}static fromJsonString(e,t){return new Ge().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ge,e,t)}}Ge.runtime=d;Ge.typeName="livekit.SimulcastCodec";Ge.fields=d.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]);class We extends O{constructor(e){super(),this.cid="",this.name="",this.type=Se.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=ce.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=be.NONE,this.stream="",d.util.initPartial(e,this)}static fromBinary(e,t){return new We().fromBinary(e,t)}static fromJson(e,t){return new We().fromJson(e,t)}static fromJsonString(e,t){return new We().fromJsonString(e,t)}static equals(e,t){return d.util.equals(We,e,t)}}We.runtime=d;We.typeName="livekit.AddTrackRequest";We.fields=d.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:d.getEnumType(Se)},{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:d.getEnumType(ce)},{no:9,name:"layers",kind:"message",T:Pe,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Ge,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:d.getEnumType(be)},{no:15,name:"stream",kind:"scalar",T:9}]);class Ke extends O{constructor(e){super(),this.candidateInit="",this.target=we.PUBLISHER,d.util.initPartial(e,this)}static fromBinary(e,t){return new Ke().fromBinary(e,t)}static fromJson(e,t){return new Ke().fromJson(e,t)}static fromJsonString(e,t){return new Ke().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ke,e,t)}}Ke.runtime=d;Ke.typeName="livekit.TrickleRequest";Ke.fields=d.util.newFieldList(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:d.getEnumType(we)}]);class Ye extends O{constructor(e){super(),this.sid="",this.muted=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Ye().fromBinary(e,t)}static fromJson(e,t){return new Ye().fromJson(e,t)}static fromJsonString(e,t){return new Ye().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ye,e,t)}}Ye.runtime=d;Ye.typeName="livekit.MuteTrackRequest";Ye.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]);class Jt extends O{constructor(e){super(),this.otherParticipants=[],this.serverVersion="",this.iceServers=[],this.subscriberPrimary=!1,this.alternativeUrl="",this.serverRegion="",this.pingTimeout=0,this.pingInterval=0,this.sifTrailer=new Uint8Array(0),d.util.initPartial(e,this)}static fromBinary(e,t){return new Jt().fromBinary(e,t)}static fromJson(e,t){return new Jt().fromJson(e,t)}static fromJsonString(e,t){return new Jt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Jt,e,t)}}Jt.runtime=d;Jt.typeName="livekit.JoinResponse";Jt.fields=d.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Wi},{no:2,name:"participant",kind:"message",T:De},{no:3,name:"other_participants",kind:"message",T:De,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:yt,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:lt},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Ut},{no:13,name:"sif_trailer",kind:"scalar",T:12}]);class Vt extends O{constructor(e){super(),this.iceServers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Vt().fromBinary(e,t)}static fromJson(e,t){return new Vt().fromJson(e,t)}static fromJsonString(e,t){return new Vt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Vt,e,t)}}Vt.runtime=d;Vt.typeName="livekit.ReconnectResponse";Vt.fields=d.util.newFieldList(()=>[{no:1,name:"ice_servers",kind:"message",T:yt,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:lt}]);class Xe extends O{constructor(e){super(),this.cid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Xe().fromBinary(e,t)}static fromJson(e,t){return new Xe().fromJson(e,t)}static fromJsonString(e,t){return new Xe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Xe,e,t)}}Xe.runtime=d;Xe.typeName="livekit.TrackPublishedResponse";Xe.fields=d.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:xe}]);class qt extends O{constructor(e){super(),this.trackSid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new qt().fromBinary(e,t)}static fromJson(e,t){return new qt().fromJson(e,t)}static fromJsonString(e,t){return new qt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(qt,e,t)}}qt.runtime=d;qt.typeName="livekit.TrackUnpublishedResponse";qt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);class _e extends O{constructor(e){super(),this.type="",this.sdp="",d.util.initPartial(e,this)}static fromBinary(e,t){return new _e().fromBinary(e,t)}static fromJson(e,t){return new _e().fromJson(e,t)}static fromJsonString(e,t){return new _e().fromJsonString(e,t)}static equals(e,t){return d.util.equals(_e,e,t)}}_e.runtime=d;_e.typeName="livekit.SessionDescription";_e.fields=d.util.newFieldList(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]);class $t extends O{constructor(e){super(),this.participants=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new $t().fromBinary(e,t)}static fromJson(e,t){return new $t().fromJson(e,t)}static fromJsonString(e,t){return new $t().fromJsonString(e,t)}static equals(e,t){return d.util.equals($t,e,t)}}$t.runtime=d;$t.typeName="livekit.ParticipantUpdate";$t.fields=d.util.newFieldList(()=>[{no:1,name:"participants",kind:"message",T:De,repeated:!0}]);class Fe extends O{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Fe().fromBinary(e,t)}static fromJson(e,t){return new Fe().fromJson(e,t)}static fromJsonString(e,t){return new Fe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Fe,e,t)}}Fe.runtime=d;Fe.typeName="livekit.UpdateSubscription";Fe.fields=d.util.newFieldList(()=>[{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:ut,repeated:!0}]);class mt extends O{constructor(e){super(),this.trackSids=[],this.disabled=!1,this.quality=ui.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new mt().fromBinary(e,t)}static fromJson(e,t){return new mt().fromJson(e,t)}static fromJsonString(e,t){return new mt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(mt,e,t)}}mt.runtime=d;mt.typeName="livekit.UpdateTrackSettings";mt.fields=d.util.newFieldList(()=>[{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:d.getEnumType(ui)},{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}]);class je extends O{constructor(e){super(),this.canReconnect=!1,this.reason=ri.UNKNOWN_REASON,this.action=_n.DISCONNECT,d.util.initPartial(e,this)}static fromBinary(e,t){return new je().fromBinary(e,t)}static fromJson(e,t){return new je().fromJson(e,t)}static fromJsonString(e,t){return new je().fromJsonString(e,t)}static equals(e,t){return d.util.equals(je,e,t)}}je.runtime=d;je.typeName="livekit.LeaveRequest";je.fields=d.util.newFieldList(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:d.getEnumType(ri)},{no:3,name:"action",kind:"enum",T:d.getEnumType(_n)},{no:4,name:"regions",kind:"message",T:ti}]);var _n;(function(i){i[i.DISCONNECT=0]="DISCONNECT",i[i.RESUME=1]="RESUME",i[i.RECONNECT=2]="RECONNECT"})(_n||(_n={}));d.util.setEnumType(_n,"livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]);class gt extends O{constructor(e){super(),this.trackSid="",this.layers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new gt().fromBinary(e,t)}static fromJson(e,t){return new gt().fromJson(e,t)}static fromJsonString(e,t){return new gt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(gt,e,t)}}gt.runtime=d;gt.typeName="livekit.UpdateVideoLayers";gt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Pe,repeated:!0}]);class vt extends O{constructor(e){super(),this.metadata="",this.name="",d.util.initPartial(e,this)}static fromBinary(e,t){return new vt().fromBinary(e,t)}static fromJson(e,t){return new vt().fromJson(e,t)}static fromJsonString(e,t){return new vt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(vt,e,t)}}vt.runtime=d;vt.typeName="livekit.UpdateParticipantMetadata";vt.fields=d.util.newFieldList(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]);class yt extends O{constructor(e){super(),this.urls=[],this.username="",this.credential="",d.util.initPartial(e,this)}static fromBinary(e,t){return new yt().fromBinary(e,t)}static fromJson(e,t){return new yt().fromJson(e,t)}static fromJsonString(e,t){return new yt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(yt,e,t)}}yt.runtime=d;yt.typeName="livekit.ICEServer";yt.fields=d.util.newFieldList(()=>[{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}]);class Ht extends O{constructor(e){super(),this.speakers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Ht().fromBinary(e,t)}static fromJson(e,t){return new Ht().fromJson(e,t)}static fromJsonString(e,t){return new Ht().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ht,e,t)}}Ht.runtime=d;Ht.typeName="livekit.SpeakersChanged";Ht.fields=d.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:at,repeated:!0}]);class zt extends O{constructor(e){super(),d.util.initPartial(e,this)}static fromBinary(e,t){return new zt().fromBinary(e,t)}static fromJson(e,t){return new zt().fromJson(e,t)}static fromJsonString(e,t){return new zt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(zt,e,t)}}zt.runtime=d;zt.typeName="livekit.RoomUpdate";zt.fields=d.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Wi}]);class Gt extends O{constructor(e){super(),this.participantSid="",this.quality=At.POOR,this.score=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new Gt().fromBinary(e,t)}static fromJson(e,t){return new Gt().fromJson(e,t)}static fromJsonString(e,t){return new Gt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Gt,e,t)}}Gt.runtime=d;Gt.typeName="livekit.ConnectionQualityInfo";Gt.fields=d.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:d.getEnumType(At)},{no:3,name:"score",kind:"scalar",T:2}]);class Wt extends O{constructor(e){super(),this.updates=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Wt().fromBinary(e,t)}static fromJson(e,t){return new Wt().fromJson(e,t)}static fromJsonString(e,t){return new Wt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Wt,e,t)}}Wt.runtime=d;Wt.typeName="livekit.ConnectionQualityUpdate";Wt.fields=d.util.newFieldList(()=>[{no:1,name:"updates",kind:"message",T:Gt,repeated:!0}]);class Kt extends O{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=_i.ACTIVE,d.util.initPartial(e,this)}static fromBinary(e,t){return new Kt().fromBinary(e,t)}static fromJson(e,t){return new Kt().fromJson(e,t)}static fromJsonString(e,t){return new Kt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Kt,e,t)}}Kt.runtime=d;Kt.typeName="livekit.StreamStateInfo";Kt.fields=d.util.newFieldList(()=>[{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:d.getEnumType(_i)}]);class Yt extends O{constructor(e){super(),this.streamStates=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Yt().fromBinary(e,t)}static fromJson(e,t){return new Yt().fromJson(e,t)}static fromJsonString(e,t){return new Yt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Yt,e,t)}}Yt.runtime=d;Yt.typeName="livekit.StreamStateUpdate";Yt.fields=d.util.newFieldList(()=>[{no:1,name:"stream_states",kind:"message",T:Kt,repeated:!0}]);class Qe extends O{constructor(e){super(),this.quality=ui.LOW,this.enabled=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Qe().fromBinary(e,t)}static fromJson(e,t){return new Qe().fromJson(e,t)}static fromJsonString(e,t){return new Qe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Qe,e,t)}}Qe.runtime=d;Qe.typeName="livekit.SubscribedQuality";Qe.fields=d.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:d.getEnumType(ui)},{no:2,name:"enabled",kind:"scalar",T:8}]);class Xt extends O{constructor(e){super(),this.codec="",this.qualities=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Xt().fromBinary(e,t)}static fromJson(e,t){return new Xt().fromJson(e,t)}static fromJsonString(e,t){return new Xt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Xt,e,t)}}Xt.runtime=d;Xt.typeName="livekit.SubscribedCodec";Xt.fields=d.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Qe,repeated:!0}]);class Qt extends O{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Qt().fromBinary(e,t)}static fromJson(e,t){return new Qt().fromJson(e,t)}static fromJsonString(e,t){return new Qt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Qt,e,t)}}Qt.runtime=d;Qt.typeName="livekit.SubscribedQualityUpdate";Qt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Qe,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Xt,repeated:!0}]);class bt extends O{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",d.util.initPartial(e,this)}static fromBinary(e,t){return new bt().fromBinary(e,t)}static fromJson(e,t){return new bt().fromJson(e,t)}static fromJsonString(e,t){return new bt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(bt,e,t)}}bt.runtime=d;bt.typeName="livekit.TrackPermission";bt.fields=d.util.newFieldList(()=>[{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}]);class kt extends O{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new kt().fromBinary(e,t)}static fromJson(e,t){return new kt().fromJson(e,t)}static fromJsonString(e,t){return new kt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(kt,e,t)}}kt.runtime=d;kt.typeName="livekit.SubscriptionPermission";kt.fields=d.util.newFieldList(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:bt,repeated:!0}]);class Zt extends O{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Zt().fromBinary(e,t)}static fromJson(e,t){return new Zt().fromJson(e,t)}static fromJsonString(e,t){return new Zt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Zt,e,t)}}Zt.runtime=d;Zt.typeName="livekit.SubscriptionPermissionUpdate";Zt.fields=d.util.newFieldList(()=>[{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}]);class Ct extends O{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],this.trackSidsDisabled=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Ct().fromBinary(e,t)}static fromJson(e,t){return new Ct().fromJson(e,t)}static fromJsonString(e,t){return new Ct().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ct,e,t)}}Ct.runtime=d;Ct.typeName="livekit.SyncState";Ct.fields=d.util.newFieldList(()=>[{no:1,name:"answer",kind:"message",T:_e},{no:2,name:"subscription",kind:"message",T:Fe},{no:3,name:"publish_tracks",kind:"message",T:Xe,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Tt,repeated:!0},{no:5,name:"offer",kind:"message",T:_e},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]);class Tt extends O{constructor(e){super(),this.label="",this.id=0,this.target=we.PUBLISHER,d.util.initPartial(e,this)}static fromBinary(e,t){return new Tt().fromBinary(e,t)}static fromJson(e,t){return new Tt().fromJson(e,t)}static fromJsonString(e,t){return new Tt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Tt,e,t)}}Tt.runtime=d;Tt.typeName="livekit.DataChannelInfo";Tt.fields=d.util.newFieldList(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:d.getEnumType(we)}]);class ye extends O{constructor(e){super(),this.scenario={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new ye().fromBinary(e,t)}static fromJson(e,t){return new ye().fromJson(e,t)}static fromJsonString(e,t){return new ye().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ye,e,t)}}ye.runtime=d;ye.typeName="livekit.SimulateScenario";ye.fields=d.util.newFieldList(()=>[{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:d.getEnumType(ts),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"}]);class St extends O{constructor(e){super(),this.timestamp=F.zero,this.rtt=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new St().fromBinary(e,t)}static fromJson(e,t){return new St().fromJson(e,t)}static fromJsonString(e,t){return new St().fromJsonString(e,t)}static equals(e,t){return d.util.equals(St,e,t)}}St.runtime=d;St.typeName="livekit.Ping";St.fields=d.util.newFieldList(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]);class ei extends O{constructor(e){super(),this.lastPingTimestamp=F.zero,this.timestamp=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ei,e,t)}}ei.runtime=d;ei.typeName="livekit.Pong";ei.fields=d.util.newFieldList(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]);class ti extends O{constructor(e){super(),this.regions=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new ti().fromBinary(e,t)}static fromJson(e,t){return new ti().fromJson(e,t)}static fromJsonString(e,t){return new ti().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ti,e,t)}}ti.runtime=d;ti.typeName="livekit.RegionSettings";ti.fields=d.util.newFieldList(()=>[{no:1,name:"regions",kind:"message",T:ii,repeated:!0}]);class ii extends O{constructor(e){super(),this.region="",this.url="",this.distance=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new ii().fromBinary(e,t)}static fromJson(e,t){return new ii().fromJson(e,t)}static fromJsonString(e,t){return new ii().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ii,e,t)}}ii.runtime=d;ii.typeName="livekit.RegionInfo";ii.fields=d.util.newFieldList(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]);class ni extends O{constructor(e){super(),this.trackSid="",this.err=wn.SE_UNKNOWN,d.util.initPartial(e,this)}static fromBinary(e,t){return new ni().fromBinary(e,t)}static fromJson(e,t){return new ni().fromJson(e,t)}static fromJsonString(e,t){return new ni().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ni,e,t)}}ni.runtime=d;ni.typeName="livekit.SubscriptionResponse";ni.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:d.getEnumType(wn)}]);function Pd(i){if(!(typeof i>"u"))return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}const _d=5e3,sn=[];var Be;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Be||(Be={}));class C extends Et.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=q,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),_d):this.handleAppVisibilityChanged()},this.log=ci((s=n.loggerName)!==null&&s!==void 0?s:wt.Track),this.loggerContextCb=n.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)),ie(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&&C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(sn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&sn.splice(sn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Fi(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?_.AudioPlaybackStarted:_.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?_.AudioPlaybackFailed:_.VideoPlaybackFailed,r):r.name==="AbortError"?q.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):q.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(_.ElementAttached,e),e}detach(e){try{if(e){Vi(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(_.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Vi(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(_.ElementDetached,n)}),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)}updateLoggerOptions(e){e.loggerName&&(this.log=ci(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sn.forEach(n=>{n.parentElement||(t=!1)}),t&&sn.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){Ie()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ie()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fi(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!Ri()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Ri()||Gi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Vi(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(u){u.Audio="audio",u.Video="video",u.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(u){u.Camera="camera",u.Microphone="microphone",u.ScreenShare="screen_share",u.ScreenShareAudio="screen_share_audio",u.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(u){u.Active="active",u.Paused="paused",u.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(u){switch(u){case e.Audio:return Se.AUDIO;case e.Video:return Se.VIDEO;default:return Se.DATA}}i.kindToProto=s;function r(u){switch(u){case Se.AUDIO:return e.Audio;case Se.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(u){switch(u){case t.Camera:return ce.CAMERA;case t.Microphone:return ce.MICROPHONE;case t.ScreenShare:return ce.SCREEN_SHARE;case t.ScreenShareAudio:return ce.SCREEN_SHARE_AUDIO;default:return ce.UNKNOWN}}i.sourceToProto=o;function a(u){switch(u){case ce.CAMERA:return t.Camera;case ce.MICROPHONE:return t.Microphone;case ce.SCREEN_SHARE:return t.ScreenShare;case ce.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(u){switch(u){case _i.ACTIVE:return n.Active;case _i.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(C||(C={}));function Wa(i,e,t){var n;const s=(n=Pd(i))!==null&&n!==void 0?n:{};return s.audio===!0&&(s.audio={}),s.video===!0&&(s.video={}),s.audio&&Xs(s.audio,e),s.video&&Xs(s.video,t),s}function Xs(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function us(i){const e={};if(i.video)if(typeof i.video=="object"){const t={},n=t,s=i.video;Object.keys(s).forEach(r=>{switch(r){case"resolution":Xs(n,s.resolution);break;default:n[r]=s[r]}}),e.video=t}else e.video=i.video;else e.video=!1;return i.audio?typeof i.audio=="object"?e.audio=i.audio:e.audio=!0:e.audio=!1,e}function Rd(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return m(this,void 0,void 0,function*(){const t=Ka();if(t){const n=t.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);t.createMediaStreamSource(new MediaStream([i.mediaStreamTrack])).connect(n),yield oi(e),n.getByteTimeDomainData(r);const a=r.some(c=>c!==128&&c!==0);return t.close(),!a}return!1})}function Ka(){const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(i)return new i({latencyHint:"interactive"})}function Od(i){return i===C.Source.Microphone?"audioinput":i===C.Source.Camera?"videoinput":void 0}function xd(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Ri()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio}}function Ya(i){const e=i.split("/")[1].toLowerCase();if(!Ga.includes(e))throw Error("Video codec not supported: ".concat(e));return e}function Id(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Xe({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ie(i){return i instanceof C?{trackSid:i.sid,trackSource:i.source,trackMuted:i.isMuted,trackEnabled:i.mediaStreamTrack.enabled,trackKind:i.kind}:{trackSid:i.trackSid,trackName:i.trackName,track:i.track?ie(i.track):void 0,trackEnabled:i.isEnabled,trackEncrypted:i.isEncrypted,trackMimeType:i.mimeType}}const Nd="|",Qr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ad(i){const e=i.split(Nd);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function oi(i){return m(this,void 0,void 0,function*(){return new Promise(e=>ke.setTimeout(e,i))})}function Zr(){return"addTransceiver"in RTCPeerConnection.prototype}function eo(){return"addTrack"in RTCPeerConnection.prototype}function Md(){if(!("getCapabilities"in RTCRtpSender)||Ri())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Dd(){if(!("getCapabilities"in RTCRtpSender)||Gi())return!1;if(Ri()){const t=ki();if(t!=null&&t.version&&vr(t.version,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function gn(i){return i==="av1"||i==="vp9"}function Qs(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}const Ld={Chrome:"100",Safari:"15",Firefox:"100"};function Ud(i){if(!Ie()||!("setCodecPreferences"in i))return!1;const e=ki();if(!(e!=null&&e.name)||!e.version)return!1;const t=Ld[e.name];return t?vr(e.version,t)>=0:!1}function Gi(){var i;return((i=ki())===null||i===void 0?void 0:i.name)==="Firefox"}function Ri(){var i;return((i=ki())===null||i===void 0?void 0:i.name)==="Safari"}function Fd(){const i=ki();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")}function Xa(){return Ie()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Ie(){return typeof document<"u"}function Oi(){return navigator.product=="ReactNative"}function Zs(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function Qa(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Za(){if(!Oi())return;let i=Qa();if(i)return i.platform}function to(){if(Ie())return window.devicePixelRatio;if(Oi()){let i=Qa();if(i)return i.devicePixelRatio}return 1}function vr(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function jd(i){for(const e of i)e.target.handleResize(e)}function Bd(i){for(const e of i)e.target.handleVisibilityChanged(e)}let bs=null;const io=()=>(bs||(bs=new ResizeObserver(jd)),bs);let ks=null;const no=()=>(ks||(ks=new IntersectionObserver(Bd,{root:null,rootMargin:"0px"})),ks);function Jd(){var i;const e=new Ft({sdk:zi.JS,protocol:Sd,version:Td});return Oi()&&(e.os=(i=Za())!==null&&i!==void 0?i:""),e}function so(){let i=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,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let rn;function Cs(){if(!rn){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[rn]=n.stream.getAudioTracks(),!rn)throw Error("Could not get empty media stream audio track");rn.enabled=!1}return rn.clone()}class ec{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,s)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}class Ze{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Vd(i){return Ga.includes(i)}function wi(i){if(typeof i=="string")return i;if(Array.isArray(i))return i[0];if(i.exact)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function qd(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function ro(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}const oo="default";class Ee{static getInstance(){return this.instance===void 0&&(this.instance=new Ee),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n;return m(this,void 0,void 0,function*(){if(((n=Ee.userMediaPromiseMap)===null||n===void 0?void 0:n.size)>0){q.debug("awaiting getUserMedia promise");try{e?yield Ee.userMediaPromiseMap.get(e):yield Promise.all(Ee.userMediaPromiseMap.values())}catch{q.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&!(Ri()&&this.hasDeviceInUse(e))&&(s.length===0||s.some(o=>{const a=o.label==="",c=e?o.kind===e:!0;return a&&c}))){const o={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},a=yield navigator.mediaDevices.getUserMedia(o);s=yield navigator.mediaDevices.enumerateDevices(),a.getTracks().forEach(c=>{c.stop()})}return e&&(s=s.filter(r=>r.kind===e)),s})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==oo)return t;const r=(yield this.getDevices(e)).find(o=>o.groupId===n&&o.deviceId!==oo);return r==null?void 0:r.deviceId})}hasDeviceInUse(e){return e?Ee.userMediaPromiseMap.has(e):Ee.userMediaPromiseMap.size>0}}Ee.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Ee.userMediaPromiseMap=new Map;const $d=1e3;class Rn extends C{get constraints(){return this._constraints}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=mr(()=>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(_.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Ze,this.pauseUpstreamLock=new Ze,this.processorLock=new Ze,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return m(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Vi(this._mediaStreamTrack,s)}),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 n;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{s()}}this.sender&&(yield this.sender.replaceTrack(n??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Fi(n??e,s)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$d;var t;return m(this,void 0,void 0,function*(){if(this.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((t=ki())===null||t===void 0?void 0:t.os)==="iOS"&&(yield oi(10));const n=Date.now();for(;Date.now()-n<e;){const s=this.dimensions;if(s)return s;yield oi(50)}throw new rt("unable to get track dimensions after timeout")})}getDeviceId(){return m(this,void 0,void 0,function*(){if(this.source===C.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),n=this.kind===C.Kind.Audio?"audioinput":"videoinput";return Ee.getInstance().normalizeDeviceId(n,e,t)})}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){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return m(this,void 0,void 0,function*(){if(!this.sender)throw new rt("unable to replace an unpublished track");return this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){e||(e=this._constraints),this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const t={audio:!1,video:!1};this.kind===C.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach(r=>{Vi(this.mediaStreamTrack,r)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const s=(yield navigator.mediaDevices.getUserMedia(t)).getTracks()[0];return s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(_.Restarted,this),this})}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?_.Muted:_.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),Xa()&&(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;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*(){const e=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(_.UpstreamPaused,this);const t=ki();if((t==null?void 0:t.name)==="Safari"&&vr(t.version,"12.0")<0)throw new pr("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){const e=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(_.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return m(this,void 0,void 0,function*(){return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n,s;return m(this,void 0,void 0,function*(){const r=yield this.processorLock.lock();try{if(this.log.debug("setting up processor",this.logContext),this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement=(n=this.processorElement)!==null&&n!==void 0?n:document.createElement(this.kind),Fi(this._mediaStreamTrack,this.processorElement),this.processorElement.muted=!0,this.processorElement.play().catch(a=>this.log.error("failed to play processor element",Object.assign(Object.assign({},this.logContext),{error:a})));const o={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement,audioContext:this.audioContext};if(yield e.init(o),this.processor=e,this.processor.processedTrack){for(const a of this.attachedElements)a!==this.processorElement&&t&&(Vi(this._mediaStreamTrack,a),Fi(this.processor.processedTrack,a));yield(s=this.sender)===null||s===void 0?void 0:s.replaceTrack(this.processor.processedTrack)}}finally{r()}})}getProcessor(){return this.processor}stopProcessor(){var e,t;return m(this,void 0,void 0,function*(){this.processor&&(this.log.debug("stopping processor",this.logContext),(e=this.processor.processedTrack)===null||e===void 0||e.stop(),yield this.processor.destroy(),this.processor=void 0,(t=this.processorElement)===null||t===void 0||t.remove(),this.processorElement=void 0,yield this.restart())})}}class Hd extends Et.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:o}=t.data;switch(r){case"error":q.error(o.error.message),this.emit(vi.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(this.encryptionEnabled!==o.enabled&&o.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(vi.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(vi.ParticipantEncryptionStatusChanged,o.enabled,a)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"ratchetKey":this.keyProvider.emit(bi.KeyRatcheted,o.material,o.keyIndex);break}},this.onWorkerError=t=>{q.error("e2ee worker encountered an error:",{error:t.error}),this.emit(vi.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!gd())throw new pr("tried to setup end-to-end encryption on an unsupported browser");if(q.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&(q.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){q.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?q.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(x.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(P.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==be.NONE,s.identity)),e.on(P.ConnectionStateChanged,n=>{n===X.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==be.NONE,s.identity)})})}).on(P.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(P.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(P.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),t.getKeys().forEach(n=>{this.postKey(n)})}),e.localParticipant.on(N.LocalTrackPublished,n=>m(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(bi.SetKey,n=>this.postKey(n)).on(bi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Ya(n.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof Rn)||!t){t||q.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return m(this,void 0,void 0,function*(){if(this.worker){if(Gs()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Un in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(a,[o,r])}e[Un]=!0}})}handleSender(e,t,n){var s;if(!(Un 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(Gs()){q.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{q.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(o,[r.readable,r.writable])}e[Un]=!0}}}var vn;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(vn||(vn={}));class zd{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ze,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:vn.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=vn.RUNNING,yield e()}finally{t.status=vn.COMPLETED,this.pendingTasks.delete(t.id),n()}})}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())}}const Gd=["syncState","trickle","offer","answer","simulate","leave"];function Wd(i){const e=Gd.indexOf(i.case)>=0;return q.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var re;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(re||(re={}));class yr{get currentState(){return this.state}get isDisconnected(){return this.state===re.DISCONNECTING||this.state===re.DISCONNECTED}get isEstablishingConnection(){return this.state===re.CONNECTING||this.state===re.RECONNECTING}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=re.DISCONNECTED,this.log=q,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.log=ci((n=t.loggerName)!==null&&n!==void 0?n:wt.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new zd,this.queuedRequests=[],this.closingLock=new Ze,this.connectionLock=new Ze,this.state=re.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,n,s){return m(this,void 0,void 0,function*(){return this.state=re.CONNECTING,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=re.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}))})}connect(e,t,n,s){this.connectOptions=n,e=qd(e),e=e.replace(/\/$/,""),e+="/rtc";const r=Jd(),o=Kd(t,r,n);return new Promise((a,c)=>m(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const l=()=>m(this,void 0,void 0,function*(){this.close(),clearTimeout(h),c(new te("room connection has been cancelled (signal)"))}),h=setTimeout(()=>{this.close(),c(new te("room connection has timed out (signal)"))},n.websocketTimeout);s!=null&&s.aborted&&l(),s==null||s.addEventListener("abort",l),this.log.debug("connecting to ".concat(e+o),this.logContext),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(e+o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=f=>m(this,void 0,void 0,function*(){if(this.state!==re.CONNECTED){clearTimeout(h);try{const p=yield fetch("http".concat(e.substring(2),"/validate").concat(o));if(p.status.toFixed(0).startsWith("4")){const v=yield p.text();c(new te(v,0,p.status))}else c(new te("Internal error",2,p.status))}catch{c(new te("server was not reachable",1))}return}this.handleWSError(f)}),this.ws.onmessage=f=>m(this,void 0,void 0,function*(){var p,v,y,R;let S;if(typeof f.data=="string"){const w=JSON.parse(f.data);S=pt.fromJson(w,{ignoreUnknownFields:!0})}else if(f.data instanceof ArrayBuffer)S=pt.fromBinary(new Uint8Array(f.data));else{this.log.error("could not decode websocket message: ".concat(typeof f.data),this.logContext);return}if(this.state!==re.CONNECTED){let w=!1;if(((p=S.message)===null||p===void 0?void 0:p.case)==="join"?(this.state=re.CONNECTED,s==null||s.removeEventListener("abort",l),this.pingTimeoutDuration=S.message.value.pingTimeout,this.pingIntervalDuration=S.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),a(S.message.value)):this.state===re.RECONNECTING&&S.message.case!=="leave"?(this.state=re.CONNECTED,s==null||s.removeEventListener("abort",l),this.startPingInterval(),((v=S.message)===null||v===void 0?void 0:v.case)==="reconnect"?a((y=S.message)===null||y===void 0?void 0:y.value):(a(),w=!0)):this.isEstablishingConnection&&S.message.case==="leave"?c(new te("Received leave request while trying to (re)connect",4)):n.reconnect||c(new te("did not receive join response, got ".concat((R=S.message)===null||R===void 0?void 0:R.case," instead"))),!w)return}this.signalLatency&&(yield oi(this.signalLatency)),this.handleSignalResponse(S)}),this.ws.onclose=f=>{this.isEstablishingConnection&&c(new te("Websocket got closed during a (re)connection attempt")),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:f.reason,code:f.code,wasClean:f.wasClean,state:this.state})),this.handleOnClose(f.reason)}}finally{u()}}))}close(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return m(this,void 0,void 0,function*(){const t=yield this.closingLock.lock();try{if(e&&(this.state=re.DISCONNECTING),this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const n=new Promise(s=>{this.ws?this.ws.onclose=()=>{s()}:s()});this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([n,oi(250)])),this.ws=void 0}}finally{e&&(this.state=re.DISCONNECTED),this.clearPingInterval(),t()}})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:is(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:is(e)})}sendIceCandidate(e,t){return this.log.trace("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ke({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ye({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new vt({metadata:e,name:t})})}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 gt({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new kt({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:F.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new St({timestamp:F.parse(Date.now()),rtt:F.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new je({canReconnect:!1,reason:ri.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return m(this,void 0,void 0,function*(){if(!t&&!Wd(e)&&this.state===re.RECONNECTING){this.queuedRequests.push(()=>m(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield oi(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){this.log.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case),this.logContext);return}const s=new Bt({message:e});try{this.useJSON?this.ws.send(s.toJsonString()):this.ws.send(s.toBinary())}catch(r){this.log.error("error sending signal message",Object.assign(Object.assign({},this.logContext),{error:r}))}})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=ao(s.value);this.onAnswer&&this.onAnswer(o)}else if(s.case==="offer"){const o=ao(s.value);this.onOffer&&this.onOffer(o)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||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===re.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=ke.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ke.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=ke.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ke.clearInterval(this.pingInterval)}}function ao(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function is(i){return new _e({sdp:i.sdp,type:i.type})}function Kd(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Oi()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),"?".concat(s.toString())}var tc={},ic={exports:{}},co=ic.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var e="candidate:%s %d %s %d %s %d typ %s";return e+=i.raddr!=null?" raddr %s rport %d":"%v%v",e+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(e+=" generation %d"),e+=i["network-id"]!=null?" network-id %d":"%v",e+=i["network-cost"]!=null?" network-cost %d":"%v",e}},{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(i){var e="ssrc:%d";return i.attribute!=null&&(e+=" %s",i.value!=null&&(e+=":%s")),e}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var e="mediaclk:";return e+=i.id!=null?"id=%s %s":"%v%s",e+=i.mediaClockValue!=null?"=%s":"",e+=i.rateNumerator!=null?" rate=%s":"",e+=i.rateDenominator!=null?"/%s":"",e}},{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"]}]};Object.keys(co).forEach(function(i){var e=co[i];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var nc=ic.exports;(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,u,l){if(l&&!u)c[l]=e(a[1]);else for(var h=0;h<u.length;h+=1)a[h+1]!=null&&(c[u[h]]=e(a[h+1]))},n=function(a,c,u){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var h=a.push?{}:l?c[a.name]:c;t(u.match(a.reg),h,a.names,a.name),a.push&&c[a.push].push(h)},s=nc,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},u=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var f=h[0],p=h.slice(2);f==="m"&&(u.push({rtp:[],fmtp:[]}),l=u[u.length-1]);for(var v=0;v<(s[f]||[]).length;v+=1){var y=s[f][v];if(y.reg.test(p))return n(y,l,p)}}),c.media=u,c};var o=function(a,c){var u=c.split(/=(.+)/,2);return u.length===2?a[u[0]]=e(u[1]):u.length===1&&c.length>1&&(a[u[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],u=a.split(" ").map(e),l=0;l<u.length;l+=3)c.push({component:u[l],ip:u[l+1],port:u[l+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(u){var l,h=!1;return u[0]!=="~"?l=e(u):(l=e(u.substring(1,u.length)),h=!0),{scid:l,paused:h}})})}})(tc);var Ts=nc,Yd=/%[sdv%]/g,Xd=function(i){var e=1,t=arguments,n=t.length;return i.replace(Yd,function(s){if(e>=n)return s;var r=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},on=function(i,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[i+"="+n];if(e.names)for(var r=0;r<e.names.length;r+=1){var o=e.names[r];e.name?s.push(t[e.name][o]):s.push(t[e.names[r]])}else s.push(t[e.name]);return Xd.apply(null,s)},Qd=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Zd=["i","c","b","a"],eh=function(i,e){e=e||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(r){r.payloads==null&&(r.payloads="")});var t=e.outerOrder||Qd,n=e.innerOrder||Zd,s=[];return t.forEach(function(r){Ts[r].forEach(function(o){o.name in i&&i[o.name]!=null?s.push(on(r,o,i)):o.push in i&&i[o.push]!=null&&i[o.push].forEach(function(a){s.push(on(r,o,a))})})}),i.media.forEach(function(r){s.push(on("m",Ts.m[0],r)),n.forEach(function(o){Ts[o].forEach(function(a){a.name in r&&r[a.name]!=null?s.push(on(o,a,r)):a.push in r&&r[a.push]!=null&&r[a.push].forEach(function(c){s.push(on(o,a,c))})})})}),s.join(`\r
|
|
52
|
+
`);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Kn(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.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 Yn(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var dd=Object.freeze({__proto__:null,removeExtmapAllowMixed:Gs,shimAddIceCandidateNullOrEmpty:Kn,shimConnectionState:zs,shimMaxMessageSize:Gn,shimParameterlessSetLocalDescription:Yn,shimRTCIceCandidate:zn,shimRTCIceCandidateRelayProtocol:Hs,shimSendThrowTypeError:Wn});function hd(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=ga,n=ad(i),s={browserDetails:n,commonShim:dd,extractVersion:Hn,disableLog:rd,disableWarnings:od,sdp:ld};switch(n.browser){case"chrome":if(!Wr||!qs||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Wr,Kn(i,n),Yn(i),ya(i,n),ba(i),qs(i,n),ka(i),Ea(i,n),Ca(i),Ta(i),Sa(i),Pa(i,n),zn(i),Hs(i),zs(i),Gn(i,n),Wn(i),Gs(i,n);break;case"firefox":if(!Kr||!$s||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=Kr,Kn(i,n),Yn(i),_a(i,n),$s(i,n),Ra(i),Ia(i),Oa(i),xa(i),Na(i),Aa(i),Ma(i),Da(i),La(i),zn(i),zs(i),Gn(i,n),Wn(i);break;case"safari":if(!Yr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Yr,Kn(i,n),Yn(i),Va(i),$a(i),ja(i),Ua(i),Fa(i),qa(i),Ba(i),Ha(i),zn(i),Hs(i),Gn(i,n),Wn(i),Gs(i,n);break;default:t("Unsupported browser!");break}return s}hd({window:typeof window>"u"?void 0:window});const fd=10,Fn="lk_e2ee",pd="LKFrameEncryptionKey",md={sharedKey:!1,ratchetSalt:pd,ratchetWindowSize:8,failureTolerance:fd};var bi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(bi||(bi={}));var Xr;(function(i){i.KeyRatcheted="keyRatcheted"})(Xr||(Xr={}));var vi;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(vi||(vi={}));var Qr;(function(i){i.Error="cryptorError"})(Qr||(Qr={}));function gd(){return vd()||Ws()}function Ws(){return typeof window.RTCRtpScriptTransform<"u"}function vd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Bh extends wt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{$.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},md),e),this.on(bi.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(bi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(bi.RatchetRequest,e,t)}}class Yi extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class te extends Yi{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class mr extends Yi{constructor(e){super(21,e??"device is unsupported")}}class st extends Yi{constructor(e){super(20,e??"track is invalid")}}class yd extends Yi{constructor(e){super(10,e??"unsupported server")}}class he extends Yi{constructor(e){super(12,e??"unexpected connection state")}}class Ks extends Yi{constructor(e){super(13,e??"unable to negotiate")}}var ts;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(ts||(ts={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(ts||(ts={}));var _;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged"})(_||(_={}));var N;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded"})(N||(N={}));var I;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished"})(I||(I={}));var R;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed"})(R||(R={}));function gr(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,u=Date.now(),l=[];function h(){if(c!==void 0){var p=Date.now()-u;if(p+e>=c)return c-p}return e}var f=function(){var p=[].slice.call(arguments),y=this;return new Promise(function(v,w){var S=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,u=Date.now(),!o){var J=i.apply(y,p);a&&a(J),l.forEach(function(K){return(0,K.resolve)(J)}),l=[]}},h()),S){var E=i.apply(y,p);return a&&a(E),v(E)}l.push({resolve:v,reject:w})})};return f.cancel=function(p){r!==void 0&&clearTimeout(r),l.forEach(function(y){return(0,y.reject)(p)}),l=[]},f}const bd=/version\/(\d+(\.?_?\d+)+)/i;let ys;function ki(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;const t=(i??navigator.userAgent).toLowerCase();if(ys===void 0||e){const n=kd.find(s=>{let{test:r}=s;return r.test(t)});ys=n==null?void 0:n.describe(t)}return ys}const kd=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:bs(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:bs(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:bs(bd,i),os:i.includes("mobile/")?"iOS":"macOS"}}}];function bs(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}var Cd="2.0.2";const Td=Cd,Sd=12;class Te{}Te.setTimeout=function(){return setTimeout(...arguments)};Te.setInterval=function(){return setInterval(...arguments)};Te.clearTimeout=function(){return clearTimeout(...arguments)};Te.clearInterval=function(){return clearInterval(...arguments)};class X{constructor(e,t,n,s,r){this.width=e,this.height=t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const wd=["vp8","h264"],Wa=["vp8","h264","vp9","av1"];function Ed(i){return!!wd.find(e=>e===i)}var Ys;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:2e4},i.music={maxBitrate:32e3},i.musicStereo={maxBitrate:48e3},i.musicHighQuality={maxBitrate:64e3},i.musicHighQualityStereo={maxBitrate:96e3}})(Ys||(Ys={}));const Pn={h90:new X(160,90,9e4,20),h180:new X(320,180,16e4,20),h216:new X(384,216,18e4,20),h360:new X(640,360,45e4,20),h540:new X(960,540,8e5,25),h720:new X(1280,720,17e5,30),h1080:new X(1920,1080,3e6,30),h1440:new X(2560,1440,5e6,30),h2160:new X(3840,2160,8e6,30)},Xs={h120:new X(160,120,7e4,20),h180:new X(240,180,125e3,20),h240:new X(320,240,14e4,20),h360:new X(480,360,33e4,20),h480:new X(640,480,5e5,20),h540:new X(720,540,6e5,25),h720:new X(960,720,13e5,30),h1080:new X(1440,1080,23e5,30),h1440:new X(1920,1440,38e5,30)},vr={h360fps3:new X(640,360,2e5,3,"medium"),h360fps15:new X(640,360,4e5,15,"medium"),h720fps5:new X(1280,720,8e5,5,"medium"),h720fps15:new X(1280,720,15e5,15,"medium"),h720fps30:new X(1280,720,2e6,30,"medium"),h1080fps15:new X(1920,1080,25e5,15,"medium"),h1080fps30:new X(1920,1080,5e6,30,"medium"),original:new X(0,0,7e6,30,"medium")};var we;(function(i){i[i.PUBLISHER=0]="PUBLISHER",i[i.SUBSCRIBER=1]="SUBSCRIBER"})(we||(we={}));d.util.setEnumType(we,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]);var Pi;(function(i){i[i.ACTIVE=0]="ACTIVE",i[i.PAUSED=1]="PAUSED"})(Pi||(Pi={}));d.util.setEnumType(Pi,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);var is;(function(i){i[i.UDP=0]="UDP",i[i.TCP=1]="TCP",i[i.TLS=2]="TLS"})(is||(is={}));d.util.setEnumType(is,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class jt extends x{constructor(e){super(),this.message={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new jt().fromBinary(e,t)}static fromJson(e,t){return new jt().fromJson(e,t)}static fromJsonString(e,t){return new jt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(jt,e,t)}}jt.runtime=d;jt.typeName="livekit.SignalRequest";jt.fields=d.util.newFieldList(()=>[{no:1,name:"offer",kind:"message",T:Re,oneof:"message"},{no:2,name:"answer",kind:"message",T:Re,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ke,oneof:"message"},{no:4,name:"add_track",kind:"message",T:We,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ye,oneof:"message"},{no:6,name:"subscription",kind:"message",T:je,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:pt,oneof:"message"},{no:8,name:"leave",kind:"message",T:Be,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:mt,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:bt,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:kt,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ke,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:gt,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Tt,oneof:"message"}]);class ft extends x{constructor(e){super(),this.message={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new ft().fromBinary(e,t)}static fromJson(e,t){return new ft().fromJson(e,t)}static fromJsonString(e,t){return new ft().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ft,e,t)}}ft.runtime=d;ft.typeName="livekit.SignalResponse";ft.fields=d.util.newFieldList(()=>[{no:1,name:"join",kind:"message",T:Bt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Re,oneof:"message"},{no:3,name:"offer",kind:"message",T:Re,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ke,oneof:"message"},{no:5,name:"update",kind:"message",T:qt,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xe,oneof:"message"},{no:8,name:"leave",kind:"message",T:Be,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ye,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:$t,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ht,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Gt,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Kt,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Xt,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Qt,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Vt,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Jt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Zt,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ii,oneof:"message"}]);class Ge extends x{constructor(e){super(),this.codec="",this.cid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Ge().fromBinary(e,t)}static fromJson(e,t){return new Ge().fromJson(e,t)}static fromJsonString(e,t){return new Ge().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ge,e,t)}}Ge.runtime=d;Ge.typeName="livekit.SimulcastCodec";Ge.fields=d.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]);class We extends x{constructor(e){super(),this.cid="",this.name="",this.type=Se.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=ce.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=Ce.NONE,this.stream="",d.util.initPartial(e,this)}static fromBinary(e,t){return new We().fromBinary(e,t)}static fromJson(e,t){return new We().fromJson(e,t)}static fromJsonString(e,t){return new We().fromJsonString(e,t)}static equals(e,t){return d.util.equals(We,e,t)}}We.runtime=d;We.typeName="livekit.AddTrackRequest";We.fields=d.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:d.getEnumType(Se)},{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:d.getEnumType(ce)},{no:9,name:"layers",kind:"message",T:_e,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Ge,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:d.getEnumType(Ce)},{no:15,name:"stream",kind:"scalar",T:9}]);class Ke extends x{constructor(e){super(),this.candidateInit="",this.target=we.PUBLISHER,d.util.initPartial(e,this)}static fromBinary(e,t){return new Ke().fromBinary(e,t)}static fromJson(e,t){return new Ke().fromJson(e,t)}static fromJsonString(e,t){return new Ke().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ke,e,t)}}Ke.runtime=d;Ke.typeName="livekit.TrickleRequest";Ke.fields=d.util.newFieldList(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:d.getEnumType(we)}]);class Ye extends x{constructor(e){super(),this.sid="",this.muted=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Ye().fromBinary(e,t)}static fromJson(e,t){return new Ye().fromJson(e,t)}static fromJsonString(e,t){return new Ye().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ye,e,t)}}Ye.runtime=d;Ye.typeName="livekit.MuteTrackRequest";Ye.fields=d.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]);class Bt extends x{constructor(e){super(),this.otherParticipants=[],this.serverVersion="",this.iceServers=[],this.subscriberPrimary=!1,this.alternativeUrl="",this.serverRegion="",this.pingTimeout=0,this.pingInterval=0,this.sifTrailer=new Uint8Array(0),d.util.initPartial(e,this)}static fromBinary(e,t){return new Bt().fromBinary(e,t)}static fromJson(e,t){return new Bt().fromJson(e,t)}static fromJsonString(e,t){return new Bt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Bt,e,t)}}Bt.runtime=d;Bt.typeName="livekit.JoinResponse";Bt.fields=d.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Ki},{no:2,name:"participant",kind:"message",T:Le},{no:3,name:"other_participants",kind:"message",T:Le,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:vt,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:ut},{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:Lt},{no:13,name:"sif_trailer",kind:"scalar",T:12}]);class Jt extends x{constructor(e){super(),this.iceServers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Jt().fromBinary(e,t)}static fromJson(e,t){return new Jt().fromJson(e,t)}static fromJsonString(e,t){return new Jt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Jt,e,t)}}Jt.runtime=d;Jt.typeName="livekit.ReconnectResponse";Jt.fields=d.util.newFieldList(()=>[{no:1,name:"ice_servers",kind:"message",T:vt,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ut}]);class Xe extends x{constructor(e){super(),this.cid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Xe().fromBinary(e,t)}static fromJson(e,t){return new Xe().fromJson(e,t)}static fromJsonString(e,t){return new Xe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Xe,e,t)}}Xe.runtime=d;Xe.typeName="livekit.TrackPublishedResponse";Xe.fields=d.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ie}]);class Vt extends x{constructor(e){super(),this.trackSid="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Vt().fromBinary(e,t)}static fromJson(e,t){return new Vt().fromJson(e,t)}static fromJsonString(e,t){return new Vt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Vt,e,t)}}Vt.runtime=d;Vt.typeName="livekit.TrackUnpublishedResponse";Vt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);class Re extends x{constructor(e){super(),this.type="",this.sdp="",d.util.initPartial(e,this)}static fromBinary(e,t){return new Re().fromBinary(e,t)}static fromJson(e,t){return new Re().fromJson(e,t)}static fromJsonString(e,t){return new Re().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Re,e,t)}}Re.runtime=d;Re.typeName="livekit.SessionDescription";Re.fields=d.util.newFieldList(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]);class qt extends x{constructor(e){super(),this.participants=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new qt().fromBinary(e,t)}static fromJson(e,t){return new qt().fromJson(e,t)}static fromJsonString(e,t){return new qt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(qt,e,t)}}qt.runtime=d;qt.typeName="livekit.ParticipantUpdate";qt.fields=d.util.newFieldList(()=>[{no:1,name:"participants",kind:"message",T:Le,repeated:!0}]);class je extends x{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new je().fromBinary(e,t)}static fromJson(e,t){return new je().fromJson(e,t)}static fromJsonString(e,t){return new je().fromJsonString(e,t)}static equals(e,t){return d.util.equals(je,e,t)}}je.runtime=d;je.typeName="livekit.UpdateSubscription";je.fields=d.util.newFieldList(()=>[{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:ct,repeated:!0}]);class pt extends x{constructor(e){super(),this.trackSids=[],this.disabled=!1,this.quality=ci.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new pt().fromBinary(e,t)}static fromJson(e,t){return new pt().fromJson(e,t)}static fromJsonString(e,t){return new pt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(pt,e,t)}}pt.runtime=d;pt.typeName="livekit.UpdateTrackSettings";pt.fields=d.util.newFieldList(()=>[{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:d.getEnumType(ci)},{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}]);class Be extends x{constructor(e){super(),this.canReconnect=!1,this.reason=si.UNKNOWN_REASON,this.action=_n.DISCONNECT,d.util.initPartial(e,this)}static fromBinary(e,t){return new Be().fromBinary(e,t)}static fromJson(e,t){return new Be().fromJson(e,t)}static fromJsonString(e,t){return new Be().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Be,e,t)}}Be.runtime=d;Be.typeName="livekit.LeaveRequest";Be.fields=d.util.newFieldList(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:d.getEnumType(si)},{no:3,name:"action",kind:"enum",T:d.getEnumType(_n)},{no:4,name:"regions",kind:"message",T:ei}]);var _n;(function(i){i[i.DISCONNECT=0]="DISCONNECT",i[i.RESUME=1]="RESUME",i[i.RECONNECT=2]="RECONNECT"})(_n||(_n={}));d.util.setEnumType(_n,"livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]);class mt extends x{constructor(e){super(),this.trackSid="",this.layers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new mt().fromBinary(e,t)}static fromJson(e,t){return new mt().fromJson(e,t)}static fromJsonString(e,t){return new mt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(mt,e,t)}}mt.runtime=d;mt.typeName="livekit.UpdateVideoLayers";mt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:_e,repeated:!0}]);class gt extends x{constructor(e){super(),this.metadata="",this.name="",d.util.initPartial(e,this)}static fromBinary(e,t){return new gt().fromBinary(e,t)}static fromJson(e,t){return new gt().fromJson(e,t)}static fromJsonString(e,t){return new gt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(gt,e,t)}}gt.runtime=d;gt.typeName="livekit.UpdateParticipantMetadata";gt.fields=d.util.newFieldList(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]);class vt extends x{constructor(e){super(),this.urls=[],this.username="",this.credential="",d.util.initPartial(e,this)}static fromBinary(e,t){return new vt().fromBinary(e,t)}static fromJson(e,t){return new vt().fromJson(e,t)}static fromJsonString(e,t){return new vt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(vt,e,t)}}vt.runtime=d;vt.typeName="livekit.ICEServer";vt.fields=d.util.newFieldList(()=>[{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}]);class $t extends x{constructor(e){super(),this.speakers=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new $t().fromBinary(e,t)}static fromJson(e,t){return new $t().fromJson(e,t)}static fromJsonString(e,t){return new $t().fromJsonString(e,t)}static equals(e,t){return d.util.equals($t,e,t)}}$t.runtime=d;$t.typeName="livekit.SpeakersChanged";$t.fields=d.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:ot,repeated:!0}]);class Ht extends x{constructor(e){super(),d.util.initPartial(e,this)}static fromBinary(e,t){return new Ht().fromBinary(e,t)}static fromJson(e,t){return new Ht().fromJson(e,t)}static fromJsonString(e,t){return new Ht().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ht,e,t)}}Ht.runtime=d;Ht.typeName="livekit.RoomUpdate";Ht.fields=d.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Ki}]);class zt extends x{constructor(e){super(),this.participantSid="",this.quality=Nt.POOR,this.score=0,d.util.initPartial(e,this)}static fromBinary(e,t){return new zt().fromBinary(e,t)}static fromJson(e,t){return new zt().fromJson(e,t)}static fromJsonString(e,t){return new zt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(zt,e,t)}}zt.runtime=d;zt.typeName="livekit.ConnectionQualityInfo";zt.fields=d.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:d.getEnumType(Nt)},{no:3,name:"score",kind:"scalar",T:2}]);class Gt extends x{constructor(e){super(),this.updates=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Gt().fromBinary(e,t)}static fromJson(e,t){return new Gt().fromJson(e,t)}static fromJsonString(e,t){return new Gt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Gt,e,t)}}Gt.runtime=d;Gt.typeName="livekit.ConnectionQualityUpdate";Gt.fields=d.util.newFieldList(()=>[{no:1,name:"updates",kind:"message",T:zt,repeated:!0}]);class Wt extends x{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=Pi.ACTIVE,d.util.initPartial(e,this)}static fromBinary(e,t){return new Wt().fromBinary(e,t)}static fromJson(e,t){return new Wt().fromJson(e,t)}static fromJsonString(e,t){return new Wt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Wt,e,t)}}Wt.runtime=d;Wt.typeName="livekit.StreamStateInfo";Wt.fields=d.util.newFieldList(()=>[{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:d.getEnumType(Pi)}]);class Kt extends x{constructor(e){super(),this.streamStates=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Kt().fromBinary(e,t)}static fromJson(e,t){return new Kt().fromJson(e,t)}static fromJsonString(e,t){return new Kt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Kt,e,t)}}Kt.runtime=d;Kt.typeName="livekit.StreamStateUpdate";Kt.fields=d.util.newFieldList(()=>[{no:1,name:"stream_states",kind:"message",T:Wt,repeated:!0}]);class Qe extends x{constructor(e){super(),this.quality=ci.LOW,this.enabled=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Qe().fromBinary(e,t)}static fromJson(e,t){return new Qe().fromJson(e,t)}static fromJsonString(e,t){return new Qe().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Qe,e,t)}}Qe.runtime=d;Qe.typeName="livekit.SubscribedQuality";Qe.fields=d.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:d.getEnumType(ci)},{no:2,name:"enabled",kind:"scalar",T:8}]);class Yt extends x{constructor(e){super(),this.codec="",this.qualities=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Yt().fromBinary(e,t)}static fromJson(e,t){return new Yt().fromJson(e,t)}static fromJsonString(e,t){return new Yt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Yt,e,t)}}Yt.runtime=d;Yt.typeName="livekit.SubscribedCodec";Yt.fields=d.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Qe,repeated:!0}]);class Xt extends x{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new Xt().fromBinary(e,t)}static fromJson(e,t){return new Xt().fromJson(e,t)}static fromJsonString(e,t){return new Xt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Xt,e,t)}}Xt.runtime=d;Xt.typeName="livekit.SubscribedQualityUpdate";Xt.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Qe,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Yt,repeated:!0}]);class yt extends x{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",d.util.initPartial(e,this)}static fromBinary(e,t){return new yt().fromBinary(e,t)}static fromJson(e,t){return new yt().fromJson(e,t)}static fromJsonString(e,t){return new yt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(yt,e,t)}}yt.runtime=d;yt.typeName="livekit.TrackPermission";yt.fields=d.util.newFieldList(()=>[{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}]);class bt extends x{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new bt().fromBinary(e,t)}static fromJson(e,t){return new bt().fromJson(e,t)}static fromJsonString(e,t){return new bt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(bt,e,t)}}bt.runtime=d;bt.typeName="livekit.SubscriptionPermission";bt.fields=d.util.newFieldList(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:yt,repeated:!0}]);class Qt extends x{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,d.util.initPartial(e,this)}static fromBinary(e,t){return new Qt().fromBinary(e,t)}static fromJson(e,t){return new Qt().fromJson(e,t)}static fromJsonString(e,t){return new Qt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Qt,e,t)}}Qt.runtime=d;Qt.typeName="livekit.SubscriptionPermissionUpdate";Qt.fields=d.util.newFieldList(()=>[{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}]);class kt extends x{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],this.trackSidsDisabled=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new kt().fromBinary(e,t)}static fromJson(e,t){return new kt().fromJson(e,t)}static fromJsonString(e,t){return new kt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(kt,e,t)}}kt.runtime=d;kt.typeName="livekit.SyncState";kt.fields=d.util.newFieldList(()=>[{no:1,name:"answer",kind:"message",T:Re},{no:2,name:"subscription",kind:"message",T:je},{no:3,name:"publish_tracks",kind:"message",T:Xe,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ct,repeated:!0},{no:5,name:"offer",kind:"message",T:Re},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]);class Ct extends x{constructor(e){super(),this.label="",this.id=0,this.target=we.PUBLISHER,d.util.initPartial(e,this)}static fromBinary(e,t){return new Ct().fromBinary(e,t)}static fromJson(e,t){return new Ct().fromJson(e,t)}static fromJsonString(e,t){return new Ct().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Ct,e,t)}}Ct.runtime=d;Ct.typeName="livekit.DataChannelInfo";Ct.fields=d.util.newFieldList(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:d.getEnumType(we)}]);class ke extends x{constructor(e){super(),this.scenario={case:void 0},d.util.initPartial(e,this)}static fromBinary(e,t){return new ke().fromBinary(e,t)}static fromJson(e,t){return new ke().fromJson(e,t)}static fromJsonString(e,t){return new ke().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ke,e,t)}}ke.runtime=d;ke.typeName="livekit.SimulateScenario";ke.fields=d.util.newFieldList(()=>[{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:d.getEnumType(is),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"}]);class Tt extends x{constructor(e){super(),this.timestamp=F.zero,this.rtt=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new Tt().fromBinary(e,t)}static fromJson(e,t){return new Tt().fromJson(e,t)}static fromJsonString(e,t){return new Tt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Tt,e,t)}}Tt.runtime=d;Tt.typeName="livekit.Ping";Tt.fields=d.util.newFieldList(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]);class Zt extends x{constructor(e){super(),this.lastPingTimestamp=F.zero,this.timestamp=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new Zt().fromBinary(e,t)}static fromJson(e,t){return new Zt().fromJson(e,t)}static fromJsonString(e,t){return new Zt().fromJsonString(e,t)}static equals(e,t){return d.util.equals(Zt,e,t)}}Zt.runtime=d;Zt.typeName="livekit.Pong";Zt.fields=d.util.newFieldList(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]);class ei extends x{constructor(e){super(),this.regions=[],d.util.initPartial(e,this)}static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ei,e,t)}}ei.runtime=d;ei.typeName="livekit.RegionSettings";ei.fields=d.util.newFieldList(()=>[{no:1,name:"regions",kind:"message",T:ti,repeated:!0}]);class ti extends x{constructor(e){super(),this.region="",this.url="",this.distance=F.zero,d.util.initPartial(e,this)}static fromBinary(e,t){return new ti().fromBinary(e,t)}static fromJson(e,t){return new ti().fromJson(e,t)}static fromJsonString(e,t){return new ti().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ti,e,t)}}ti.runtime=d;ti.typeName="livekit.RegionInfo";ti.fields=d.util.newFieldList(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]);class ii extends x{constructor(e){super(),this.trackSid="",this.err=wn.SE_UNKNOWN,d.util.initPartial(e,this)}static fromBinary(e,t){return new ii().fromBinary(e,t)}static fromJson(e,t){return new ii().fromJson(e,t)}static fromJsonString(e,t){return new ii().fromJsonString(e,t)}static equals(e,t){return d.util.equals(ii,e,t)}}ii.runtime=d;ii.typeName="livekit.SubscriptionResponse";ii.fields=d.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:d.getEnumType(wn)}]);function Pd(i){if(!(typeof i>"u"))return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}const _d=5e3,sn=[];var Je;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Je||(Je={}));class C extends wt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=$,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),_d):this.handleAppVisibilityChanged()},this.log=ai((s=n.loggerName)!==null&&s!==void 0?s:St.Track),this.loggerContextCb=n.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)),ie(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&&C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(sn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&sn.splice(sn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ji(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?R.AudioPlaybackStarted:R.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?R.AudioPlaybackFailed:R.VideoPlaybackFailed,r):r.name==="AbortError"?$.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):$.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){qi(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(R.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{qi(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(R.ElementDetached,n)}),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)}updateLoggerOptions(e){e.loggerName&&(this.log=ai(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sn.forEach(n=>{n.parentElement||(t=!1)}),t&&sn.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){Ne()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ne()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ji(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!_i()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(_i()||Wi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function qi(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(u){u.Audio="audio",u.Video="video",u.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(u){u.Camera="camera",u.Microphone="microphone",u.ScreenShare="screen_share",u.ScreenShareAudio="screen_share_audio",u.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(u){u.Active="active",u.Paused="paused",u.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(u){switch(u){case e.Audio:return Se.AUDIO;case e.Video:return Se.VIDEO;default:return Se.DATA}}i.kindToProto=s;function r(u){switch(u){case Se.AUDIO:return e.Audio;case Se.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(u){switch(u){case t.Camera:return ce.CAMERA;case t.Microphone:return ce.MICROPHONE;case t.ScreenShare:return ce.SCREEN_SHARE;case t.ScreenShareAudio:return ce.SCREEN_SHARE_AUDIO;default:return ce.UNKNOWN}}i.sourceToProto=o;function a(u){switch(u){case ce.CAMERA:return t.Camera;case ce.MICROPHONE:return t.Microphone;case ce.SCREEN_SHARE:return t.ScreenShare;case ce.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(u){switch(u){case Pi.ACTIVE:return n.Active;case Pi.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(C||(C={}));function Ka(i,e,t){var n;const s=(n=Pd(i))!==null&&n!==void 0?n:{};return s.audio===!0&&(s.audio={}),s.video===!0&&(s.video={}),s.audio&&Qs(s.audio,e),s.video&&Qs(s.video,t),s}function Qs(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function ls(i){const e={};if(i.video)if(typeof i.video=="object"){const t={},n=t,s=i.video;Object.keys(s).forEach(r=>{switch(r){case"resolution":Qs(n,s.resolution);break;default:n[r]=s[r]}}),e.video=t}else e.video=i.video;else e.video=!1;return i.audio?typeof i.audio=="object"?e.audio=i.audio:e.audio=!0:e.audio=!1,e}function Rd(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return m(this,void 0,void 0,function*(){const t=Ya();if(t){const n=t.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);t.createMediaStreamSource(new MediaStream([i.mediaStreamTrack])).connect(n),yield ri(e),n.getByteTimeDomainData(r);const a=r.some(c=>c!==128&&c!==0);return t.close(),!a}return!1})}function Ya(){const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(i)return new i({latencyHint:"interactive"})}function Od(i){return i===C.Source.Microphone?"audioinput":i===C.Source.Camera?"videoinput":void 0}function xd(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,_i()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio}}function Xa(i){const e=i.split("/")[1].toLowerCase();if(!Wa.includes(e))throw Error("Video codec not supported: ".concat(e));return e}function Id(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Xe({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ie(i){return i instanceof C?{trackSid:i.sid,trackSource:i.source,trackMuted:i.isMuted,trackEnabled:i.mediaStreamTrack.enabled,trackKind:i.kind}:{trackSid:i.trackSid,trackName:i.trackName,track:i.track?ie(i.track):void 0,trackEnabled:i.isEnabled,trackEncrypted:i.isEncrypted,trackMimeType:i.mimeType}}const Nd="|",Zr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ad(i){const e=i.split(Nd);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ri(i){return m(this,void 0,void 0,function*(){return new Promise(e=>Te.setTimeout(e,i))})}function eo(){return"addTransceiver"in RTCPeerConnection.prototype}function to(){return"addTrack"in RTCPeerConnection.prototype}function Md(){if(!("getCapabilities"in RTCRtpSender)||_i())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Dd(){if(!("getCapabilities"in RTCRtpSender)||Wi())return!1;if(_i()){const t=ki();if(t!=null&&t.version&&yr(t.version,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function gn(i){return i==="av1"||i==="vp9"}function Zs(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}const Ld={Chrome:"100",Safari:"15",Firefox:"100"};function Ud(i){if(!Ne()||!("setCodecPreferences"in i))return!1;const e=ki();if(!(e!=null&&e.name)||!e.version)return!1;const t=Ld[e.name];return t?yr(e.version,t)>=0:!1}function Wi(){var i;return((i=ki())===null||i===void 0?void 0:i.name)==="Firefox"}function _i(){var i;return((i=ki())===null||i===void 0?void 0:i.name)==="Safari"}function Fd(){const i=ki();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")}function Qa(){return Ne()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Ne(){return typeof document<"u"}function Ri(){return navigator.product=="ReactNative"}function er(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function Za(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ec(){if(!Ri())return;let i=Za();if(i)return i.platform}function io(){if(Ne())return window.devicePixelRatio;if(Ri()){let i=Za();if(i)return i.devicePixelRatio}return 1}function yr(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function jd(i){for(const e of i)e.target.handleResize(e)}function Bd(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ks=null;const no=()=>(ks||(ks=new ResizeObserver(jd)),ks);let Cs=null;const so=()=>(Cs||(Cs=new IntersectionObserver(Bd,{root:null,rootMargin:"0px"})),Cs);function Jd(){var i;const e=new Ut({sdk:Gi.JS,protocol:Sd,version:Td});return Ri()&&(e.os=(i=ec())!==null&&i!==void 0?i:""),e}function ro(){let i=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,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let rn;function Ts(){if(!rn){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[rn]=n.stream.getAudioTracks(),!rn)throw Error("Could not get empty media stream audio track");rn.enabled=!1}return rn.clone()}class tc{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,s)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}class Ze{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Vd(i){return Wa.includes(i)}function Si(i){if(typeof i=="string")return i;if(Array.isArray(i))return i[0];if(i.exact)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function qd(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function oo(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}const ao="default";class Pe{static getInstance(){return this.instance===void 0&&(this.instance=new Pe),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n;return m(this,void 0,void 0,function*(){if(((n=Pe.userMediaPromiseMap)===null||n===void 0?void 0:n.size)>0){$.debug("awaiting getUserMedia promise");try{e?yield Pe.userMediaPromiseMap.get(e):yield Promise.all(Pe.userMediaPromiseMap.values())}catch{$.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&!(_i()&&this.hasDeviceInUse(e))&&(s.length===0||s.some(o=>{const a=o.label==="",c=e?o.kind===e:!0;return a&&c}))){const o={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},a=yield navigator.mediaDevices.getUserMedia(o);s=yield navigator.mediaDevices.enumerateDevices(),a.getTracks().forEach(c=>{c.stop()})}return e&&(s=s.filter(r=>r.kind===e)),s})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==ao)return t;const r=(yield this.getDevices(e)).find(o=>o.groupId===n&&o.deviceId!==ao);return r==null?void 0:r.deviceId})}hasDeviceInUse(e){return e?Pe.userMediaPromiseMap.has(e):Pe.userMediaPromiseMap.size>0}}Pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Pe.userMediaPromiseMap=new Map;const $d=1e3;class Rn extends C{get constraints(){return this._constraints}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=gr(()=>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=s,this.muteLock=new Ze,this.pauseUpstreamLock=new Ze,this.processorLock=new Ze,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return m(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{qi(this._mediaStreamTrack,s)}),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 n;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ji(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{s()}}this.sender&&(yield this.sender.replaceTrack(n??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{ji(n??e,s)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$d;var t;return m(this,void 0,void 0,function*(){if(this.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((t=ki())===null||t===void 0?void 0:t.os)==="iOS"&&(yield ri(10));const n=Date.now();for(;Date.now()-n<e;){const s=this.dimensions;if(s)return s;yield ri(50)}throw new st("unable to get track dimensions after timeout")})}getDeviceId(){return m(this,void 0,void 0,function*(){if(this.source===C.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),n=this.kind===C.Kind.Audio?"audioinput":"videoinput";return Pe.getInstance().normalizeDeviceId(n,e,t)})}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){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return m(this,void 0,void 0,function*(){if(!this.sender)throw new st("unable to replace an unpublished track");return this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){e||(e=this._constraints),this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const t={audio:!1,video:!1};this.kind===C.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach(r=>{qi(this.mediaStreamTrack,r)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const s=(yield navigator.mediaDevices.getUserMedia(t)).getTracks()[0];return s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(R.Restarted,this),this})}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),Qa()&&(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;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*(){const e=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 t=ki();if((t==null?void 0:t.name)==="Safari"&&yr(t.version,"12.0")<0)throw new mr("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){const e=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),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return m(this,void 0,void 0,function*(){return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n,s;return m(this,void 0,void 0,function*(){const r=yield this.processorLock.lock();try{if(this.log.debug("setting up processor",this.logContext),this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement=(n=this.processorElement)!==null&&n!==void 0?n:document.createElement(this.kind),ji(this._mediaStreamTrack,this.processorElement),this.processorElement.muted=!0,this.processorElement.play().catch(a=>this.log.error("failed to play processor element",Object.assign(Object.assign({},this.logContext),{error:a})));const o={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement,audioContext:this.audioContext};if(yield e.init(o),this.processor=e,this.processor.processedTrack){for(const a of this.attachedElements)a!==this.processorElement&&t&&(qi(this._mediaStreamTrack,a),ji(this.processor.processedTrack,a));yield(s=this.sender)===null||s===void 0?void 0:s.replaceTrack(this.processor.processedTrack)}}finally{r()}})}getProcessor(){return this.processor}stopProcessor(){var e,t;return m(this,void 0,void 0,function*(){this.processor&&(this.log.debug("stopping processor",this.logContext),(e=this.processor.processedTrack)===null||e===void 0||e.stop(),yield this.processor.destroy(),this.processor=void 0,(t=this.processorElement)===null||t===void 0||t.remove(),this.processorElement=void 0,yield this.restart())})}}class Hd extends wt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:o}=t.data;switch(r){case"error":$.error(o.error.message),this.emit(vi.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(this.encryptionEnabled!==o.enabled&&o.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(vi.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(vi.ParticipantEncryptionStatusChanged,o.enabled,a)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"ratchetKey":this.keyProvider.emit(bi.KeyRatcheted,o.material,o.keyIndex);break}},this.onWorkerError=t=>{$.error("e2ee worker encountered an error:",{error:t.error}),this.emit(vi.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!gd())throw new mr("tried to setup end-to-end encryption on an unsupported browser");if($.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&($.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){$.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?$.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(I.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(_.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Ce.NONE,s.identity)),e.on(_.ConnectionStateChanged,n=>{n===Y.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Ce.NONE,s.identity)})})}).on(_.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(_.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(_.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),t.getKeys().forEach(n=>{this.postKey(n)})}),e.localParticipant.on(N.LocalTrackPublished,n=>m(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(bi.SetKey,n=>this.postKey(n)).on(bi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Xa(n.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof Rn)||!t){t||$.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return m(this,void 0,void 0,function*(){if(this.worker){if(Ws()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Fn in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(a,[o,r])}e[Fn]=!0}})}handleSender(e,t,n){var s;if(!(Fn 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(Ws()){$.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{$.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(o,[r.readable,r.writable])}e[Fn]=!0}}}var vn;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(vn||(vn={}));class zd{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ze,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:vn.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=vn.RUNNING,yield e()}finally{t.status=vn.COMPLETED,this.pendingTasks.delete(t.id),n()}})}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())}}const Gd=["syncState","trickle","offer","answer","simulate","leave"];function Wd(i){const e=Gd.indexOf(i.case)>=0;return $.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var re;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(re||(re={}));class br{get currentState(){return this.state}get isDisconnected(){return this.state===re.DISCONNECTING||this.state===re.DISCONNECTED}get isEstablishingConnection(){return this.state===re.CONNECTING||this.state===re.RECONNECTING}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=re.DISCONNECTED,this.log=$,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.log=ai((n=t.loggerName)!==null&&n!==void 0?n:St.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new zd,this.queuedRequests=[],this.closingLock=new Ze,this.connectionLock=new Ze,this.state=re.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,n,s){return m(this,void 0,void 0,function*(){return this.state=re.CONNECTING,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=re.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}))})}connect(e,t,n,s){this.connectOptions=n,e=qd(e),e=e.replace(/\/$/,""),e+="/rtc";const r=Jd(),o=Kd(t,r,n);return new Promise((a,c)=>m(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const l=()=>m(this,void 0,void 0,function*(){this.close(),clearTimeout(h),c(new te("room connection has been cancelled (signal)"))}),h=setTimeout(()=>{this.close(),c(new te("room connection has timed out (signal)"))},n.websocketTimeout);s!=null&&s.aborted&&l(),s==null||s.addEventListener("abort",l),this.log.debug("connecting to ".concat(e+o),this.logContext),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(e+o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=f=>m(this,void 0,void 0,function*(){if(this.state!==re.CONNECTED){clearTimeout(h);try{const p=yield fetch("http".concat(e.substring(2),"/validate").concat(o));if(p.status.toFixed(0).startsWith("4")){const y=yield p.text();c(new te(y,0,p.status))}else c(new te("Internal error",2,p.status))}catch{c(new te("server was not reachable",1))}return}this.handleWSError(f)}),this.ws.onmessage=f=>m(this,void 0,void 0,function*(){var p,y,v,w;let S;if(typeof f.data=="string"){const E=JSON.parse(f.data);S=ft.fromJson(E,{ignoreUnknownFields:!0})}else if(f.data instanceof ArrayBuffer)S=ft.fromBinary(new Uint8Array(f.data));else{this.log.error("could not decode websocket message: ".concat(typeof f.data),this.logContext);return}if(this.state!==re.CONNECTED){let E=!1;if(((p=S.message)===null||p===void 0?void 0:p.case)==="join"?(this.state=re.CONNECTED,s==null||s.removeEventListener("abort",l),this.pingTimeoutDuration=S.message.value.pingTimeout,this.pingIntervalDuration=S.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),a(S.message.value)):this.state===re.RECONNECTING&&S.message.case!=="leave"?(this.state=re.CONNECTED,s==null||s.removeEventListener("abort",l),this.startPingInterval(),((y=S.message)===null||y===void 0?void 0:y.case)==="reconnect"?a((v=S.message)===null||v===void 0?void 0:v.value):(a(),E=!0)):this.isEstablishingConnection&&S.message.case==="leave"?c(new te("Received leave request while trying to (re)connect",4)):n.reconnect||c(new te("did not receive join response, got ".concat((w=S.message)===null||w===void 0?void 0:w.case," instead"))),!E)return}this.signalLatency&&(yield ri(this.signalLatency)),this.handleSignalResponse(S)}),this.ws.onclose=f=>{this.isEstablishingConnection&&c(new te("Websocket got closed during a (re)connection attempt")),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:f.reason,code:f.code,wasClean:f.wasClean,state:this.state})),this.handleOnClose(f.reason)}}finally{u()}}))}close(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return m(this,void 0,void 0,function*(){const t=yield this.closingLock.lock();try{if(e&&(this.state=re.DISCONNECTING),this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const n=new Promise(s=>{this.ws?this.ws.onclose=()=>{s()}:s()});this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([n,ri(250)])),this.ws=void 0}}finally{e&&(this.state=re.DISCONNECTED),this.clearPingInterval(),t()}})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ns(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ns(e)})}sendIceCandidate(e,t){return this.log.trace("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ke({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ye({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new gt({metadata:e,name:t})})}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 mt({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new bt({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:F.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Tt({timestamp:F.parse(Date.now()),rtt:F.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new Be({canReconnect:!1,reason:si.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return m(this,void 0,void 0,function*(){if(!t&&!Wd(e)&&this.state===re.RECONNECTING){this.queuedRequests.push(()=>m(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield ri(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){this.log.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case),this.logContext);return}const s=new jt({message:e});try{this.useJSON?this.ws.send(s.toJsonString()):this.ws.send(s.toBinary())}catch(r){this.log.error("error sending signal message",Object.assign(Object.assign({},this.logContext),{error:r}))}})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=co(s.value);this.onAnswer&&this.onAnswer(o)}else if(s.case==="offer"){const o=co(s.value);this.onOffer&&this.onOffer(o)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||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===re.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Te.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Te.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Te.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Te.clearInterval(this.pingInterval)}}function co(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function ns(i){return new Re({sdp:i.sdp,type:i.type})}function Kd(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Ri()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),"?".concat(s.toString())}var ic={},nc={exports:{}},uo=nc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var e="candidate:%s %d %s %d %s %d typ %s";return e+=i.raddr!=null?" raddr %s rport %d":"%v%v",e+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(e+=" generation %d"),e+=i["network-id"]!=null?" network-id %d":"%v",e+=i["network-cost"]!=null?" network-cost %d":"%v",e}},{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(i){var e="ssrc:%d";return i.attribute!=null&&(e+=" %s",i.value!=null&&(e+=":%s")),e}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var e="mediaclk:";return e+=i.id!=null?"id=%s %s":"%v%s",e+=i.mediaClockValue!=null?"=%s":"",e+=i.rateNumerator!=null?" rate=%s":"",e+=i.rateDenominator!=null?"/%s":"",e}},{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"]}]};Object.keys(uo).forEach(function(i){var e=uo[i];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var sc=nc.exports;(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,u,l){if(l&&!u)c[l]=e(a[1]);else for(var h=0;h<u.length;h+=1)a[h+1]!=null&&(c[u[h]]=e(a[h+1]))},n=function(a,c,u){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var h=a.push?{}:l?c[a.name]:c;t(u.match(a.reg),h,a.names,a.name),a.push&&c[a.push].push(h)},s=sc,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},u=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var f=h[0],p=h.slice(2);f==="m"&&(u.push({rtp:[],fmtp:[]}),l=u[u.length-1]);for(var y=0;y<(s[f]||[]).length;y+=1){var v=s[f][y];if(v.reg.test(p))return n(v,l,p)}}),c.media=u,c};var o=function(a,c){var u=c.split(/=(.+)/,2);return u.length===2?a[u[0]]=e(u[1]):u.length===1&&c.length>1&&(a[u[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],u=a.split(" ").map(e),l=0;l<u.length;l+=3)c.push({component:u[l],ip:u[l+1],port:u[l+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(u){var l,h=!1;return u[0]!=="~"?l=e(u):(l=e(u.substring(1,u.length)),h=!0),{scid:l,paused:h}})})}})(ic);var Ss=sc,Yd=/%[sdv%]/g,Xd=function(i){var e=1,t=arguments,n=t.length;return i.replace(Yd,function(s){if(e>=n)return s;var r=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},on=function(i,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[i+"="+n];if(e.names)for(var r=0;r<e.names.length;r+=1){var o=e.names[r];e.name?s.push(t[e.name][o]):s.push(t[e.names[r]])}else s.push(t[e.name]);return Xd.apply(null,s)},Qd=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Zd=["i","c","b","a"],eh=function(i,e){e=e||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(r){r.payloads==null&&(r.payloads="")});var t=e.outerOrder||Qd,n=e.innerOrder||Zd,s=[];return t.forEach(function(r){Ss[r].forEach(function(o){o.name in i&&i[o.name]!=null?s.push(on(r,o,i)):o.push in i&&i[o.push]!=null&&i[o.push].forEach(function(a){s.push(on(r,o,a))})})}),i.media.forEach(function(r){s.push(on("m",Ss.m[0],r)),n.forEach(function(o){Ss[o].forEach(function(a){a.name in r&&r[a.name]!=null?s.push(on(o,a,r)):a.push in r&&r[a.push]!=null&&r[a.push].forEach(function(c){s.push(on(o,a,c))})})})}),s.join(`\r
|
|
53
53
|
`)+`\r
|
|
54
|
-
`},th=tc,ih=eh,Ss=ih,ln=th.parse;const uo=.7,qi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class lo extends Et.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 n;super(),this.log=q,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=mr(s=>m(this,void 0,void 0,function*(){this.emit(qi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),100),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=ci((n=t.loggerName)!==null&&n!==void 0?n:wt.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.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){var t;return m(this,void 0,void 0,function*(){let n;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=sh(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=ln((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||r.mid!=o.transceiver.mid)return!1;let a=0;if(r.rtp.some(u=>u.codec.toUpperCase()===o.codec.toUpperCase()?(a=u.payload,!0):!1),a===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===a){u.config=u.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),c=!0;break}return c||o.maxbr>0&&r.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),n=Ss(s)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(qi.NegotiationComplete),e.sdp&&ln(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(qi.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){var t;return m(this,void 0,void 0,function*(){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"){const r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);else{this.renegotiate=!0;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 n=yield this.pc.createOffer(e),s=ln((t=n.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"?ho(r,[],[]):r.type==="video"&&(nh(r),this.trackBitrates.some(o=>{if(!r.msid||!o.cid||!r.msid.includes(o.cid))return!1;let a=0;if(r.rtp.some(u=>u.codec.toUpperCase()===o.codec.toUpperCase()?(a=u.payload,!0):!1),a===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===a){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(Math.round(o.maxbr*uo))),u.config.includes("x-google-max-bitrate")||(u.config+=";x-google-max-bitrate=".concat(o.maxbr)),c=!0;break}return c||r.fmtp.push({payload:a,config:"x-google-start-bitrate=".concat(Math.round(o.maxbr*uo),";x-google-max-bitrate=").concat(o.maxbr)}),!0}))}),yield this.setMungedSDP(n,Ss(s)),this.onOffer(n)})}createAndSetAnswer(){var e;return m(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),n=ln((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{s.type==="audio"&&ho(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ss(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new he("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 he("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()}getConnectedAddress(){var e;return m(this,void 0,void 0,function*(){if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Ws(r)}})}}function ho(i,e,t){let n=0;i.rtp.some(s=>s.codec==="opus"?(n=s.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(s=>s.payload===n&&s.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(s=>s.payload===n?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function nh(i){var e,t,n,s;const r=(t=(e=i.rtp[0])===null||e===void 0?void 0:e.codec)===null||t===void 0?void 0:t.toLowerCase();if(!gn(r))return;let o=0;((n=i.ext)===null||n===void 0?void 0:n.some(c=>c.uri===Qr?!0:(c.value>o&&(o=c.value),!1)))||(s=i.ext)===null||s===void 0||s.push({value:o+1,uri:Qr})}function sh(i){var e;const t=[],n=[],s=ln((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===r&&c.type==="nack")&&n.push(o.mid),o.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(o.mid),!0):!1))}),{stereoMids:t,nackMids:n}}const er="vp8",rh={audioPreset:Ks.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:gr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:er,backupCodec:!0},sc={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},rc={resolution:Pn.h720.resolution},oh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ql,disconnectOnPageLeave:!0,webAudioMix:!0},br={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var pe;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(pe||(pe={}));class ah{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=br.peerConnectionTimeout,this.log=q,this.updateState=()=>{var r;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=pe.CONNECTED:a.some(c=>c==="failed")?this.state=pe.FAILED:a.some(c=>c==="connecting")?this.state=pe.CONNECTING:a.every(c=>c==="closed")?this.state=pe.CLOSED:a.some(c=>c==="closed")?this.state=pe.CLOSING:a.every(c=>c==="new")&&(this.state=pe.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(pe[o]," to ").concat(pe[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=ci((s=n.loggerName)!==null&&s!==void 0?s:wt.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new lo(e,n),this.subscriber=new lo(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,we.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=r=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r)},this.state=pe.NEW,this.connectionLock=new Ze}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){return this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()})),yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var n;return m(this,void 0,void 0,function*(){const s=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const s=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(qi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(qi.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),n(o)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return m(this,void 0,void 0,function*(){if(e.getConnectionState()!=="connected")return new Promise((r,o)=>m(this,void 0,void 0,function*(){const a=()=>{this.log.warn("abort transport connection",this.logContext),ke.clearTimeout(c),o(new te("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&a(),t==null||t.signal.addEventListener("abort",a);const c=ke.setTimeout(()=>{t==null||t.signal.removeEventListener("abort",a),o(new te("could not establish pc connection"))},n);for(;this.state!==pe.CONNECTED;)if(yield oi(50),t!=null&&t.signal.aborted){o(new te("room connection has been cancelled",3));return}ke.clearTimeout(c),t==null||t.signal.removeEventListener("abort",a),r()}))})}}const fo="_lossy",po="_reliable",ch=2*1e3,mo="leave-reconnect";var Ve;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Ve||(Ve={}));class uh extends Et.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=br.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ve.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=q,this.handleDataChannel=n=>{let{channel:s}=n;return m(this,void 0,void 0,function*(){if(s){if(s.label===po)this.reliableDCSub=s;else if(s.label===fo)this.lossyDCSub=s;else return;this.log.debug("on data channel ".concat(s.id,", ").concat(s.label),this.logContext),s.onmessage=this.handleDataMessage}})},this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var s,r;const o=yield this.dataProcessLock.lock();try{let a;if(n.data instanceof ArrayBuffer)a=n.data;else if(n.data instanceof Blob)a=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=ot.fromBinary(new Uint8Array(a));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(x.ActiveSpeakersUpdate,c.value.value.speakers):((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&this.emit(x.DataPacketReceived,c.value.value,c.kind)}finally{o()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?fe.LOSSY:fe.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(x.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===mo&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ke.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Ve.Connected&&n();const r=()=>{this.off(x.Disconnected,o),n()},o=()=>{this.off(x.Restarted,r),s()};this.once(x.Restarted,r),this.once(x.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(x.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===re.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(xt.RR_SIGNAL_DISCONNECTED))},this.log=ci((t=e.loggerName)!==null&&t!==void 0?t:wt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new yr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ze,this.dataProcessLock=new Ze,this.dcBufferStatus=new Map([[fe.LOSSY,!0],[fe.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(x.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(x.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(x.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(x.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(x.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(x.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(x.StreamStateChanged,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomSid:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,identity:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity}}join(e,t,n,s){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof te&&r.reason===1&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}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.emit(x.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){var e;return m(this,void 0,void 0,function*(){yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new rt("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new te("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){var e;return m(this,void 0,void 0,function*(){return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t;return m(this,void 0,void 0,function*(){if(this.pcManager&&this.pcManager.currentState!==pe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const n=this.makeRTCConfiguration(e);this.pcManager=new ah(n,e.subscriberPrimary,this.loggerOptions),this.emit(x.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,r)=>{this.client.sendIceCandidate(s,r)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,r,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),s===pe.CONNECTED){const a=this.pcState===Ve.New;this.pcState=Ve.Connected,a&&this.emit(x.Connected,e)}else s===pe.FAILED&&this.pcState===Ve.Connected&&(this.pcState=Ve.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?xt.RR_SUBSCRIBER_FAILED:xt.RR_PUBLISHER_FAILED))}),this.pcManager.onTrack=s=>{this.emit(x.MediaTrackAdded,s.track,s.streams[0],s.receiver)},this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.trace("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{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),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(x.LocalTrackUnpublished,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(x.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(x.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",xt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.handleDisconnect(mo)):(this.emit(x.Disconnected,e==null?void 0:e.reason),this.close()),this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason}))}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===et.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(fo,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(po,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,n){if(!("getCapabilities"in RTCRtpSender))return;const s=RTCRtpSender.getCapabilities(t);if(!s)return;this.log.debug("get sender capabilities",Object.assign(Object.assign({},this.logContext),{cap:s}));const r=[],o=[],a=[];s.codecs.forEach(c=>{const u=c.mimeType.toLowerCase();if(u==="audio/opus"){r.push(c);return}if(!(u==="video/".concat(n))){a.push(c);return}if(n==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(c):o.push(c);return}r.push(c)}),Ud(e)&&e.setCodecPreferences(r.concat(o,a))}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(Zr())return yield this.createTransceiverRTCRtpSender(e,t,n);if(eo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new he("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return m(this,void 0,void 0,function*(){if(Zr())return this.createSimulcastTransceiverSender(e,t,n,s);if(eo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new he("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream);const r={direction:"sendonly",streams:s};n&&(r.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r);return e.kind===C.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(o,e.kind,t.videoCodec),e.codec=t.videoCodec),o.sender})}createSimulcastTransceiverSender(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return this.setPreferredCodec(o,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){var t,n,s;return m(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){q.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===et.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:pe.NEW)===pe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof he?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Di||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",xt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(x.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){var t,n,s;return m(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new he("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(x.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Di;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof te&&o.reason===0?new he("could not reconnect, token might be expired"):new Di}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(x.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==re.CONNECTED)throw new Di("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(x.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){var t;return m(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new he("could not reconnect, url or token not saved");if(!this.pcManager)throw new he("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(x.Resuming);try{this.setupSignalClientCallbacks();const n=yield this.client.reconnect(this.url,this.token,this.participantSid,e);if(n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s)}}catch(n){let s="";throw n instanceof Error&&(s=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof te&&n.reason===0?new he("could not reconnect, token might be expired"):n instanceof te&&n.reason===4?n:new Di(s)}if(this.emit(x.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==re.CONNECTED)throw new Di("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(),this.emit(x.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Ve.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield oi(ch),!this.pcManager)throw new he("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ve.Connected}catch(e){throw this.pcState=Ve.Disconnected,new te("could not establish PC connection, ".concat(e.message))}})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(n),this.updateAndEmitDCBufferStatus(t)})}ensureDataTransportConnected(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;var n;return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("PC manager is closed");const s=t?this.pcManager.subscriber:this.pcManager.publisher,r=t?"Subscriber":"Publisher";if(!s)throw new te("".concat(r," connection not set"));!t&&!this.pcManager.publisher.isICEConnected&&this.pcManager.publisher.getICEConnectionState()!=="checking"&&this.negotiate();const o=this.dataChannelForKind(e,t);if((o==null?void 0:o.readyState)==="open")return;const a=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()<a;){if(s.isICEConnected&&((n=this.dataChannelForKind(e,t))===null||n===void 0?void 0:n.readyState)==="open")return;yield oi(50)}throw new te("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){yield this.ensureDataTransportConnected(e,!1)})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==pe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ws("PC manager is closed"));return}this.pcManager.requirePublisher();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(x.Closing,s),this.pcManager.publisher.once(qi.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();Vd(c)&&o.set(a.payload,c)}),this.emit(x.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Ws&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",xt.RR_UNKNOWN),t(r)}finally{this.off(x.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===fe.LOSSY)return this.lossyDCSub;if(e===fe.RELIABLE)return this.reliableDCSub}else{if(e===fe.LOSSY)return this.lossyDC;if(e===fe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(s=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,u=new Array;e.forEach(l=>{l.isDesired!==a&&c.push(l.trackSid),l.isEnabled||u.push(l.trackSid)}),this.client.sendSyncState(new Ct({answer:r?is({sdp:r.sdp,type:r.type}):void 0,offer:o?is({sdp:o.sdp,type:o.type}):void 0,subscription:new Fe({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:Id(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Tt({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(fe.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(fe.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(fe.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(fe.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ke.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ie()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ie()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Di extends Error{}class go{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Zs(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(s=>s.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),q.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(lh(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function lh(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}const kr=2e3;function ls(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}class Me extends Rn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,n,r),this.stopOnMute=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=ls(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.checkForSilence()}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||wi(e)===this.mediaStreamTrack.getSettings().deviceId)})}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.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{const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==wi(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=us({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Ie()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},kr)))}setProcessor(e){var t;return m(this,void 0,void 0,function*(){const n=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack))}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return m(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Rd(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(_.AudioSilenceDetected)),e})}}function oc(i,e,t){switch(i.kind){case"audio":return new Me(i,e,!1,void 0,t);case"video":return new Ue(i,e,!1,t);default:throw new rt("unsupported track type: ".concat(i.kind))}}const dh=Object.values(Pn),hh=Object.values(Ys),fh=Object.values(gr),ph=[Pn.h180,Pn.h360],mh=[Ys.h180,Ys.h360],gh=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new Q(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),tr=["q","h","f"];function ir(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,u=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=yh(i,e,t,u),q.debug("using video encoding",o));const l=new Q(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&gn(u)){q.debug("using svc with scalabilityMode ".concat(c));const p=new ac(c),v=[];if(p.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let y=0;y<p.spatial;y+=1)v.push({rid:tr[2-y],maxBitrate:o.maxBitrate/Math.pow(3,y),maxFramerate:l.encoding.maxFramerate});return v[0].scalabilityMode=c,q.debug("encodings",v),v}if(!a)return[o];let h=[];i?h=(s=yo(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:vo(i,l):h=(r=yo(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:vo(i,l);let f;if(h.length>0){const p=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return ws(e,t,[p,f,l]);if(v>=480)return ws(e,t,[p,l])}return ws(e,t,[l])}function vh(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&q.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,u=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return ir(i.source===C.Source.ScreenShare,c,u,t)}function yh(i,e,t,n){const s=bh(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function bh(i,e,t){if(i)return fh;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?dh:hh}function vo(i,e){if(i)return gh(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?ph:mh}function ws(i,e,t){const n=[];if(t.forEach((s,r)=>{if(r>=tr.length)return;const o=Math.min(i,e),c={rid:tr[r],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate};s.encoding.maxFramerate&&(c.maxFramerate=s.encoding.maxFramerate);const u=Gi()||r===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),n.push(c)}),Oi()&&Za()==="ios"){let s;n.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let r=!0;n.forEach(o=>{var a;o.maxFramerate!=s&&(r&&(r=!1,q.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),q.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(s)),o.maxFramerate=s)})}return n}function yo(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class ac{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:"")}}const kh=5e3;class Ue extends Rn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,u)=>{var l;const h=(l=this.prevStats)===null||l===void 0?void 0:l.get(u);a+=ls(c,h)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new Ze}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ie())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},kr))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,n,s,r,o;return m(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var a=!0,c=Ui(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0)r=u.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,n,s,r,o;return m(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var a=!0,c=Ui(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;yield(o=l.sender)===null||o===void 0?void 0:o.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.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.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.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return m(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,framesSent:s.framesSent,timestamp:s.timestamp,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t})}setPublishingQuality(e){const t=[];for(let n=Be.LOW;n<=Be.HIGH;n+=1)t.push(new Qe({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===wi(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||wi(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,n,s,r;return m(this,void 0,void 0,function*(){let o;if(e){const l=us({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=Ui(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;l.sender&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var s,r,o,a,c,u;return m(this,void 0,void 0,function*(){if(yield n.setProcessor.call(this,e,t),!((c=this.processor)===null||c===void 0)&&c.processedTrack)try{for(var l=!0,h=Ui(this.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;l=!0)a=f.value,l=!1,yield(u=a.sender)===null||u===void 0?void 0:u.replaceTrack(this.processor.processedTrack)}catch(p){r={error:p}}finally{try{!l&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(r)throw r.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},kh))}setPublishingCodecs(e){var t,n,s,r,o,a,c;return m(this,void 0,void 0,function*(){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(e[0].qualities),[];this.subscribedCodecs=e;const u=[];try{for(t=!0,n=Ui(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const h=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:h})),!h||!h.sender){for(const f of l.qualities)if(f.enabled){u.push(l.codec);break}}else h.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield bo(h.sender,h.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){o={error:l}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return u})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield bo(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xa()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function bo(i,e,t,n,s,r){return m(this,void 0,void 0,function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:i,qualities:t,senderEncodings:e}));try{const a=i.getParameters(),{encodings:c}=a;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch");return}let u=!1;!1&&c[0].scalabilityMode||c.forEach((h,f)=>{var p;let v=(p=h.rid)!==null&&p!==void 0?p:"";v===""&&(v="q");const y=cc(v),R=t.find(S=>S.quality===y);R&&h.active!==R.enabled&&(u=!0,h.active=R.enabled,s.debug("setting layer ".concat(R.quality," to ").concat(h.active?"enabled":"disabled"),r),Gi()&&(R.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))}),u&&(a.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:a.encodings})),yield i.setParameters(a))}finally{o()}})}function cc(i){switch(i){case"f":return Be.HIGH;case"h":return Be.MEDIUM;case"q":return Be.LOW;default:return Be.HIGH}}function ko(i,e,t,n){if(!t)return[new Pe({quality:Be.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new ac(s),o=[];for(let a=0;a<r.spatial;a+=1)o.push(new Pe({quality:Be.HIGH-a,width:Math.ceil(i/Math.pow(2,a)),height:Math.ceil(e/Math.pow(2,a)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(3,a)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let u=cc((o=s.rid)!==null&&o!==void 0?o:"");return new Pe({quality:u,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}class uc extends C{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?_.Muted:_.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver=void 0,this._currentBitrate=0,this.emit(_.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return m(this,void 0,void 0,function*(){return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),kr))}}class yn extends uc{constructor(e,t,n,s,r,o){super(e,t,C.Kind.Audio,n,o),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=ls(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Oi()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Oi())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(Qs(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Qs(e)&&e.setSinkId(this.sinkId),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 n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.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(_.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(_.AudioPlaybackFailed,s)})}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(n=>{n.type==="inbound-rtp"&&(t={type:"audio",timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Es=100;class bn extends uc{constructor(e,t,n,s,r){super(e,t,C.Kind.Video,n,r),this.elementInfos=[],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=ls(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=mr(()=>{this.updateDimensions()},Es),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Vi(this._mediaStreamTrack,t):Fi(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 Ch(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);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,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}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(){var e,t;const n=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!s||r;if(this.lastVisible!==o){if(!o&&Date.now()-n<Es){ke.setTimeout(()=>{this.updateVisibility()},Es);return}this.lastVisible=o,this.emit(_.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(_.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?to():t||(to()>2?2:1)}}class Ch{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n;this.isPiP=!0,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=!1,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Co(e),this.isPiP=Ie()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Co(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;(e=this.handleResize)===null||e===void 0||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,no().observe(this.element),io().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=no())===null||e===void 0||e.unobserve(this.element),(t=io())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Co(i){let e=i.offsetTop,t=i.offsetLeft;const n=i.offsetWidth,s=i.offsetHeight,{hidden:r}=i,{opacity:o,display:a}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,e+=i.offsetTop,t+=i.offsetLeft;return e<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&e+s>window.pageYOffset&&t+n>window.pageXOffset&&!r&&(o!==""?parseFloat(o)>0:!0)&&a!=="none"}class It extends Et.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=be.NONE,this.log=q,this.handleMuted=()=>{this.emit(_.Muted)},this.handleUnmuted=()=>{this.emit(_.Unmuted)},this.log=ci((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:wt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=C.Source.Unknown}setTrack(e){this.track&&(this.track.off(_.Muted,this.handleMuted),this.track.off(_.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(_.Muted,this.handleMuted),e.on(_.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ie(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==be.NONE}get audioTrack(){if(this.track instanceof Me||this.track instanceof yn)return this.track}get videoTrack(){if(this.track instanceof Ue||this.track instanceof bn)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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(i.PermissionStatus||(i.PermissionStatus={}))})(It||(It={}));class ns extends It{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(_.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(_.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(_.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return m(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return m(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return m(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return m(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var fi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(fi||(fi={}));function Th(i){switch(i){case At.EXCELLENT:return fi.Excellent;case At.GOOD:return fi.Good;case At.POOR:return fi.Poor;case At.LOST:return fi.Lost;default:return fi.Unknown}}class lc extends Et.EventEmitter{get logContext(){var e,t;return Object.assign(Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e)),{participantSid:this.sid,participantId:this.identity})}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e,t;return(t=(e=this.permissions)===null||e===void 0?void 0:e.agent)!==null&&t!==void 0?t:!1}constructor(e,t,n,s,r){var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=fi.Unknown,this.log=q,this.log=ci((o=r==null?void 0:r.loggerName)!==null&&o!==void 0?o:wt.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}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){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),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(N.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(N.ParticipantNameChanged,e)}setPermissions(e){var t,n,s,r,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[l])});return this.permissions=e,c&&this.emit(N.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(N.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Th(e),t!==this._connectionQuality&&this.emit(N.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>(t.track instanceof yn||t.track instanceof Me)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(_.Muted,()=>{this.emit(N.TrackMuted,e)}),e.on(_.Unmuted,()=>{this.emit(N.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 Sh(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new bt({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class To extends lc{constructor(e,t,n,s){super(e,t,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=be.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ec)},this.handleReconnected=()=>{var r,o;(o=(r=this.reconnectFuture)===null||r===void 0?void 0:r.resolve)===null||o===void 0||o.call(r),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var r,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(r=this.reconnectFuture)===null||r===void 0?void 0:r.reject)===null||o===void 0||o.call(r,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(r=>Sh(r)))},this.onTrackUnmuted=r=>{this.onTrackMuted(r,r.isUpstreamPaused)},this.onTrackMuted=(r,o)=>{if(o===void 0&&(o=!0),!r.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ie(r)));return}this.engine.updateMuteStatus(r.sid,o)},this.onTrackUpstreamPaused=r=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ie(r))),this.onTrackMuted(r,!0)},this.onTrackUpstreamResumed=r=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ie(r))),this.onTrackMuted(r,r.isMuted)},this.handleSubscribedQualityUpdate=r=>m(this,void 0,void 0,function*(){var o,a,c,u,l,h;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const f=this.videoTrackPublications.get(r.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}if(r.subscribedCodecs.length>0){if(!f.videoTrack)return;const R=yield f.videoTrack.setPublishingCodecs(r.subscribedCodecs);try{for(var p=!0,v=Ui(R),y;y=yield v.next(),o=y.done,!o;p=!0){u=y.value,p=!1;const S=u;Ed(S)&&(this.log.debug("publish ".concat(S," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ie(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,S,f.options))}}catch(S){a={error:S}}finally{try{!p&&!o&&(c=v.return)&&(yield c.call(v))}finally{if(a)throw a.error}}}else r.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(r.subscribedQualities))}),this.handleLocalTrackUnpublished=r=>{const o=this.trackPublications.get(r.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=r=>m(this,void 0,void 0,function*(){if(r.source===C.Source.ScreenShare||r.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ie(r))),this.unpublishTrack(r);else if(r.isUserProvided)yield r.mute();else if(r instanceof Me||r instanceof Ue)try{if(Ie())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:r.source===C.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(r.source),Object.assign(Object.assign({},this.logContext),ie(r))),o.onchange=()=>{o.state!=="denied"&&(r.isMuted||r.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}r.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ie(r))),yield r.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ie(r))),yield r.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==be.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){this.engine=e,this.engine.on(x.RemoteMute,(t,n)=>{const s=this.trackPublications.get(t);!s||!s.track||(n?s.mute():s.unmute())}),this.engine.on(x.Connected,this.handleReconnected).on(x.SignalRestarted,this.handleReconnected).on(x.SignalResumed,this.handleReconnected).on(x.Restarting,this.handleReconnecting).on(x.Resuming,this.handleReconnecting).on(x.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(x.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(x.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,(t=this.name)!==null&&t!==void 0?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata((t=this.metadata)!==null&&t!==void 0?t:"",e)}setCameraEnabled(e,t,n){return this.setTrackEnabled(C.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(C.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(C.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(N.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?be.GCM:be.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){var r,o;return m(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t}));let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){this.log.info("skipping duplicate published source",Object.assign(Object.assign({},this.logContext),{source:e}));return}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new rt(e)}const u=[];for(const h of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ie(h))),u.push(this.publishTrack(h,s));[a]=yield Promise.all(u)}catch(u){throw c==null||c.forEach(l=>{l.stop()}),u instanceof Error&&!(u instanceof rt)&&this.emit(N.MediaDevicesError,u),u}finally{this.pendingPublishing.delete(e)}}else if(a&&a.track)if(e===C.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}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){var t,n;return m(this,void 0,void 0,function*(){const s=Wa(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),r=us(s);let o;try{o=yield navigator.mediaDevices.getUserMedia(r)}catch(a){throw a instanceof Error&&(r.audio&&(this.microphoneError=a),r.video&&(this.cameraError=a)),a}return r.audio&&(this.microphoneError=void 0,this.emit(N.AudioStreamAcquired)),r.video&&(this.cameraError=void 0),o.getTracks().map(a=>{const c=a.kind==="audio";c?e.audio:e.video;let u;const l=c?r.audio:r.video;typeof l!="boolean"&&(u=l);const h=oc(a,u,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=o,h})})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new pr("getDisplayMedia not supported");e.resolution===void 0&&!Fd()&&(e.resolution=gr.h1080fps30.resolution);const t=xd(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new rt("no video track found");const r=new Ue(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(N.AudioStreamAcquired);const a=new Me(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=C.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){var n,s,r,o;return m(this,void 0,void 0,function*(){yield(n=this.reconnectFuture)===null||n===void 0?void 0:n.promise,e instanceof Rn&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let a;if(e instanceof MediaStreamTrack)a=e.getConstraints();else{a=e.constraints;let p;switch(e.source){case C.Source.Microphone:p="audioinput";break;case C.Source.Camera:p="videoinput"}p&&this.activeDeviceMap.has(p)&&(a=Object.assign(Object.assign({},a),{deviceId:this.activeDeviceMap.get(p)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Me(e,a,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Ue(e,a,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new rt("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e instanceof Me&&e.setAudioContext(this.audioContext);let c;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(c=p)}),c)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),ie(c))),c;const u="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=(s=t==null?void 0:t.forceStereo)!==null&&s!==void 0?s:u;l&&(t||(t={}),t.dtx===void 0&&this.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},this.logContext),ie(e))),t.red===void 0&&this.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(r=t.dtx)!==null&&r!==void 0||(t.dtx=!1),(o=t.red)!==null&&o!==void 0||(t.red=!1));const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Ri()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari",Object.assign({},this.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const f=this.publish(e,h,l);this.pendingPublishPromises.set(e,f);try{return yield f}catch(p){throw p}finally{this.pendingPublishPromises.delete(e)}})}publish(e,t,n){var s,r,o,a,c,u,l,h,f,p,v,y;return m(this,void 0,void 0,function*(){Array.from(this.trackPublications.values()).find(U=>e instanceof Rn&&U.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ie(e))),t.stopMicTrackOnMute&&e instanceof Me&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&Gi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Md()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Dd()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=er);const S=t.videoCodec;e.on(_.Muted,this.onTrackMuted),e.on(_.Unmuted,this.onTrackUnmuted),e.on(_.Ended,this.handleTrackEnded),e.on(_.UpstreamPaused,this.onTrackUpstreamPaused),e.on(_.UpstreamResumed,this.onTrackUpstreamResumed);const w=new We({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||s),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream});let $;if(e.kind===C.Kind.Video){let U={width:0,height:0};try{U=yield e.waitForDimensions()}catch{const M=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Pn.h720.resolution;U={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{dims:U}))}w.width=U.width,w.height=U.height,e instanceof Ue&&(gn(S)&&(e.source===C.Source.ScreenShare&&S==="vp9"&&(t.scalabilityMode="L1T3"),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new Ge({codec:S,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:er}),t.backupCodec&&S!==t.backupCodec.codec&&w.encryption===be.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new Ge({codec:t.backupCodec.codec,cid:""})))),$=ir(e.source===C.Source.ScreenShare,w.width,w.height,t),w.layers=ko(w.width,w.height,$,gn(t.videoCodec))}else e.kind===C.Kind.Audio&&($=[{maxBitrate:(u=t.audioPreset)===null||u===void 0?void 0:u.maxBitrate,priority:(h=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&h!==void 0?h:"high",networkPriority:(p=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new he("cannot publish track when not connected");const K=yield this.engine.addTrack(w);let me;if(K.codecs.forEach(U=>{me===void 0&&(me=U.mimeType)}),me&&e.kind===C.Kind.Video){const U=Ya(me);U!==S&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{codec:U})),t.videoCodec=U,$=ir(e.source===C.Source.ScreenShare,w.width,w.height,t))}const de=new ns(e.kind,K,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(de.options=t,e.sid=K.sid,!this.engine.pcManager)throw new he("pcManager is not ready");if(this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:$,trackInfo:K})),e.sender=yield this.engine.createSender(e,t,$),$)if(Gi()&&e.kind===C.Kind.Audio){let U;for(const ee of this.engine.pcManager.publisher.getTransceivers())if(ee.sender===e.sender){U=ee;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((v=$[0])===null||v===void 0)&&v.maxBitrate?$[0].maxBitrate/1e3:0})}else e.codec&&gn(e.codec)&&(!((y=$[0])===null||y===void 0)&&y.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:$[0].maxBitrate/1e3});return yield this.engine.negotiate(),e instanceof Ue?e.startMonitor(this.engine.client):e instanceof Me&&e.startMonitor(),this.addTrackPublication(de),this.emit(N.LocalTrackPublished,de),de})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var s;return m(this,void 0,void 0,function*(){if(this.encryptionType!==be.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new rt("track is not published");if(!(e instanceof Ue))throw new rt("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=vh(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ie(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const u=new We({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(u.layers=ko(u.width,u.height,a),!this.engine||this.engine.isClosed)throw new he("cannot publish track when not connected");const l=yield this.engine.addTrack(u);yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate(),this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:l}))})}unpublishTrack(e,t){var n,s;return m(this,void 0,void 0,function*(){const r=this.getPublicationForTrack(e),o=r?ie(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(_.Muted,this.onTrackMuted),e.off(_.Unmuted,this.onTrackUnmuted),e.off(_.Ended,this.handleTrackEnded),e.off(_.UpstreamPaused,this.onTrackUpstreamPaused),e.off(_.UpstreamResumed,this.onTrackUpstreamResumed),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t&&e.stop();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<pe.FAILED&&c)try{for(const u of this.engine.pcManager.publisher.getTransceivers())u.sender===c&&(u.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),e instanceof Ue){for(const[,u]of e.simulcastCodecs)u.sender&&(this.engine.removeTrack(u.sender)&&(a=!0),u.sender=void 0);e.simulcastCodecs.clear()}}catch(u){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:u}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(N.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>n instanceof ns)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return m(this,void 0,void 0,function*(){const n=[];this.trackPublications.forEach(s=>{s.track&&(e&&(s.options=Object.assign(Object.assign({},s.options),e)),n.push(s))}),yield Promise.all(n.map(s=>m(this,void 0,void 0,function*(){const r=s.track;yield this.unpublishTrack(r,!1),t&&!r.isMuted&&r.source!==C.Source.ScreenShare&&r.source!==C.Source.ScreenShareAudio&&(r instanceof Me||r instanceof Ue)&&!r.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:s.trackSid})),yield r.restartTrack()),yield this.publishTrack(r,s.options)})))})}publishData(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return m(this,void 0,void 0,function*(){const n=t.reliable?fe.RELIABLE:fe.LOSSY,s=t.destinationIdentities,r=t.topic,o=new ot({kind:n,value:{case:"user",value:new ct({participantIdentity:this.identity,payload:e,destinationIdentities:s,topic:r})}});yield this.engine.sendDataPacket(o,n)})}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()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ie(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(s instanceof Me||s instanceof Ue)&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}}class dc extends It{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Be.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(_.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Fe({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ut({participantSid:"",trackSids:[this.trackSid]})]});this.emit(_.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?It.SubscriptionStatus.Unsubscribed:super.isSubscribed?It.SubscriptionStatus.Subscribed:It.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?It.PermissionStatus.Allowed:It.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(this.track instanceof bn&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof bn&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(_.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(_.VisibilityChanged,this.handleVisibilityChange),s.off(_.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(_.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(_.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(_.VisibilityChanged,this.handleVisibilityChange),e.on(_.Ended,this.handleEnded),this.emit(_.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(_.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?_.Muted:_.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(_.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(_.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===C.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return this.track instanceof bn&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new mt({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Be.HIGH,this.emit(_.UpdateSettings,e)}}class ss extends lc{static fromParticipantInfo(e,t){return new ss(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,n,s,r,o){super(t,n||"",s,r,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(_.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ie(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(_.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(_.SubscriptionPermissionChanged,t=>{this.emit(N.TrackSubscriptionPermissionChanged,e,t)}),e.on(_.SubscriptionStatusChanged,t=>{this.emit(N.TrackSubscriptionStatusChanged,e,t)}),e.on(_.Subscribed,t=>{this.emit(N.TrackSubscribed,t,e)}),e.on(_.Unsubscribed,t=>{this.emit(N.TrackUnsubscribed,t,e)}),e.on(_.SubscriptionFailed,t=>{this.emit(N.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 n=this.getTrackPublication(t);n&&n.track&&n.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,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(N.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-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),ie(a))),this.emit(N.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let u;return c?u=new bn(e,t,s,r):u=new yn(e,t,s,this.audioContext,this.audioOutput),u.source=a.source,u.isMuted=a.isMuted,u.setMediaStream(n),u.start(),a.setTrack(u),this.volumeMap.has(a.source)&&u instanceof yn&&u.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;a=new dc(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const u=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));u&&a.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ie(u),newTrack:ie(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ie(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(N.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(N.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;n.track instanceof yn&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var X;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting"})(X||(X={}));const wh=2*1e3;class hc extends Et.EventEmitter{constructor(e){var t,n,s;super(),t=this,this.state=X.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=q,this.bufferedEvents=[],this.isResuming=!1,this.connect=(r,o,a)=>m(this,void 0,void 0,function*(){var c;const u=yield this.disconnectLock.lock();if(this.state===X.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(X.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==r&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Zs(new URL(r))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new go(r,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const l=(f,p,v)=>m(this,void 0,void 0,function*(){var y;this.abortController&&this.abortController.abort();const R=new AbortController;this.abortController=R,u==null||u();try{yield this.attemptConnection(v??r,o,a,R),this.abortController=void 0,f()}catch(S){if(this.regionUrlProvider&&S instanceof te&&S.reason!==3&&S.reason!==0){let w=null;try{w=yield this.regionUrlProvider.getNextBestRegionUrl((y=this.abortController)===null||y===void 0?void 0:y.signal)}catch($){if($ instanceof te&&($.status===401||$.reason===3)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p($);return}}w?(this.log.info("Initial connection failed with ConnectionError: ".concat(S.message,". Retrying with another region: ").concat(w),this.logContext),yield l(f,p,w)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(S))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(S)}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ec((f,p)=>{l(f,p,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(r,o,a,c,u,l)=>m(this,void 0,void 0,function*(){var h,f,p;const v=yield a.join(r,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let y=v.serverInfo;if(y||(y={version:v.serverVersion,region:v.serverRegion}),this.log.debug("connected to Livekit Server ".concat(Object.entries(y).map(R=>{let[S,w]=R;return"".concat(S,": ").concat(w)}).join(", ")),{room:(h=v.room)===null||h===void 0?void 0:h.name,roomSid:(f=v.room)===null||f===void 0?void 0:f.sid,identity:(p=v.participant)===null||p===void 0?void 0:p.identity}),!v.serverVersion)throw new yd("unknown server version");return v.serverVersion==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),v}),this.applyJoinResponse=r=>{const o=r.participant;this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.handleParticipantUpdates([o,...r.otherParticipants]),r.room&&this.handleRoomUpdate(r.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(r.sifTrailer)},this.attemptConnection=(r,o,a,c)=>m(this,void 0,void 0,function*(){var u,l,h;this.state===X.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},br),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(r,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const p=new te("could not establish signal connection");throw f instanceof Error&&(p.message="".concat(p.message,": ").concat(f.message)),f instanceof te&&(p.reason=f.reason,p.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),p}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ie()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ie()&&(document.addEventListener("freeze",this.onPageLeave),(h=navigator.mediaDevices)===null||h===void 0||h.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(X.Connected),this.emit(P.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return m(t,void 0,void 0,function*(){var o,a,c,u;const l=yield this.disconnectLock.lock();try{if(this.state===X.Disconnected){this.log.debug("already disconnected",this.logContext);return}this.log.info("disconnect from room",Object.assign({},this.logContext)),(this.state===X.Connecting||this.state===X.Reconnecting||this.isResuming)&&(this.log.warn("abort connection attempt",this.logContext),(o=this.abortController)===null||o===void 0||o.abort(),(c=(a=this.connectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new te("Client initiated disconnect")),this.connectFuture=void 0),!((u=this.engine)===null||u===void 0)&&u.client.isDisconnected||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(r,ri.CLIENT_INITIATED),this.engine=void 0}finally{l()}})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const r=[],o=ki();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Cs();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(P.Disconnected,()=>{c==null||c.remove(),c=null})}r.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{r.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...r.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const r=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{r.includes(u)||r.push(u)})});yield Promise.all(r.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const r of this.remoteParticipants.values())this.handleParticipantDisconnected(r.identity,r);this.setAndEmitConnectionState(X.Reconnecting)&&this.emit(P.Reconnecting)},this.handleSignalRestarted=r=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(r.serverRegion),Object.assign(Object.assign({},this.logContext),{region:r.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(r);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:r.serverRegion}))}catch{return}this.setAndEmitConnectionState(X.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=r=>{r.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Pi.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=r=>{const o=[],a={};r.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(P.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=r=>{const o=new Map;this.activeSpeakers.forEach(c=>{o.set(c.sid,c)}),r.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(P.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=r=>{r.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);!c||!c.track||(c.track.streamState=C.streamStateFromProto(o.state),a.emit(N.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(P.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=r=>{const o=this.getRemoteParticipantBySid(r.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(r.trackSid);a&&a.setAllowed(r.allowed)},this.handleSubscriptionError=r=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(r.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(r.trackSid);a&&a.setSubscriptionError(r.err)},this.handleDataPacket=(r,o)=>{const a=this.remoteParticipants.get(r.participantIdentity);this.emit(P.DataReceived,r.payload,a,o,r.topic),a==null||a.emit(N.DataReceived,r.payload,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(P.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=r=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:r})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(P.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(P.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(P.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){this.emit(P.MediaDevicesChanged)}),this.handleRoomUpdate=r=>{const o=this.roomInfo;this.roomInfo=r,o&&o.metadata!==r.metadata&&this.emitWhenConnected(P.RoomMetadataChanged,r.metadata),(o==null?void 0:o.activeRecording)!==r.activeRecording&&this.emitWhenConnected(P.RecordingStatusChanged,r.activeRecording)},this.handleConnectionQualityUpdate=r=>{r.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=r=>{this.emit(P.ParticipantMetadataChanged,r,this.localParticipant)},this.onLocalParticipantNameChanged=r=>{this.emit(P.ParticipantNameChanged,r,this.localParticipant)},this.onLocalTrackMuted=r=>{this.emit(P.TrackMuted,r,this.localParticipant)},this.onLocalTrackUnmuted=r=>{this.emit(P.TrackUnmuted,r,this.localParticipant)},this.onLocalTrackPublished=r=>m(this,void 0,void 0,function*(){var o,a,c,u;(c=(a=(o=r.track)===null||o===void 0?void 0:o.getProcessor())===null||a===void 0?void 0:a.onPublish)===null||c===void 0||c.call(a,this),this.emit(P.LocalTrackPublished,r,this.localParticipant),r.track instanceof Me&&(yield r.track.checkForSilence())&&this.emit(P.LocalAudioSilenceDetected,r);const l=yield(u=r.track)===null||u===void 0?void 0:u.getDeviceId(),h=Od(r.source);h&&l&&l!==this.localParticipant.activeDeviceMap.get(h)&&(this.localParticipant.activeDeviceMap.set(h,l),this.emit(P.ActiveDeviceChanged,h,l))}),this.onLocalTrackUnpublished=r=>{this.emit(P.LocalTrackUnpublished,r,this.localParticipant)},this.onLocalConnectionQualityChanged=r=>{this.emit(P.ConnectionQualityChanged,r,this.localParticipant)},this.onMediaDevicesError=r=>{this.emit(P.MediaDevicesError,r)},this.onLocalParticipantPermissionsChanged=r=>{this.emit(P.ParticipantPermissionsChanged,r,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},oh),e),this.log=ci((n=this.options.loggerName)!==null&&n!==void 0?n:wt.Room),this.options.audioCaptureDefaults=Object.assign(Object.assign({},sc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},rc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rh),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ze,this.localParticipant=new To("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",wi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",wi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",wi(this.options.audioOutput.deviceId)).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([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")})}setupE2EE(){var e;this.options.e2ee&&(this.e2eeManager=new Hd(this.options.e2ee),this.e2eeManager.on(vi.ParticipantEncryptionStatusChanged,(t,n)=>{n instanceof To&&(this.isE2EEEnabled=t),this.emit(P.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(vi.EncryptionError,t=>this.emit(P.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomSid:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,identity:this.localParticipant.identity}}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 m(this,void 0,void 0,function*(){return this.state===X.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(x.RoomUpdate,n),e(s.sid))};this.engine.on(x.RoomUpdate,n),this.once(P.Disconnected,()=>{this.engine.off(x.RoomUpdate,n),t("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.isClosed||(this.engine=new uh(this.options),this.engine.on(x.ParticipantUpdate,this.handleParticipantUpdates).on(x.RoomUpdate,this.handleRoomUpdate).on(x.SpeakersChanged,this.handleSpeakersChanged).on(x.StreamStateChanged,this.handleStreamStateUpdate).on(x.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(x.SubscriptionError,this.handleSubscriptionError).on(x.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(x.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(x.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(x.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(x.DataPacketReceived,this.handleDataPacket).on(x.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext)}).on(x.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents()}).on(x.SignalResumed,()=>{this.bufferedEvents=[],(this.state===X.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(x.Restarting,this.handleRestarting).on(x.SignalRestarted,this.handleSignalRestarted).on(x.DCBufferStatusChanged,(e,t)=>{this.emit(P.DCBufferStatusChanged,e,t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ee.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===X.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Zs(new URL(e))&&t){this.regionUrlProvider=new go(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===X.Disconnected&&(this.regionUrl=n,yield fetch(ro(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(ro(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}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 n=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new ye({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new ye({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new ye({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new ye({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ye({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ye({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":s=new ye({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new je({reason:ri.CLIENT_INITIATED,canReconnect:!0}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new ye({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;var s,r,o;return m(this,void 0,void 0,function*(){let a=!1,c=!0;const u=n?{exact:t}:t;if(e==="audioinput"){const l=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=u,a=l!==u;const h=Array.from(this.localParticipant.audioTrackPublications.values()).filter(f=>f.source===C.Source.Microphone);try{c=(yield Promise.all(h.map(f=>{var p;return(p=f.audioTrack)===null||p===void 0?void 0:p.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.audioCaptureDefaults.deviceId=l,f}}else if(e==="videoinput"){const l=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=u,a=l!==u;const h=Array.from(this.localParticipant.videoTrackPublications.values()).filter(f=>f.source===C.Source.Camera);try{c=(yield Promise.all(h.map(f=>{var p;return(p=f.videoTrack)===null||p===void 0?void 0:p.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.videoCaptureDefaults.deviceId=l,f}}else if(e==="audiooutput"){if(!Qs()&&!this.options.webAudioMix||this.options.webAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");(s=(o=this.options).audioOutput)!==null&&s!==void 0||(o.audioOutput={});const l=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,a=l!==u;try{this.options.webAudioMix?(r=this.audioContext)===null||r===void 0||r.setSinkId(t):yield Promise.all(Array.from(this.remoteParticipants.values()).map(h=>h.setAudioOutput({deviceId:t})))}catch(h){throw this.options.audioOutput.deviceId=l,h}}return a&&c&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(P.ActiveDeviceChanged,e,t)),c})}setupLocalParticipantEvents(){this.localParticipant.on(N.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(N.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(N.TrackMuted,this.onLocalTrackMuted).on(N.TrackUnmuted,this.onLocalTrackUnmuted).on(N.LocalTrackPublished,this.onLocalTrackPublished).on(N.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(N.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(N.MediaDevicesError,this.onMediaDevicesError).on(N.AudioStreamAcquired,this.startAudio).on(N.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===X.Connecting||this.state===X.Reconnecting){const l=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(P.Reconnected,l),this.off(P.Connected,l),this.off(P.Disconnected,h)};this.once(P.Reconnected,l),this.once(P.Connected,l),this.once(P.Disconnected,h);return}if(this.state===X.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}const s=Ad(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let u;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?u=this.options.adaptiveStream:u={}),c.addSubscribedMediaTrack(e,a,t,n,u)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.state!==X.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e&&((r=s.track)===null||r===void 0||r.detach(),(o=s.track)===null||o===void 0||o.stop())}),this.localParticipant.off(N.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(N.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(N.TrackMuted,this.onLocalTrackMuted).off(N.TrackUnmuted,this.onLocalTrackUnmuted).off(N.LocalTrackPublished,this.onLocalTrackPublished).off(N.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(N.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(N.MediaDevicesError,this.onMediaDevicesError).off(N.AudioStreamAcquired,this.startAudio).off(N.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),Ie()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(X.Disconnected),this.emit(P.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(P.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return m(this,void 0,void 0,function*(){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=Ka())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext);const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(P.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=ss.fromParticipantInfo(this.engine.client,t):s=new ss(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(P.ParticipantConnected,n),n.on(N.TrackPublished,s=>{this.emitWhenConnected(P.TrackPublished,s,n)}).on(N.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(_.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(_.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(_.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(_.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(P.TrackSubscribed,s,r,n)}).on(N.TrackUnpublished,s=>{this.emit(P.TrackUnpublished,s,n)}).on(N.TrackUnsubscribed,(s,r)=>{this.emit(P.TrackUnsubscribed,s,r,n)}).on(N.TrackSubscriptionFailed,s=>{this.emit(P.TrackSubscriptionFailed,s,n)}).on(N.TrackMuted,s=>{this.emitWhenConnected(P.TrackMuted,s,n)}).on(N.TrackUnmuted,s=>{this.emitWhenConnected(P.TrackUnmuted,s,n)}).on(N.ParticipantMetadataChanged,s=>{this.emitWhenConnected(P.ParticipantMetadataChanged,s,n)}).on(N.ParticipantNameChanged,s=>{this.emitWhenConnected(P.ParticipantNameChanged,s,n)}).on(N.ConnectionQualityChanged,s=>{this.emitWhenConnected(P.ConnectionQualityChanged,s,n)}).on(N.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(P.ParticipantPermissionsChanged,s,n)}).on(N.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionStatusChanged,s,r,n)}).on(N.TrackSubscriptionFailed,(s,r)=>{this.emit(P.TrackSubscriptionFailed,s,n,r)}).on(N.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionPermissionChanged,s,r,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&t instanceof dc&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ke.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ri.STATE_MISMATCH))):e=0},wh)}clearConnectionReconcile(){this.connectionReconcileInterval&&ke.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(P.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===X.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===X.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){var t,n;return m(this,void 0,void 0,function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Wi({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:F.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new De({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected),this.emit(P.Connected),this.setAndEmitConnectionState(X.Connected),s.video){const o=new ns(C.Kind.Video,new xe({source:ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO,name:"video-dummy"}),new Ue(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:so(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(N.LocalTrackPublished,o)}if(s.audio){const o=new ns(C.Kind.Audio,new xe({source:ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO}),new Me(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Cs(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(N.LocalTrackPublished,o)}for(let o=0;o<r.count-1;o+=1){let a=new De({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Pi.ACTIVE,tracks:[],joinedAt:F.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(r.video){const u=so(160*((n=r.aspectRatios[o%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new xe({source:ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO});c.addSubscribedMediaTrack(u,l.sid,new MediaStream([u])),a.tracks=[...a.tracks,l]}if(r.audio){const u=Cs(),l=new xe({source:ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO});c.addSubscribedMediaTrack(u,l.sid,new MediaStream([u])),a.tracks=[...a.tracks,l]}c.updateInfo(a)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==P.ActiveSpeakersChanged){const r=fc(n).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}function fc(i){return i.map(e=>{if(e)return Array.isArray(e)?fc(e):typeof e=="object"?"logContext"in e&&e.logContext:e})}var qe;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(qe||(qe={}));class Yi extends Et.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qe.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new hc(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return m(this,void 0,void 0,function*(){if(this.status!==qe.IDLE)throw Error("check is running already");this.setStatus(qe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==qe.SKIPPED&&this.setStatus(this.isSuccess()?qe.SUCCESS:qe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return m(this,void 0,void 0,function*(){return this.room.state===X.Connected?this.room:(yield this.room.connect(this.url,this.token),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==X.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qe.SKIPPED)}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}}}function pc(i){var e,t;return m(this,void 0,void 0,function*(){i??(i={}),(e=i.audio)!==null&&e!==void 0||(i.audio=!0),(t=i.video)!==null&&t!==void 0||(i.video=!0);const n=Wa(i,sc,rc),s=us(n),r=navigator.mediaDevices.getUserMedia(s);i.audio&&(Ee.userMediaPromiseMap.set("audioinput",r),r.catch(()=>Ee.userMediaPromiseMap.delete("audioinput"))),i.video&&(Ee.userMediaPromiseMap.set("videoinput",r),r.catch(()=>Ee.userMediaPromiseMap.delete("videoinput")));const o=yield r;return o.getTracks().map(a=>{const c=a.kind==="audio";c?i.audio:i.video;let u;const l=c?s.audio:s.video;typeof l!="boolean"&&(u=l),u?u.deviceId=a.getSettings().deviceId:u={deviceId:a.getSettings().deviceId};const h=oc(a,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=o,h})})}function Eh(i){return m(this,void 0,void 0,function*(){return(yield pc({audio:!1,video:i}))[0]})}function Ph(i){return m(this,void 0,void 0,function*(){return(yield pc({audio:i,video:!1}))[0]})}class _h extends Yi{get description(){return"Can publish audio"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Ph();t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&o.mediaType==="audio"&&(r=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))})}}class Rh extends Yi{get description(){return"Can publish video"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Eh();t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&o.mediaType==="video"&&(r=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}}class Oh extends Yi{get description(){return"Resuming connection after interruption"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(c=>{setTimeout(c,5e3),r=c});t.on(P.Reconnecting,()=>{n=!0}).on(P.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield o,n){if(!s||t.state!==X.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 xh extends Yi{get description(){return"Can connect via TURN"}perform(){var e,t;return m(this,void 0,void 0,function*(){const n=new yr,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,o=!1,a=!1;for(let c of s.iceServers)for(let u of c.urls)u.startsWith("turn:")?(o=!0,a=!0):u.startsWith("turns:")&&(o=!0,a=!0,r=!0),u.startsWith("stun:")&&(a=!0);a?o&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.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 Ih extends Yi{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(P.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const o=new RTCIceCandidate(s);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Nh(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(a)}n&&n(s,r)},this.room.engine.pcManager&&(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(),q.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 Nh(i){const e=i.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 Ah extends Yi{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return m(this,void 0,void 0,function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new yr;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Hi.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield s.close()})}}class Jh extends Et.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:qe.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!==qe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Ih)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(xh)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Oh)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(_h)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Rh)})}}function Mh(){const i=document.createElement("style");return i.textContent=`
|
|
54
|
+
`},th=ic,ih=eh,ws=ih,ln=th.parse;const lo=.7,$i={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class ho extends wt.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 n;super(),this.log=$,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=gr(s=>m(this,void 0,void 0,function*(){this.emit($i.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),100),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=ai((n=t.loggerName)!==null&&n!==void 0?n:St.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.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){var t;return m(this,void 0,void 0,function*(){let n;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=sh(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=ln((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||r.mid!=o.transceiver.mid)return!1;let a=0;if(r.rtp.some(u=>u.codec.toUpperCase()===o.codec.toUpperCase()?(a=u.payload,!0):!1),a===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===a){u.config=u.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),c=!0;break}return c||o.maxbr>0&&r.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),n=ws(s)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit($i.NegotiationComplete),e.sdp&&ln(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit($i.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){var t;return m(this,void 0,void 0,function*(){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"){const r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);else{this.renegotiate=!0;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 n=yield this.pc.createOffer(e),s=ln((t=n.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"?fo(r,[],[]):r.type==="video"&&(nh(r),this.trackBitrates.some(o=>{if(!r.msid||!o.cid||!r.msid.includes(o.cid))return!1;let a=0;if(r.rtp.some(u=>u.codec.toUpperCase()===o.codec.toUpperCase()?(a=u.payload,!0):!1),a===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===a){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(Math.round(o.maxbr*lo))),u.config.includes("x-google-max-bitrate")||(u.config+=";x-google-max-bitrate=".concat(o.maxbr)),c=!0;break}return c||r.fmtp.push({payload:a,config:"x-google-start-bitrate=".concat(Math.round(o.maxbr*lo),";x-google-max-bitrate=").concat(o.maxbr)}),!0}))}),yield this.setMungedSDP(n,ws(s)),this.onOffer(n)})}createAndSetAnswer(){var e;return m(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),n=ln((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{s.type==="audio"&&fo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,ws(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new he("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 he("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()}getConnectedAddress(){var e;return m(this,void 0,void 0,function*(){if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Ks(r)}})}}function fo(i,e,t){let n=0;i.rtp.some(s=>s.codec==="opus"?(n=s.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(s=>s.payload===n&&s.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(s=>s.payload===n?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function nh(i){var e,t,n,s;const r=(t=(e=i.rtp[0])===null||e===void 0?void 0:e.codec)===null||t===void 0?void 0:t.toLowerCase();if(!gn(r))return;let o=0;((n=i.ext)===null||n===void 0?void 0:n.some(c=>c.uri===Zr?!0:(c.value>o&&(o=c.value),!1)))||(s=i.ext)===null||s===void 0||s.push({value:o+1,uri:Zr})}function sh(i){var e;const t=[],n=[],s=ln((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===r&&c.type==="nack")&&n.push(o.mid),o.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(o.mid),!0):!1))}),{stereoMids:t,nackMids:n}}const tr="vp8",rh={audioPreset:Ys.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:vr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:tr,backupCodec:!0},rc={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},oc={resolution:Pn.h720.resolution},oh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ql,disconnectOnPageLeave:!0,webAudioMix:!0},kr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var pe;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(pe||(pe={}));class ah{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=kr.peerConnectionTimeout,this.log=$,this.updateState=()=>{var r;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=pe.CONNECTED:a.some(c=>c==="failed")?this.state=pe.FAILED:a.some(c=>c==="connecting")?this.state=pe.CONNECTING:a.every(c=>c==="closed")?this.state=pe.CLOSED:a.some(c=>c==="closed")?this.state=pe.CLOSING:a.every(c=>c==="new")&&(this.state=pe.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(pe[o]," to ").concat(pe[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=ai((s=n.loggerName)!==null&&s!==void 0?s:St.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new ho(e,n),this.subscriber=new ho(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,we.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=r=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r)},this.state=pe.NEW,this.connectionLock=new Ze}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){return this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()})),yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var n;return m(this,void 0,void 0,function*(){const s=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const s=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once($i.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once($i.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),n(o)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return m(this,void 0,void 0,function*(){if(e.getConnectionState()!=="connected")return new Promise((r,o)=>m(this,void 0,void 0,function*(){const a=()=>{this.log.warn("abort transport connection",this.logContext),Te.clearTimeout(c),o(new te("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&a(),t==null||t.signal.addEventListener("abort",a);const c=Te.setTimeout(()=>{t==null||t.signal.removeEventListener("abort",a),o(new te("could not establish pc connection"))},n);for(;this.state!==pe.CONNECTED;)if(yield ri(50),t!=null&&t.signal.aborted){o(new te("room connection has been cancelled",3));return}Te.clearTimeout(c),t==null||t.signal.removeEventListener("abort",a),r()}))})}}const po="_lossy",mo="_reliable",ch=2*1e3,go="leave-reconnect";var Ve;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Ve||(Ve={}));class uh extends wt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=kr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ve.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=$,this.handleDataChannel=n=>{let{channel:s}=n;return m(this,void 0,void 0,function*(){if(s){if(s.label===mo)this.reliableDCSub=s;else if(s.label===po)this.lossyDCSub=s;else return;this.log.debug("on data channel ".concat(s.id,", ").concat(s.label),this.logContext),s.onmessage=this.handleDataMessage}})},this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var s,r;const o=yield this.dataProcessLock.lock();try{let a;if(n.data instanceof ArrayBuffer)a=n.data;else if(n.data instanceof Blob)a=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=rt.fromBinary(new Uint8Array(a));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,c.value.value.speakers):((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&this.emit(I.DataPacketReceived,c.value.value,c.kind)}finally{o()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?fe.LOSSY:fe.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(I.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===go&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Te.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Ve.Connected&&n();const r=()=>{this.off(I.Disconnected,o),n()},o=()=>{this.off(I.Restarted,r),s()};this.once(I.Restarted,r),this.once(I.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(I.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===re.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Ot.RR_SIGNAL_DISCONNECTED))},this.log=ai((t=e.loggerName)!==null&&t!==void 0?t:St.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new br(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ze,this.dataProcessLock=new Ze,this.dcBufferStatus=new Map([[fe.LOSSY,!0],[fe.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(I.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(I.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(I.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(I.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(I.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(I.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(I.StreamStateChanged,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomSid:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,identity:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity}}join(e,t,n,s){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof te&&r.reason===1&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}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.emit(I.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){var e;return m(this,void 0,void 0,function*(){yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new st("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new te("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){var e;return m(this,void 0,void 0,function*(){return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t;return m(this,void 0,void 0,function*(){if(this.pcManager&&this.pcManager.currentState!==pe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const n=this.makeRTCConfiguration(e);this.pcManager=new ah(n,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,r)=>{this.client.sendIceCandidate(s,r)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,r,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),s===pe.CONNECTED){const a=this.pcState===Ve.New;this.pcState=Ve.Connected,a&&this.emit(I.Connected,e)}else s===pe.FAILED&&this.pcState===Ve.Connected&&(this.pcState=Ve.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Ot.RR_SUBSCRIBER_FAILED:Ot.RR_PUBLISHER_FAILED))}),this.pcManager.onTrack=s=>{this.emit(I.MediaTrackAdded,s.track,s.streams[0],s.receiver)},this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.trace("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{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),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(I.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Ot.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.handleDisconnect(go)):(this.emit(I.Disconnected,e==null?void 0:e.reason),this.close()),this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason}))}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===et.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(po,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(mo,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,n){if(!("getCapabilities"in RTCRtpSender))return;const s=RTCRtpSender.getCapabilities(t);if(!s)return;this.log.debug("get sender capabilities",Object.assign(Object.assign({},this.logContext),{cap:s}));const r=[],o=[],a=[];s.codecs.forEach(c=>{const u=c.mimeType.toLowerCase();if(u==="audio/opus"){r.push(c);return}if(!(u==="video/".concat(n))){a.push(c);return}if(n==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(c):o.push(c);return}r.push(c)}),Ud(e)&&e.setCodecPreferences(r.concat(o,a))}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(eo())return yield this.createTransceiverRTCRtpSender(e,t,n);if(to())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new he("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return m(this,void 0,void 0,function*(){if(eo())return this.createSimulcastTransceiverSender(e,t,n,s);if(to())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new he("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream);const r={direction:"sendonly",streams:s};n&&(r.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r);return e.kind===C.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(o,e.kind,t.videoCodec),e.codec=t.videoCodec),o.sender})}createSimulcastTransceiverSender(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return this.setPreferredCodec(o,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){var t,n,s;return m(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){$.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===et.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:pe.NEW)===pe.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof he?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Li||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Ot.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(I.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){var t,n,s;return m(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new he("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Li;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof te&&o.reason===0?new he("could not reconnect, token might be expired"):new Li}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==re.CONNECTED)throw new Li("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(I.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){var t;return m(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new he("could not reconnect, url or token not saved");if(!this.pcManager)throw new he("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);try{this.setupSignalClientCallbacks();const n=yield this.client.reconnect(this.url,this.token,this.participantSid,e);if(n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s)}}catch(n){let s="";throw n instanceof Error&&(s=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof te&&n.reason===0?new he("could not reconnect, token might be expired"):n instanceof te&&n.reason===4?n:new Li(s)}if(this.emit(I.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==re.CONNECTED)throw new Li("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(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Ve.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ri(ch),!this.pcManager)throw new he("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ve.Connected}catch(e){throw this.pcState=Ve.Disconnected,new te("could not establish PC connection, ".concat(e.message))}})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(n),this.updateAndEmitDCBufferStatus(t)})}ensureDataTransportConnected(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;var n;return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new he("PC manager is closed");const s=t?this.pcManager.subscriber:this.pcManager.publisher,r=t?"Subscriber":"Publisher";if(!s)throw new te("".concat(r," connection not set"));!t&&!this.pcManager.publisher.isICEConnected&&this.pcManager.publisher.getICEConnectionState()!=="checking"&&this.negotiate();const o=this.dataChannelForKind(e,t);if((o==null?void 0:o.readyState)==="open")return;const a=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()<a;){if(s.isICEConnected&&((n=this.dataChannelForKind(e,t))===null||n===void 0?void 0:n.readyState)==="open")return;yield ri(50)}throw new te("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){yield this.ensureDataTransportConnected(e,!1)})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==pe.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ks("PC manager is closed"));return}this.pcManager.requirePublisher();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(I.Closing,s),this.pcManager.publisher.once($i.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();Vd(c)&&o.set(a.payload,c)}),this.emit(I.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Ks&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ot.RR_UNKNOWN),t(r)}finally{this.off(I.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===fe.LOSSY)return this.lossyDCSub;if(e===fe.RELIABLE)return this.reliableDCSub}else{if(e===fe.LOSSY)return this.lossyDC;if(e===fe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(s=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,u=new Array;e.forEach(l=>{l.isDesired!==a&&c.push(l.trackSid),l.isEnabled||u.push(l.trackSid)}),this.client.sendSyncState(new kt({answer:r?ns({sdp:r.sdp,type:r.type}):void 0,offer:o?ns({sdp:o.sdp,type:o.type}):void 0,subscription:new je({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:Id(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Ct({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(fe.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(fe.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(fe.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(fe.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Te.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ne()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ne()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Li extends Error{}class vo{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return er(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(s=>s.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),$.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(lh(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function lh(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}const Cr=2e3;function ds(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}class De extends Rn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,n,r),this.stopOnMute=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=ds(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.checkForSilence()}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Si(e)===this.mediaStreamTrack.getSettings().deviceId)})}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.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{const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Si(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=ls({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Ne()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cr)))}setProcessor(e){var t;return m(this,void 0,void 0,function*(){const n=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack))}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return m(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Rd(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(R.AudioSilenceDetected)),e})}}function ac(i,e,t){switch(i.kind){case"audio":return new De(i,e,!1,void 0,t);case"video":return new Fe(i,e,!1,t);default:throw new st("unsupported track type: ".concat(i.kind))}}const dh=Object.values(Pn),hh=Object.values(Xs),fh=Object.values(vr),ph=[Pn.h180,Pn.h360],mh=[Xs.h180,Xs.h360],gh=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new X(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),ir=["q","h","f"];function nr(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,u=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=yh(i,e,t,u),$.debug("using video encoding",o));const l=new X(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&gn(u)){$.debug("using svc with scalabilityMode ".concat(c));const p=new cc(c),y=[];if(p.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let v=0;v<p.spatial;v+=1)y.push({rid:ir[2-v],maxBitrate:o.maxBitrate/Math.pow(3,v),maxFramerate:l.encoding.maxFramerate});return y[0].scalabilityMode=c,$.debug("encodings",y),y}if(!a)return[o];let h=[];i?h=(s=bo(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:yo(i,l):h=(r=bo(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:yo(i,l);let f;if(h.length>0){const p=h[0];h.length>1&&([,f]=h);const y=Math.max(e,t);if(y>=960&&f)return Es(e,t,[p,f,l]);if(y>=480)return Es(e,t,[p,l])}return Es(e,t,[l])}function vh(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&$.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,u=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return nr(i.source===C.Source.ScreenShare,c,u,t)}function yh(i,e,t,n){const s=bh(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function bh(i,e,t){if(i)return fh;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?dh:hh}function yo(i,e){if(i)return gh(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?ph:mh}function Es(i,e,t){const n=[];if(t.forEach((s,r)=>{if(r>=ir.length)return;const o=Math.min(i,e),c={rid:ir[r],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate};s.encoding.maxFramerate&&(c.maxFramerate=s.encoding.maxFramerate);const u=Wi()||r===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),n.push(c)}),Ri()&&ec()==="ios"){let s;n.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let r=!0;n.forEach(o=>{var a;o.maxFramerate!=s&&(r&&(r=!1,$.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),$.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(s)),o.maxFramerate=s)})}return n}function bo(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class cc{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:"")}}const kh=5e3;class Fe extends Rn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,u)=>{var l;const h=(l=this.prevStats)===null||l===void 0?void 0:l.get(u);a+=ds(c,h)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new Ze}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ne())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cr))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,n,s,r,o;return m(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var a=!0,c=Fi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0)r=u.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,n,s,r,o;return m(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var a=!0,c=Fi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;yield(o=l.sender)===null||o===void 0?void 0:o.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.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.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.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return m(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,framesSent:s.framesSent,timestamp:s.timestamp,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t})}setPublishingQuality(e){const t=[];for(let n=Je.LOW;n<=Je.HIGH;n+=1)t.push(new Qe({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Si(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Si(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,n,s,r;return m(this,void 0,void 0,function*(){let o;if(e){const l=ls({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=Fi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){r=u.value,a=!1;const l=r;l.sender&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var s,r,o,a,c,u;return m(this,void 0,void 0,function*(){if(yield n.setProcessor.call(this,e,t),!((c=this.processor)===null||c===void 0)&&c.processedTrack)try{for(var l=!0,h=Fi(this.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;l=!0)a=f.value,l=!1,yield(u=a.sender)===null||u===void 0?void 0:u.replaceTrack(this.processor.processedTrack)}catch(p){r={error:p}}finally{try{!l&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(r)throw r.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},kh))}setPublishingCodecs(e){var t,n,s,r,o,a,c;return m(this,void 0,void 0,function*(){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(e[0].qualities),[];this.subscribedCodecs=e;const u=[];try{for(t=!0,n=Fi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const h=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:h})),!h||!h.sender){for(const f of l.qualities)if(f.enabled){u.push(l.codec);break}}else h.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield ko(h.sender,h.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){o={error:l}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return u})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield ko(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Qa()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ko(i,e,t,n,s,r){return m(this,void 0,void 0,function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:i,qualities:t,senderEncodings:e}));try{const a=i.getParameters(),{encodings:c}=a;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch");return}let u=!1;!1&&c[0].scalabilityMode||c.forEach((h,f)=>{var p;let y=(p=h.rid)!==null&&p!==void 0?p:"";y===""&&(y="q");const v=uc(y),w=t.find(S=>S.quality===v);w&&h.active!==w.enabled&&(u=!0,h.active=w.enabled,s.debug("setting layer ".concat(w.quality," to ").concat(h.active?"enabled":"disabled"),r),Wi()&&(w.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))}),u&&(a.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:a.encodings})),yield i.setParameters(a))}finally{o()}})}function uc(i){switch(i){case"f":return Je.HIGH;case"h":return Je.MEDIUM;case"q":return Je.LOW;default:return Je.HIGH}}function Co(i,e,t,n){if(!t)return[new _e({quality:Je.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new cc(s),o=[];for(let a=0;a<r.spatial;a+=1)o.push(new _e({quality:Je.HIGH-a,width:Math.ceil(i/Math.pow(2,a)),height:Math.ceil(e/Math.pow(2,a)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(3,a)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let u=uc((o=s.rid)!==null&&o!==void 0?o:"");return new _e({quality:u,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}class lc extends C{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}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=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),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(){var e;return m(this,void 0,void 0,function*(){return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Cr))}}class yn extends lc{constructor(e,t,n,s,r,o){super(e,t,C.Kind.Audio,n,o),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=ds(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ri()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ri())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(Zs(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Zs(e)&&e.setSinkId(this.sinkId),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 n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.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(s=>{this.emit(R.AudioPlaybackFailed,s)})}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(n=>{n.type==="inbound-rtp"&&(t={type:"audio",timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Ps=100;class bn extends lc{constructor(e,t,n,s,r){super(e,t,C.Kind.Video,n,r),this.elementInfos=[],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=ds(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=gr(()=>{this.updateDimensions()},Ps),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?qi(this._mediaStreamTrack,t):ji(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 Ch(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);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,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}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(){var e,t;const n=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!s||r;if(this.lastVisible!==o){if(!o&&Date.now()-n<Ps){Te.setTimeout(()=>{this.updateVisibility()},Ps);return}this.lastVisible=o,this.emit(R.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},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"?io():t||(io()>2?2:1)}}class Ch{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n;this.isPiP=!0,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=!1,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??To(e),this.isPiP=Ne()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=To(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;(e=this.handleResize)===null||e===void 0||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,so().observe(this.element),no().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=so())===null||e===void 0||e.unobserve(this.element),(t=no())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function To(i){let e=i.offsetTop,t=i.offsetLeft;const n=i.offsetWidth,s=i.offsetHeight,{hidden:r}=i,{opacity:o,display:a}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,e+=i.offsetTop,t+=i.offsetLeft;return e<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&e+s>window.pageYOffset&&t+n>window.pageXOffset&&!r&&(o!==""?parseFloat(o)>0:!0)&&a!=="none"}class xt extends wt.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=Ce.NONE,this.log=$,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},this.log=ai((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:St.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,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)),ie(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ce.NONE}get audioTrack(){if(this.track instanceof De||this.track instanceof yn)return this.track}get videoTrack(){if(this.track instanceof Fe||this.track instanceof bn)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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(i.PermissionStatus||(i.PermissionStatus={}))})(xt||(xt={}));class ss extends xt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(R.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(R.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(R.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return m(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return m(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return m(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return m(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var fi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(fi||(fi={}));function Th(i){switch(i){case Nt.EXCELLENT:return fi.Excellent;case Nt.GOOD:return fi.Good;case Nt.POOR:return fi.Poor;case Nt.LOST:return fi.Lost;default:return fi.Unknown}}class dc extends wt.EventEmitter{get logContext(){var e,t;return Object.assign(Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e)),{participantSid:this.sid,participantId:this.identity})}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e,t;return(t=(e=this.permissions)===null||e===void 0?void 0:e.agent)!==null&&t!==void 0?t:!1}constructor(e,t,n,s,r){var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=fi.Unknown,this.log=$,this.log=ai((o=r==null?void 0:r.loggerName)!==null&&o!==void 0?o:St.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}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){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),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(N.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(N.ParticipantNameChanged,e)}setPermissions(e){var t,n,s,r,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[l])});return this.permissions=e,c&&this.emit(N.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(N.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Th(e),t!==this._connectionQuality&&this.emit(N.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>(t.track instanceof yn||t.track instanceof De)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(N.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(N.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 Sh(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new yt({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class So extends dc{constructor(e,t,n,s){super(e,t,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ce.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new tc)},this.handleReconnected=()=>{var r,o;(o=(r=this.reconnectFuture)===null||r===void 0?void 0:r.resolve)===null||o===void 0||o.call(r),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var r,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(r=this.reconnectFuture)===null||r===void 0?void 0:r.reject)===null||o===void 0||o.call(r,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(r=>Sh(r)))},this.onTrackUnmuted=r=>{this.onTrackMuted(r,r.isUpstreamPaused)},this.onTrackMuted=(r,o)=>{if(o===void 0&&(o=!0),!r.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ie(r)));return}this.engine.updateMuteStatus(r.sid,o)},this.onTrackUpstreamPaused=r=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ie(r))),this.onTrackMuted(r,!0)},this.onTrackUpstreamResumed=r=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ie(r))),this.onTrackMuted(r,r.isMuted)},this.handleSubscribedQualityUpdate=r=>m(this,void 0,void 0,function*(){var o,a,c,u,l,h;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const f=this.videoTrackPublications.get(r.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}if(r.subscribedCodecs.length>0){if(!f.videoTrack)return;const w=yield f.videoTrack.setPublishingCodecs(r.subscribedCodecs);try{for(var p=!0,y=Fi(w),v;v=yield y.next(),o=v.done,!o;p=!0){u=v.value,p=!1;const S=u;Ed(S)&&(this.log.debug("publish ".concat(S," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ie(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,S,f.options))}}catch(S){a={error:S}}finally{try{!p&&!o&&(c=y.return)&&(yield c.call(y))}finally{if(a)throw a.error}}}else r.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(r.subscribedQualities))}),this.handleLocalTrackUnpublished=r=>{const o=this.trackPublications.get(r.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=r=>m(this,void 0,void 0,function*(){if(r.source===C.Source.ScreenShare||r.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ie(r))),this.unpublishTrack(r);else if(r.isUserProvided)yield r.mute();else if(r instanceof De||r instanceof Fe)try{if(Ne())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:r.source===C.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(r.source),Object.assign(Object.assign({},this.logContext),ie(r))),o.onchange=()=>{o.state!=="denied"&&(r.isMuted||r.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}r.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ie(r))),yield r.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ie(r))),yield r.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ce.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){this.engine=e,this.engine.on(I.RemoteMute,(t,n)=>{const s=this.trackPublications.get(t);!s||!s.track||(n?s.mute():s.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,(t=this.name)!==null&&t!==void 0?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata((t=this.metadata)!==null&&t!==void 0?t:"",e)}setCameraEnabled(e,t,n){return this.setTrackEnabled(C.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(C.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(C.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(N.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?Ce.GCM:Ce.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){var r,o;return m(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t}));let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){this.log.info("skipping duplicate published source",Object.assign(Object.assign({},this.logContext),{source:e}));return}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new st(e)}const u=[];for(const h of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ie(h))),u.push(this.publishTrack(h,s));[a]=yield Promise.all(u)}catch(u){throw c==null||c.forEach(l=>{l.stop()}),u instanceof Error&&!(u instanceof st)&&this.emit(N.MediaDevicesError,u),u}finally{this.pendingPublishing.delete(e)}}else if(a&&a.track)if(e===C.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}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){var t,n;return m(this,void 0,void 0,function*(){const s=Ka(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),r=ls(s);let o;try{o=yield navigator.mediaDevices.getUserMedia(r)}catch(a){throw a instanceof Error&&(r.audio&&(this.microphoneError=a),r.video&&(this.cameraError=a)),a}return r.audio&&(this.microphoneError=void 0,this.emit(N.AudioStreamAcquired)),r.video&&(this.cameraError=void 0),o.getTracks().map(a=>{const c=a.kind==="audio";c?e.audio:e.video;let u;const l=c?r.audio:r.video;typeof l!="boolean"&&(u=l);const h=ac(a,u,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=o,h})})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new mr("getDisplayMedia not supported");e.resolution===void 0&&!Fd()&&(e.resolution=vr.h1080fps30.resolution);const t=xd(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new st("no video track found");const r=new Fe(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(N.AudioStreamAcquired);const a=new De(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=C.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){var n,s,r,o;return m(this,void 0,void 0,function*(){yield(n=this.reconnectFuture)===null||n===void 0?void 0:n.promise,e instanceof Rn&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let a;if(e instanceof MediaStreamTrack)a=e.getConstraints();else{a=e.constraints;let p;switch(e.source){case C.Source.Microphone:p="audioinput";break;case C.Source.Camera:p="videoinput"}p&&this.activeDeviceMap.has(p)&&(a=Object.assign(Object.assign({},a),{deviceId:this.activeDeviceMap.get(p)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new De(e,a,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Fe(e,a,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new st("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e instanceof De&&e.setAudioContext(this.audioContext);let c;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(c=p)}),c)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),ie(c))),c;const u="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=(s=t==null?void 0:t.forceStereo)!==null&&s!==void 0?s:u;l&&(t||(t={}),t.dtx===void 0&&this.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},this.logContext),ie(e))),t.red===void 0&&this.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(r=t.dtx)!==null&&r!==void 0||(t.dtx=!1),(o=t.red)!==null&&o!==void 0||(t.red=!1));const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);_i()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari",Object.assign({},this.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const f=this.publish(e,h,l);this.pendingPublishPromises.set(e,f);try{return yield f}catch(p){throw p}finally{this.pendingPublishPromises.delete(e)}})}publish(e,t,n){var s,r,o,a,c,u,l,h,f,p,y,v;return m(this,void 0,void 0,function*(){Array.from(this.trackPublications.values()).find(U=>e instanceof Rn&&U.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ie(e))),t.stopMicTrackOnMute&&e instanceof De&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&Wi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Md()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Dd()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=tr);const S=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);const E=new We({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||s),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream});let J;if(e.kind===C.Kind.Video){let U={width:0,height:0};try{U=yield e.waitForDimensions()}catch{const M=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Pn.h720.resolution;U={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{dims:U}))}E.width=U.width,E.height=U.height,e instanceof Fe&&(gn(S)&&(e.source===C.Source.ScreenShare&&S==="vp9"&&(t.scalabilityMode="L1T3"),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),E.simulcastCodecs=[new Ge({codec:S,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:tr}),t.backupCodec&&S!==t.backupCodec.codec&&E.encryption===Ce.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),E.simulcastCodecs.push(new Ge({codec:t.backupCodec.codec,cid:""})))),J=nr(e.source===C.Source.ScreenShare,E.width,E.height,t),E.layers=Co(E.width,E.height,J,gn(t.videoCodec))}else e.kind===C.Kind.Audio&&(J=[{maxBitrate:(u=t.audioPreset)===null||u===void 0?void 0:u.maxBitrate,priority:(h=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&h!==void 0?h:"high",networkPriority:(p=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new he("cannot publish track when not connected");const K=yield this.engine.addTrack(E);let me;if(K.codecs.forEach(U=>{me===void 0&&(me=U.mimeType)}),me&&e.kind===C.Kind.Video){const U=Xa(me);U!==S&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{codec:U})),t.videoCodec=U,J=nr(e.source===C.Source.ScreenShare,E.width,E.height,t))}const de=new ss(e.kind,K,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(de.options=t,e.sid=K.sid,!this.engine.pcManager)throw new he("pcManager is not ready");if(this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:J,trackInfo:K})),e.sender=yield this.engine.createSender(e,t,J),J)if(Wi()&&e.kind===C.Kind.Audio){let U;for(const ee of this.engine.pcManager.publisher.getTransceivers())if(ee.sender===e.sender){U=ee;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((y=J[0])===null||y===void 0)&&y.maxBitrate?J[0].maxBitrate/1e3:0})}else e.codec&&gn(e.codec)&&(!((v=J[0])===null||v===void 0)&&v.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:E.cid,codec:e.codec,maxbr:J[0].maxBitrate/1e3});return yield this.engine.negotiate(),e instanceof Fe?e.startMonitor(this.engine.client):e instanceof De&&e.startMonitor(),this.addTrackPublication(de),this.emit(N.LocalTrackPublished,de),de})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var s;return m(this,void 0,void 0,function*(){if(this.encryptionType!==Ce.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new st("track is not published");if(!(e instanceof Fe))throw new st("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=vh(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ie(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const u=new We({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(u.layers=Co(u.width,u.height,a),!this.engine||this.engine.isClosed)throw new he("cannot publish track when not connected");const l=yield this.engine.addTrack(u);yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate(),this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:l}))})}unpublishTrack(e,t){var n,s;return m(this,void 0,void 0,function*(){const r=this.getPublicationForTrack(e),o=r?ie(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.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),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t&&e.stop();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<pe.FAILED&&c)try{for(const u of this.engine.pcManager.publisher.getTransceivers())u.sender===c&&(u.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),e instanceof Fe){for(const[,u]of e.simulcastCodecs)u.sender&&(this.engine.removeTrack(u.sender)&&(a=!0),u.sender=void 0);e.simulcastCodecs.clear()}}catch(u){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:u}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(N.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>n instanceof ss)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return m(this,void 0,void 0,function*(){const n=[];this.trackPublications.forEach(s=>{s.track&&(e&&(s.options=Object.assign(Object.assign({},s.options),e)),n.push(s))}),yield Promise.all(n.map(s=>m(this,void 0,void 0,function*(){const r=s.track;yield this.unpublishTrack(r,!1),t&&!r.isMuted&&r.source!==C.Source.ScreenShare&&r.source!==C.Source.ScreenShareAudio&&(r instanceof De||r instanceof Fe)&&!r.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:s.trackSid})),yield r.restartTrack()),yield this.publishTrack(r,s.options)})))})}publishData(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return m(this,void 0,void 0,function*(){const n=t.reliable?fe.RELIABLE:fe.LOSSY,s=t.destinationIdentities,r=t.topic,o=new rt({kind:n,value:{case:"user",value:new at({participantIdentity:this.identity,payload:e,destinationIdentities:s,topic:r})}});yield this.engine.sendDataPacket(o,n)})}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()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ie(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(s instanceof De||s instanceof Fe)&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}}class hc extends xt{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Je.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(R.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new je({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ct({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?xt.SubscriptionStatus.Unsubscribed:super.isSubscribed?xt.SubscriptionStatus.Subscribed:xt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?xt.PermissionStatus.Allowed:xt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(this.track instanceof bn&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof bn&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(R.VisibilityChanged,this.handleVisibilityChange),s.off(R.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(R.Unsubscribed,s)),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(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),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.kind===C.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return this.track instanceof bn&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new pt({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Je.HIGH,this.emit(R.UpdateSettings,e)}}class rs extends dc{static fromParticipantInfo(e,t){return new rs(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,n,s,r,o){super(t,n||"",s,r,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(R.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ie(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(R.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(R.SubscriptionPermissionChanged,t=>{this.emit(N.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(N.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(N.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(N.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(N.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 n=this.getTrackPublication(t);n&&n.track&&n.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,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(N.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-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),ie(a))),this.emit(N.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let u;return c?u=new bn(e,t,s,r):u=new yn(e,t,s,this.audioContext,this.audioOutput),u.source=a.source,u.isMuted=a.isMuted,u.setMediaStream(n),u.start(),a.setTrack(u),this.volumeMap.has(a.source)&&u instanceof yn&&u.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=C.kindFromProto(s.type);if(!c)return;a=new hc(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const u=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));u&&a.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ie(u),newTrack:ie(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ie(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(N.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(N.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;n.track instanceof yn&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Y;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting"})(Y||(Y={}));const wh=2*1e3;class fc extends wt.EventEmitter{constructor(e){var t,n,s;super(),t=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=$,this.bufferedEvents=[],this.isResuming=!1,this.connect=(r,o,a)=>m(this,void 0,void 0,function*(){var c;const u=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==r&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),er(new URL(r))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new vo(r,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const l=(f,p,y)=>m(this,void 0,void 0,function*(){var v;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,u==null||u();try{yield this.attemptConnection(y??r,o,a,w),this.abortController=void 0,f()}catch(S){if(this.regionUrlProvider&&S instanceof te&&S.reason!==3&&S.reason!==0){let E=null;try{E=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(J){if(J instanceof te&&(J.status===401||J.reason===3)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(J);return}}E?(this.log.info("Initial connection failed with ConnectionError: ".concat(S.message,". Retrying with another region: ").concat(E),this.logContext),yield l(f,p,E)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(S))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),p(S)}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new tc((f,p)=>{l(f,p,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(r,o,a,c,u,l)=>m(this,void 0,void 0,function*(){var h,f,p;const y=yield a.join(r,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let v=y.serverInfo;if(v||(v={version:y.serverVersion,region:y.serverRegion}),this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(w=>{let[S,E]=w;return"".concat(S,": ").concat(E)}).join(", ")),{room:(h=y.room)===null||h===void 0?void 0:h.name,roomSid:(f=y.room)===null||f===void 0?void 0:f.sid,identity:(p=y.participant)===null||p===void 0?void 0:p.identity}),!y.serverVersion)throw new yd("unknown server version");return y.serverVersion==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),y}),this.applyJoinResponse=r=>{const o=r.participant;this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.handleParticipantUpdates([o,...r.otherParticipants]),r.room&&this.handleRoomUpdate(r.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(r.sifTrailer)},this.attemptConnection=(r,o,a,c)=>m(this,void 0,void 0,function*(){var u,l,h;this.state===Y.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},kr),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(r,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(_.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const p=new te("could not establish signal connection");throw f instanceof Error&&(p.message="".concat(p.message,": ").concat(f.message)),f instanceof te&&(p.reason=f.reason,p.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),p}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ne()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ne()&&(document.addEventListener("freeze",this.onPageLeave),(h=navigator.mediaDevices)===null||h===void 0||h.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(Y.Connected),this.emit(_.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return m(t,void 0,void 0,function*(){var o,a,c,u;const l=yield this.disconnectLock.lock();try{if(this.state===Y.Disconnected){this.log.debug("already disconnected",this.logContext);return}this.log.info("disconnect from room",Object.assign({},this.logContext)),(this.state===Y.Connecting||this.state===Y.Reconnecting||this.isResuming)&&(this.log.warn("abort connection attempt",this.logContext),(o=this.abortController)===null||o===void 0||o.abort(),(c=(a=this.connectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new te("Client initiated disconnect")),this.connectFuture=void 0),!((u=this.engine)===null||u===void 0)&&u.client.isDisconnected||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(r,si.CLIENT_INITIATED),this.engine=void 0}finally{l()}})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const r=[],o=ki();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Ts();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(_.Disconnected,()=>{c==null||c.remove(),c=null})}r.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{r.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...r.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const r=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{r.includes(u)||r.push(u)})});yield Promise.all(r.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const r of this.remoteParticipants.values())this.handleParticipantDisconnected(r.identity,r);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(_.Reconnecting)},this.handleSignalRestarted=r=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(r.serverRegion),Object.assign(Object.assign({},this.logContext),{region:r.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(r);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:r.serverRegion}))}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(_.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=r=>{r.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Ei.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=r=>{const o=[],a={};r.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(_.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=r=>{const o=new Map;this.activeSpeakers.forEach(c=>{o.set(c.sid,c)}),r.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(_.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=r=>{r.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);!c||!c.track||(c.track.streamState=C.streamStateFromProto(o.state),a.emit(N.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(_.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=r=>{const o=this.getRemoteParticipantBySid(r.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(r.trackSid);a&&a.setAllowed(r.allowed)},this.handleSubscriptionError=r=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(r.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(r.trackSid);a&&a.setSubscriptionError(r.err)},this.handleDataPacket=(r,o)=>{const a=this.remoteParticipants.get(r.participantIdentity);this.emit(_.DataReceived,r.payload,a,o,r.topic),a==null||a.emit(N.DataReceived,r.payload,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(_.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=r=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:r})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(_.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(_.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(_.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){this.emit(_.MediaDevicesChanged)}),this.handleRoomUpdate=r=>{const o=this.roomInfo;this.roomInfo=r,o&&o.metadata!==r.metadata&&this.emitWhenConnected(_.RoomMetadataChanged,r.metadata),(o==null?void 0:o.activeRecording)!==r.activeRecording&&this.emitWhenConnected(_.RecordingStatusChanged,r.activeRecording)},this.handleConnectionQualityUpdate=r=>{r.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=r=>{this.emit(_.ParticipantMetadataChanged,r,this.localParticipant)},this.onLocalParticipantNameChanged=r=>{this.emit(_.ParticipantNameChanged,r,this.localParticipant)},this.onLocalTrackMuted=r=>{this.emit(_.TrackMuted,r,this.localParticipant)},this.onLocalTrackUnmuted=r=>{this.emit(_.TrackUnmuted,r,this.localParticipant)},this.onLocalTrackPublished=r=>m(this,void 0,void 0,function*(){var o,a,c,u;(c=(a=(o=r.track)===null||o===void 0?void 0:o.getProcessor())===null||a===void 0?void 0:a.onPublish)===null||c===void 0||c.call(a,this),this.emit(_.LocalTrackPublished,r,this.localParticipant),r.track instanceof De&&(yield r.track.checkForSilence())&&this.emit(_.LocalAudioSilenceDetected,r);const l=yield(u=r.track)===null||u===void 0?void 0:u.getDeviceId(),h=Od(r.source);h&&l&&l!==this.localParticipant.activeDeviceMap.get(h)&&(this.localParticipant.activeDeviceMap.set(h,l),this.emit(_.ActiveDeviceChanged,h,l))}),this.onLocalTrackUnpublished=r=>{this.emit(_.LocalTrackUnpublished,r,this.localParticipant)},this.onLocalConnectionQualityChanged=r=>{this.emit(_.ConnectionQualityChanged,r,this.localParticipant)},this.onMediaDevicesError=r=>{this.emit(_.MediaDevicesError,r)},this.onLocalParticipantPermissionsChanged=r=>{this.emit(_.ParticipantPermissionsChanged,r,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},oh),e),this.log=ai((n=this.options.loggerName)!==null&&n!==void 0?n:St.Room),this.options.audioCaptureDefaults=Object.assign(Object.assign({},rc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},oc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rh),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ze,this.localParticipant=new So("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Si(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Si(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Si(this.options.audioOutput.deviceId)).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([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")})}setupE2EE(){var e;this.options.e2ee&&(this.e2eeManager=new Hd(this.options.e2ee),this.e2eeManager.on(vi.ParticipantEncryptionStatusChanged,(t,n)=>{n instanceof So&&(this.isE2EEEnabled=t),this.emit(_.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(vi.EncryptionError,t=>this.emit(_.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomSid:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,identity:this.localParticipant.identity}}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 m(this,void 0,void 0,function*(){return this.state===Y.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(I.RoomUpdate,n),e(s.sid))};this.engine.on(I.RoomUpdate,n),this.once(_.Disconnected,()=>{this.engine.off(I.RoomUpdate,n),t("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.isClosed||(this.engine=new uh(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents()}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.DCBufferStatusChanged,(e,t)=>{this.emit(_.DCBufferStatusChanged,e,t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(er(new URL(e))&&t){this.regionUrlProvider=new vo(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(oo(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(oo(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}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 n=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new ke({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new ke({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new ke({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new ke({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ke({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ke({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":s=new ke({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Be({reason:si.CLIENT_INITIATED,canReconnect:!0}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new ke({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;var s,r,o;return m(this,void 0,void 0,function*(){let a=!1,c=!0;const u=n?{exact:t}:t;if(e==="audioinput"){const l=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=u,a=l!==u;const h=Array.from(this.localParticipant.audioTrackPublications.values()).filter(f=>f.source===C.Source.Microphone);try{c=(yield Promise.all(h.map(f=>{var p;return(p=f.audioTrack)===null||p===void 0?void 0:p.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.audioCaptureDefaults.deviceId=l,f}}else if(e==="videoinput"){const l=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=u,a=l!==u;const h=Array.from(this.localParticipant.videoTrackPublications.values()).filter(f=>f.source===C.Source.Camera);try{c=(yield Promise.all(h.map(f=>{var p;return(p=f.videoTrack)===null||p===void 0?void 0:p.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.videoCaptureDefaults.deviceId=l,f}}else if(e==="audiooutput"){if(!Zs()&&!this.options.webAudioMix||this.options.webAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");(s=(o=this.options).audioOutput)!==null&&s!==void 0||(o.audioOutput={});const l=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,a=l!==u;try{this.options.webAudioMix?(r=this.audioContext)===null||r===void 0||r.setSinkId(t):yield Promise.all(Array.from(this.remoteParticipants.values()).map(h=>h.setAudioOutput({deviceId:t})))}catch(h){throw this.options.audioOutput.deviceId=l,h}}return a&&c&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(_.ActiveDeviceChanged,e,t)),c})}setupLocalParticipantEvents(){this.localParticipant.on(N.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(N.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(N.TrackMuted,this.onLocalTrackMuted).on(N.TrackUnmuted,this.onLocalTrackUnmuted).on(N.LocalTrackPublished,this.onLocalTrackPublished).on(N.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(N.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(N.MediaDevicesError,this.onMediaDevicesError).on(N.AudioStreamAcquired,this.startAudio).on(N.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){const l=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(_.Reconnected,l),this.off(_.Connected,l),this.off(_.Disconnected,h)};this.once(_.Reconnected,l),this.once(_.Connected,l),this.once(_.Disconnected,h);return}if(this.state===Y.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}const s=Ad(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let u;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?u=this.options.adaptiveStream:u={}),c.addSubscribedMediaTrack(e,a,t,n,u)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.state!==Y.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e&&((r=s.track)===null||r===void 0||r.detach(),(o=s.track)===null||o===void 0||o.stop())}),this.localParticipant.off(N.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(N.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(N.TrackMuted,this.onLocalTrackMuted).off(N.TrackUnmuted,this.onLocalTrackUnmuted).off(N.LocalTrackPublished,this.onLocalTrackPublished).off(N.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(N.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(N.MediaDevicesError,this.onMediaDevicesError).off(N.AudioStreamAcquired,this.startAudio).off(N.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),Ne()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(_.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(_.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return m(this,void 0,void 0,function*(){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=Ya())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext);const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(_.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=rs.fromParticipantInfo(this.engine.client,t):s=new rs(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(_.ParticipantConnected,n),n.on(N.TrackPublished,s=>{this.emitWhenConnected(_.TrackPublished,s,n)}).on(N.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(R.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(R.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(_.TrackSubscribed,s,r,n)}).on(N.TrackUnpublished,s=>{this.emit(_.TrackUnpublished,s,n)}).on(N.TrackUnsubscribed,(s,r)=>{this.emit(_.TrackUnsubscribed,s,r,n)}).on(N.TrackSubscriptionFailed,s=>{this.emit(_.TrackSubscriptionFailed,s,n)}).on(N.TrackMuted,s=>{this.emitWhenConnected(_.TrackMuted,s,n)}).on(N.TrackUnmuted,s=>{this.emitWhenConnected(_.TrackUnmuted,s,n)}).on(N.ParticipantMetadataChanged,s=>{this.emitWhenConnected(_.ParticipantMetadataChanged,s,n)}).on(N.ParticipantNameChanged,s=>{this.emitWhenConnected(_.ParticipantNameChanged,s,n)}).on(N.ConnectionQualityChanged,s=>{this.emitWhenConnected(_.ConnectionQualityChanged,s,n)}).on(N.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(_.ParticipantPermissionsChanged,s,n)}).on(N.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(_.TrackSubscriptionStatusChanged,s,r,n)}).on(N.TrackSubscriptionFailed,(s,r)=>{this.emit(_.TrackSubscriptionFailed,s,n,r)}).on(N.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(_.TrackSubscriptionPermissionChanged,s,r,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&t instanceof hc&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Te.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,si.STATE_MISMATCH))):e=0},wh)}clearConnectionReconcile(){this.connectionReconcileInterval&&Te.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(_.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Y.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){var t,n;return m(this,void 0,void 0,function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ki({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:F.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Le({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(_.SignalConnected),this.emit(_.Connected),this.setAndEmitConnectionState(Y.Connected),s.video){const o=new ss(C.Kind.Video,new Ie({source:ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO,name:"video-dummy"}),new Fe(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ro(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(N.LocalTrackPublished,o)}if(s.audio){const o=new ss(C.Kind.Audio,new Ie({source:ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO}),new De(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ts(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(N.LocalTrackPublished,o)}for(let o=0;o<r.count-1;o+=1){let a=new Le({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Ei.ACTIVE,tracks:[],joinedAt:F.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(r.video){const u=ro(160*((n=r.aspectRatios[o%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new Ie({source:ce.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO});c.addSubscribedMediaTrack(u,l.sid,new MediaStream([u])),a.tracks=[...a.tracks,l]}if(r.audio){const u=Ts(),l=new Ie({source:ce.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Se.AUDIO});c.addSubscribedMediaTrack(u,l.sid,new MediaStream([u])),a.tracks=[...a.tracks,l]}c.updateInfo(a)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==_.ActiveSpeakersChanged){const r=pc(n).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}function pc(i){return i.map(e=>{if(e)return Array.isArray(e)?pc(e):typeof e=="object"?"logContext"in e&&e.logContext:e})}var qe;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(qe||(qe={}));class Xi extends wt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qe.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new fc(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return m(this,void 0,void 0,function*(){if(this.status!==qe.IDLE)throw Error("check is running already");this.setStatus(qe.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==qe.SKIPPED&&this.setStatus(this.isSuccess()?qe.SUCCESS:qe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return m(this,void 0,void 0,function*(){return this.room.state===Y.Connected?this.room:(yield this.room.connect(this.url,this.token),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==Y.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qe.SKIPPED)}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}}}function mc(i){var e,t;return m(this,void 0,void 0,function*(){i??(i={}),(e=i.audio)!==null&&e!==void 0||(i.audio=!0),(t=i.video)!==null&&t!==void 0||(i.video=!0);const n=Ka(i,rc,oc),s=ls(n),r=navigator.mediaDevices.getUserMedia(s);i.audio&&(Pe.userMediaPromiseMap.set("audioinput",r),r.catch(()=>Pe.userMediaPromiseMap.delete("audioinput"))),i.video&&(Pe.userMediaPromiseMap.set("videoinput",r),r.catch(()=>Pe.userMediaPromiseMap.delete("videoinput")));const o=yield r;return o.getTracks().map(a=>{const c=a.kind==="audio";c?i.audio:i.video;let u;const l=c?s.audio:s.video;typeof l!="boolean"&&(u=l),u?u.deviceId=a.getSettings().deviceId:u={deviceId:a.getSettings().deviceId};const h=ac(a,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=o,h})})}function Eh(i){return m(this,void 0,void 0,function*(){return(yield mc({audio:!1,video:i}))[0]})}function Ph(i){return m(this,void 0,void 0,function*(){return(yield mc({audio:i,video:!1}))[0]})}class _h extends Xi{get description(){return"Can publish audio"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Ph();t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&o.mediaType==="audio"&&(r=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))})}}class Rh extends Xi{get description(){return"Can publish video"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Eh();t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&o.mediaType==="video"&&(r=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}}class Oh extends Xi{get description(){return"Resuming connection after interruption"}perform(){var e;return m(this,void 0,void 0,function*(){const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(c=>{setTimeout(c,5e3),r=c});t.on(_.Reconnecting,()=>{n=!0}).on(_.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield o,n){if(!s||t.state!==Y.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 xh extends Xi{get description(){return"Can connect via TURN"}perform(){var e,t;return m(this,void 0,void 0,function*(){const n=new br,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,o=!1,a=!1;for(let c of s.iceServers)for(let u of c.urls)u.startsWith("turn:")?(o=!0,a=!0):u.startsWith("turns:")&&(o=!0,a=!0,r=!0),u.startsWith("stun:")&&(a=!0);a?o&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.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 Ih extends Xi{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(_.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const o=new RTCIceCandidate(s);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Nh(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(a)}n&&n(s,r)},this.room.engine.pcManager&&(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(),$.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 Nh(i){const e=i.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 Ah extends Xi{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return m(this,void 0,void 0,function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new br;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===zi.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield s.close()})}}class Jh extends wt.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:qe.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!==qe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Ih)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(xh)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Oh)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(_h)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Rh)})}}function Mh(){const i=document.createElement("style");return i.textContent=`
|
|
55
55
|
* {
|
|
56
56
|
cursor: crosshair !important;
|
|
57
57
|
}
|
|
@@ -60,4 +60,4 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
|
60
60
|
pointer-events: none !important;
|
|
61
61
|
user-select: none !important;
|
|
62
62
|
}
|
|
63
|
-
`,i}function Lh(i){xc(i,"svelte-10y2zdk",'#liveroom-client-element.svelte-10y2zdk.svelte-10y2zdk{font-family:Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;line-height:1.5;font-weight:400;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}#users-container.svelte-10y2zdk.svelte-10y2zdk{z-index:999999;position:fixed;inset:0;overflow:hidden;pointer-events:none}.user.svelte-10y2zdk.svelte-10y2zdk{z-index:10;position:absolute;top:0;left:0;user-select:none;transform:translate(var(--x), var(--y));transition:transform 100ms linear;will-change:transform}.user[data-isfocusmode="true"].svelte-10y2zdk.svelte-10y2zdk{transform:translate(calc(50vw - 350px), calc(50svh - 200px)) scale(4)}.user.svelte-10y2zdk .cursor.svelte-10y2zdk{position:absolute;top:0;left:0;color:var(--color);transform-origin:top left;transform:rotate(6deg)}.user[data-isself="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{display:none}.user[data-isfocusmode="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{opacity:0}.user-label.svelte-10y2zdk.svelte-10y2zdk{font-weight:600;font-size:12px;color:black;background-color:var(--color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:9999px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05);display:flex;flex-direction:column;align-items:center}.user-label[data-cameraenabled="false"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:18px;left:14px}.user-label[data-cameraenabled="true"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:10px;left:6px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{position:absolute;top:0;left:0;background-color:transparent;overflow:visible;box-shadow:none}.user[data-isself="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk .user-name.svelte-10y2zdk{display:flex;justify-content:center;align-items:center;background-color:var(--color)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] .user-name.svelte-10y2zdk{padding:4px 10px}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="true"] .user-name.svelte-10y2zdk{position:absolute;inset-inline:0;bottom:0;padding:2px 0 4px 0}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label .user-name.svelte-10y2zdk{transform:translate(0, -4px) scale(0.3);border-radius:9999px;padding:4px 16px;width:fit-content}.user-label.svelte-10y2zdk #video-container.svelte-10y2zdk{overflow:hidden;display:flex;justify-content:center;align-items:center}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:100px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:auto;border-radius:4px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] #video-container.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk #video-container video.svelte-10y2zdk{height:100%;aspect-ratio:16 / 9;transform:scaleX(-1);margin-bottom:30px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container video.svelte-10y2zdk{margin-bottom:0}.user.svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0);z-index:-1;position:absolute;top:-60px;left:-60px;width:120px;height:120px;border-radius:9999px;border:1px solid var(--color75);background-color:var(--color25);transition:transform 200ms ease-in-out;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user.svelte-10y2zdk .halo[data-show="true"].svelte-10y2zdk{transform:scale(1)}.user[data-isfocusmode="true"].svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0) !important}#focus_mode_dialog.svelte-10y2zdk.svelte-10y2zdk{z-index:999998;position:fixed;inset:0;background-color:rgb(39, 39, 42, 0.25);backdrop-filter:blur(6px)}')}function So(i,e,t){const n=i.slice();return n[30]=e[t],n[31]=e,n[32]=t,n}function wo(i){let e,t=[],n=new Map,s=Or(Object.values(i[2]));const r=o=>o[30].id;for(let o=0;o<s.length;o+=1){let a=So(i,s,o),c=r(a);n.set(c,t[o]=Eo(c,a))}return{c(){e=$e("div");for(let o=0;o<t.length;o+=1)t[o].c();V(e,"id","users-container"),V(e,"class","svelte-10y2zdk")},m(o,a){Si(o,e,a);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(o,a){a[0]&30&&(s=Or(Object.values(o[2])),t=Hc(t,a,r,1,o,s,n,e,$c,Eo,null,So))},d(o){o&&yi(e);for(let a=0;a<t.length;a+=1)t[a].d()}}}function Eo(i,e){let t,n,s,r,o,a,c,u,l=e[30],h,f,p=e[30].name+"",v,y,R,S,w,$,K,me,de;const U=()=>e[14](c,l),ee=()=>e[14](null,l);return{key:i,first:null,c(){t=$e("div"),n=_r("svg"),s=_r("path"),r=an(),o=$e("div"),a=$e("div"),c=$e("video"),h=an(),f=$e("div"),v=rr(p),R=an(),S=$e("div"),$=an(),V(s,"d","M2.2706 0.0593359L25.4277 8.05957H25.45926C25.65896 8.13153 25.83096 8.25952 25.95221 8.42653C26.07357 8.59354 26.13851 8.79166 26.13851 8.99459C26.13851 9.19751 26.07357 9.39564 25.95221 9.56265C25.83096 9.72966 25.65896 9.85765 25.45926 9.92962L15.3543 13.7698L11.3124 23.37C11.2344 23.5561 11.0994 23.7156 10.9248 23.828C10.7503 23.9402 10.5443 24.0002 10.3335 24C10.1172 24 9.9061 23.9365 9.7291 23.8184C9.552 23.7004 9.4176 23.5332 9.344 23.34L0.9233 1.33937C0.8555 1.16076 0.8426 0.967504 0.8861 0.782189C0.9297 0.596873 1.0278 0.427163 1.1691 0.292901C1.3105 0.158639 1.4891 0.0653762 1.6841 0.0240151C1.8792 -0.0173461 2.0826 -0.00509504 2.2706 0.0593359Z"),V(n,"width","23"),V(n,"viewBox","0 0 27 24"),V(n,"fill","currentColor"),V(n,"aria-hidden","true"),V(n,"xmlns","http://www.w3.org/2000/svg"),V(n,"class","cursor svelte-10y2zdk"),V(c,"id",u=`user-video-${e[30].id}`),V(c,"class","svelte-10y2zdk"),V(a,"id","video-container"),V(a,"class","svelte-10y2zdk"),V(f,"class","user-name svelte-10y2zdk"),V(o,"class","user-label svelte-10y2zdk"),V(o,"data-cameraenabled",y=e[30].camera_enabled),V(S,"class","halo svelte-10y2zdk"),V(S,"data-show",w=(e[30].id==e[1].id&&e[30].is_shift_key_down||e[30].id!=e[1].id&&(e[30].is_shift_key_down||e[30].is_mouse_down))&&e[4]>1),V(t,"id",K="user-"+e[30].id),V(t,"class","user svelte-10y2zdk"),V(t,"data-isself",me=e[30].id==e[1].id),V(t,"data-isfocusmode",de=e[30].is_f_key_down),nt(t,"--color",e[30].color),nt(t,"--color25",e[30].color+"25"),nt(t,"--color75",e[30].color+"75"),nt(t,"--x",parseFloat(e[30].x)+"vw"),nt(t,"--y",parseFloat(e[30].y)+"vh"),this.first=t},m(M,H){Si(M,t,H),Ae(t,n),Ae(n,s),Ae(t,r),Ae(t,o),Ae(o,a),Ae(a,c),U(),Ae(o,h),Ae(o,f),Ae(f,v),Ae(t,R),Ae(t,S),Ae(t,$)},p(M,H){e=M,H[0]&4&&u!==(u=`user-video-${e[30].id}`)&&V(c,"id",u),l!==e[30]&&(ee(),l=e[30],U()),H[0]&4&&p!==(p=e[30].name+"")&&Dc(v,p),H[0]&4&&y!==(y=e[30].camera_enabled)&&V(o,"data-cameraenabled",y),H[0]&22&&w!==(w=(e[30].id==e[1].id&&e[30].is_shift_key_down||e[30].id!=e[1].id&&(e[30].is_shift_key_down||e[30].is_mouse_down))&&e[4]>1)&&V(S,"data-show",w),H[0]&4&&K!==(K="user-"+e[30].id)&&V(t,"id",K),H[0]&6&&me!==(me=e[30].id==e[1].id)&&V(t,"data-isself",me),H[0]&4&&de!==(de=e[30].is_f_key_down)&&V(t,"data-isfocusmode",de),H[0]&4&&nt(t,"--color",e[30].color),H[0]&4&&nt(t,"--color25",e[30].color+"25"),H[0]&4&&nt(t,"--color75",e[30].color+"75"),H[0]&4&&nt(t,"--x",parseFloat(e[30].x)+"vw"),H[0]&4&&nt(t,"--y",parseFloat(e[30].y)+"vh")},d(M){M&&yi(t),ee()}}}function Po(i){let e;return{c(){e=$e("div"),V(e,"id","focus_mode_dialog"),V(e,"role","dialog"),V(e,"class","svelte-10y2zdk")},m(t,n){Si(t,e,n)},d(t){t&&yi(e)}}}function Uh(i){let e,t,n,s=i[1]&&i[2]&&wo(i),r=i[0]&&Po();return{c(){e=$e("div"),s&&s.c(),t=an(),r&&r.c(),n=Ac(),V(e,"id","liveroom-client-element"),V(e,"class","svelte-10y2zdk")},m(o,a){Si(o,e,a),s&&s.m(e,null),Si(o,t,a),r&&r.m(o,a),Si(o,n,a)},p(o,a){o[1]&&o[2]?s?s.p(o,a):(s=wo(o),s.c(),s.m(e,null)):s&&(s.d(1),s=null),o[0]?r||(r=Po(),r.c(),r.m(n.parentNode,n)):r&&(r.d(1),r=null)},i:kn,o:kn,d(o){o&&(yi(e),yi(t),yi(n)),s&&s.d(),r&&r.d(o)}}}function nr(i,e){if(i.tagName==="BODY")return window;if(sr(i))return i;const{overflowY:t,overflowX:n}=getComputedStyle(i);return e==="vertical"&&["auto","scroll"].includes(t)&&i.scrollHeight>i.clientHeight||e==="horizontal"&&["auto","scroll"].includes(n)&&i.scrollWidth>i.clientWidth?i:i.parentElement?nr(i.parentElement,e):window}function sr(i){return i.tagName==="ION-CONTENT"&&typeof i.scrollByPoint=="function"}function Fh(i,e,t){let{version:n}=e,{url:s}=e,{room_id:r}=e,{user_name:o=void 0}=e,{user_color:a=void 0}=e,c,u,l=!1,h=!1,f=Mh(),p=Dh(),v,y,R,S,w={},$;Uc(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${o}')... (v${n})`),me()}),Fc(()=>{de(),Zi(),t(0,h=!1)});async function K(){if(console.log("[LiveKit] Beginning setup..."),t(10,u=new hc({dynacast:!0}).on(P.TrackSubscribed,async(I,Ce,Te)=>{switch(console.log("[LiveKit] Track Subscribed",I,Ce,Te),console.table({identity:Te.identity,source:Ce.source}),Ce.source){case C.Source.Camera:{const it=w[Te.identity];it&&(console.log(`[LiveKit] Attaching user camera (identity ${Te.identity})`),I.attach(it));break}}})),console.log("[LiveKit] Created room",u.name),!R)throw new Error("LiveKit websocket URL not set");if(!S)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${R}'...`),await u.connect(R,S,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",u.name)}function me(){c=new Qu({url:s,topic:`liveroom-livestate:${r}`,params:{room_id:r,user_name:o,user_color:a,referrer:document.referrer,current_url:window.location.href,window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,language:window.navigator.language,user_agent:window.navigator.userAgent},socketOptions:{logger:null}}),c.addEventListener("wheel-from-another-user",({detail:{delta_x:I,delta_y:Ce,x:Te,y:it}})=>{const Y=parseInt(I),Je=parseInt(Ce),An=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(Te)/100,clientY:window.innerHeight*parseFloat(it)/100,deltaX:Y,deltaY:Je,deltaMode:0}),oe=document.head.contains(p);oe&&document.head.removeChild(p);const Ii=document.elementFromPoint(An.clientX,An.clientY);if(oe&&document.head.appendChild(p),Ii instanceof HTMLElement||Ii instanceof SVGElement)if(Math.abs(Je)>=Math.abs(Y)){const _t=nr(Ii,"vertical");sr(_t)?_t.scrollByPoint(0,Je,0):_t.scrollBy({top:Je,left:0,behavior:"instant"})}else{const _t=nr(Ii,"horizontal");sr(_t)?_t.scrollByPoint(Y,0,0):_t.scrollBy({top:0,left:Y,behavior:"instant"})}}),c.addEventListener("click-from-another-user",({detail:{x:I,y:Ce}})=>{const Te=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1,clientX:window.innerWidth*parseFloat(I)/100,clientY:window.innerHeight*parseFloat(Ce)/100}),it=document.head.contains(p);it&&document.head.removeChild(p);const Y=document.elementFromPoint(Te.clientX,Te.clientY);Y==null||Y.dispatchEvent(Te),it&&document.head.appendChild(p)}),c.addEventListener("livestate-change",({detail:{state:I}})=>{var Ce,Te;(Ce=I==null?void 0:I.me)!=null&&Ce.name&&I.me.name!=(v==null?void 0:v.name)&&(sessionStorage==null||sessionStorage.setItem(Er.SESSION_STORAGE_KEY_USER_NAME,I.me.name)),(Te=I==null?void 0:I.me)!=null&&Te.color&&I.me.color!=(v==null?void 0:v.color)&&(sessionStorage==null||sessionStorage.setItem(Er.SESSION_STORAGE_KEY_USER_COLOR,I.me.color)),t(5,r=I.room_id),t(1,v=I.me),t(2,y=I.users),t(12,R=I.livekit_ws_url),t(13,S=I.livekit_token)}),c.connect(),window.addEventListener("mousemove",U),window.addEventListener("mousedown",ee),window.addEventListener("mouseup",M),window.addEventListener("keydown",Pt),window.addEventListener("keyup",tt),window.addEventListener("resize",Xi)}function de(){window.removeEventListener("resize",Xi),window.removeEventListener("keyup",tt),window.removeEventListener("keydown",Pt),window.removeEventListener("mouseup",M),window.removeEventListener("mousedown",ee),window.removeEventListener("mousemove",U),c==null||c.disconnect(),c=void 0,u==null||u.disconnect(),t(10,u=void 0)}function U(I){c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:v.id,x:Number(I.clientX/window.innerWidth*100).toFixed(2),y:Number(I.clientY/window.innerHeight*100).toFixed(2)}}))}function ee(){c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:v.id}}))}function M(){c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:v.id}}))}const H=["Shift"];function Pt(I){!I.repeat&&H.includes(I.key)&&c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("key_down",{detail:{key:I.key,user_id:v.id}}))}function tt(I){H.includes(I.key)&&c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("key_up",{detail:{key:I.key,user_id:v.id}}))}function Xi(){setTimeout(()=>{c&&(v!=null&&v.id)&&c.dispatchEvent(new CustomEvent("window_resize",{detail:{window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,user_id:v.id}}))},100)}function Qi(){document.head.appendChild(f),document.head.appendChild(p),t(11,l=!0)}function Zi(){document.head.removeChild(f),document.head.removeChild(p),t(11,l=!1)}function Nn(I,Ce){Ps[I?"unshift":"push"](()=>{w[Ce.id]=I,t(3,w)})}return i.$$set=I=>{"version"in I&&t(6,n=I.version),"url"in I&&t(7,s=I.url),"room_id"in I&&t(5,r=I.room_id),"user_name"in I&&t(8,o=I.user_name),"user_color"in I&&t(9,a=I.user_color)},i.$$.update=()=>{i.$$.dirty[0]&13318&&!u&&v&&y&&R&&S&&K(),i.$$.dirty[0]&4&&t(4,$=Object.keys(y||{}).length),i.$$.dirty[0]&2052&&!l&&y&&Object.values(y).some(I=>I.type=="admin"&&I.is_b_key_down)&&Qi(),i.$$.dirty[0]&2052&&l&&y&&Object.values(y).filter(I=>I.type=="admin").every(I=>!I.is_b_key_down)&&Zi(),i.$$.dirty[0]&5&&!h&&y&&Object.values(y).some(I=>I.type=="admin"&&I.is_f_key_down)&&t(0,h=!0),i.$$.dirty[0]&5&&h&&y&&Object.values(y).filter(I=>I.type=="admin").every(I=>!I.is_f_key_down)&&t(0,h=!1)},[h,v,y,w,$,r,n,s,o,a,u,l,R,S,Nn]}class mc extends Xc{constructor(e){super(),Kc(this,e,Fh,Uh,Rc,{version:6,url:7,room_id:5,user_name:8,user_color:9},Lh,[-1,-1])}get version(){return this.$$.ctx[6]}set version(e){this.$$set({version:e}),Ti()}get url(){return this.$$.ctx[7]}set url(e){this.$$set({url:e}),Ti()}get room_id(){return this.$$.ctx[5]}set room_id(e){this.$$set({room_id:e}),Ti()}get user_name(){return this.$$.ctx[8]}set user_name(e){this.$$set({user_name:e}),Ti()}get user_color(){return this.$$.ctx[9]}set user_color(e){this.$$set({user_color:e}),Ti()}}customElements.define("liveroom-client-element",Yc(mc,{version:{},url:{},room_id:{},user_name:{},user_color:{}},[],[],!0));module.exports=mc;
|
|
63
|
+
`,i}function Lh(i){xc(i,"svelte-10y2zdk",'#liveroom-client-element.svelte-10y2zdk.svelte-10y2zdk{font-family:Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;line-height:1.5;font-weight:400;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}#users-container.svelte-10y2zdk.svelte-10y2zdk{z-index:999999;position:fixed;inset:0;overflow:hidden;pointer-events:none}.user.svelte-10y2zdk.svelte-10y2zdk{z-index:10;position:absolute;top:0;left:0;user-select:none;transform:translate(var(--x), var(--y));transition:transform 100ms linear;will-change:transform}.user[data-isfocusmode="true"].svelte-10y2zdk.svelte-10y2zdk{transform:translate(calc(50vw - 350px), calc(50svh - 200px)) scale(4)}.user.svelte-10y2zdk .cursor.svelte-10y2zdk{position:absolute;top:0;left:0;color:var(--color);transform-origin:top left;transform:rotate(6deg)}.user[data-isself="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{display:none}.user[data-isfocusmode="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{opacity:0}.user-label.svelte-10y2zdk.svelte-10y2zdk{font-weight:600;font-size:12px;color:black;background-color:var(--color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:9999px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05);display:flex;flex-direction:column;align-items:center}.user-label[data-cameraenabled="false"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:18px;left:14px}.user-label[data-cameraenabled="true"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:10px;left:6px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{position:absolute;top:0;left:0;background-color:transparent;overflow:visible;box-shadow:none}.user[data-isself="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk .user-name.svelte-10y2zdk{display:flex;justify-content:center;align-items:center;background-color:var(--color)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] .user-name.svelte-10y2zdk{padding:4px 10px}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="true"] .user-name.svelte-10y2zdk{position:absolute;inset-inline:0;bottom:0;padding:2px 0 4px 0}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label .user-name.svelte-10y2zdk{transform:translate(0, -4px) scale(0.3);border-radius:9999px;padding:4px 16px;width:fit-content}.user-label.svelte-10y2zdk #video-container.svelte-10y2zdk{overflow:hidden;display:flex;justify-content:center;align-items:center}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:100px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:auto;border-radius:4px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] #video-container.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk #video-container video.svelte-10y2zdk{height:100%;aspect-ratio:16 / 9;transform:scaleX(-1);margin-bottom:30px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container video.svelte-10y2zdk{margin-bottom:0}.user.svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0);z-index:-1;position:absolute;top:-60px;left:-60px;width:120px;height:120px;border-radius:9999px;border:1px solid var(--color75);background-color:var(--color25);transition:transform 200ms ease-in-out;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user.svelte-10y2zdk .halo[data-show="true"].svelte-10y2zdk{transform:scale(1)}.user[data-isfocusmode="true"].svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0) !important}#focus_mode_dialog.svelte-10y2zdk.svelte-10y2zdk{z-index:999998;position:fixed;inset:0;background-color:rgb(39, 39, 42, 0.25);backdrop-filter:blur(6px)}')}function wo(i,e,t){const n=i.slice();return n[31]=e[t],n[32]=e,n[33]=t,n}function Eo(i){let e,t=[],n=new Map,s=xr(Object.values(i[2]));const r=o=>o[31].id;for(let o=0;o<s.length;o+=1){let a=wo(i,s,o),c=r(a);n.set(c,t[o]=Po(c,a))}return{c(){e=$e("div");for(let o=0;o<t.length;o+=1)t[o].c();q(e,"id","users-container"),q(e,"class","svelte-10y2zdk")},m(o,a){Ti(o,e,a);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(o,a){a[0]&30&&(s=xr(Object.values(o[2])),t=Hc(t,a,r,1,o,s,n,e,$c,Po,null,wo))},d(o){o&&yi(e);for(let a=0;a<t.length;a+=1)t[a].d()}}}function Po(i,e){let t,n,s,r,o,a,c,u,l=e[31],h,f,p=e[31].name+"",y,v,w,S,E,J,K,me,de;const U=()=>e[15](c,l),ee=()=>e[15](null,l);return{key:i,first:null,c(){t=$e("div"),n=Rr("svg"),s=Rr("path"),r=an(),o=$e("div"),a=$e("div"),c=$e("video"),h=an(),f=$e("div"),y=or(p),w=an(),S=$e("div"),J=an(),q(s,"d","M2.2706 0.0593359L25.4277 8.05957H25.45926C25.65896 8.13153 25.83096 8.25952 25.95221 8.42653C26.07357 8.59354 26.13851 8.79166 26.13851 8.99459C26.13851 9.19751 26.07357 9.39564 25.95221 9.56265C25.83096 9.72966 25.65896 9.85765 25.45926 9.92962L15.3543 13.7698L11.3124 23.37C11.2344 23.5561 11.0994 23.7156 10.9248 23.828C10.7503 23.9402 10.5443 24.0002 10.3335 24C10.1172 24 9.9061 23.9365 9.7291 23.8184C9.552 23.7004 9.4176 23.5332 9.344 23.34L0.9233 1.33937C0.8555 1.16076 0.8426 0.967504 0.8861 0.782189C0.9297 0.596873 1.0278 0.427163 1.1691 0.292901C1.3105 0.158639 1.4891 0.0653762 1.6841 0.0240151C1.8792 -0.0173461 2.0826 -0.00509504 2.2706 0.0593359Z"),q(n,"width","23"),q(n,"viewBox","0 0 27 24"),q(n,"fill","currentColor"),q(n,"aria-hidden","true"),q(n,"xmlns","http://www.w3.org/2000/svg"),q(n,"class","cursor svelte-10y2zdk"),q(c,"id",u=`user-video-${e[31].id}`),q(c,"class","svelte-10y2zdk"),q(a,"id","video-container"),q(a,"class","svelte-10y2zdk"),q(f,"class","user-name svelte-10y2zdk"),q(o,"class","user-label svelte-10y2zdk"),q(o,"data-cameraenabled",v=e[31].camera_enabled),q(S,"class","halo svelte-10y2zdk"),q(S,"data-show",E=(e[31].id==e[1].id&&e[31].is_shift_key_down||e[31].id!=e[1].id&&(e[31].is_shift_key_down||e[31].is_mouse_down))&&e[4]>1),q(t,"id",K="user-"+e[31].id),q(t,"class","user svelte-10y2zdk"),q(t,"data-isself",me=e[31].id==e[1].id),q(t,"data-isfocusmode",de=e[31].is_f_key_down),it(t,"--color",e[31].color),it(t,"--color25",e[31].color+"25"),it(t,"--color75",e[31].color+"75"),it(t,"--x",parseFloat(e[31].x)+"vw"),it(t,"--y",parseFloat(e[31].y)+"vh"),this.first=t},m(M,H){Ti(M,t,H),Me(t,n),Me(n,s),Me(t,r),Me(t,o),Me(o,a),Me(a,c),U(),Me(o,h),Me(o,f),Me(f,y),Me(t,w),Me(t,S),Me(t,J)},p(M,H){e=M,H[0]&4&&u!==(u=`user-video-${e[31].id}`)&&q(c,"id",u),l!==e[31]&&(ee(),l=e[31],U()),H[0]&4&&p!==(p=e[31].name+"")&&Dc(y,p),H[0]&4&&v!==(v=e[31].camera_enabled)&&q(o,"data-cameraenabled",v),H[0]&22&&E!==(E=(e[31].id==e[1].id&&e[31].is_shift_key_down||e[31].id!=e[1].id&&(e[31].is_shift_key_down||e[31].is_mouse_down))&&e[4]>1)&&q(S,"data-show",E),H[0]&4&&K!==(K="user-"+e[31].id)&&q(t,"id",K),H[0]&6&&me!==(me=e[31].id==e[1].id)&&q(t,"data-isself",me),H[0]&4&&de!==(de=e[31].is_f_key_down)&&q(t,"data-isfocusmode",de),H[0]&4&&it(t,"--color",e[31].color),H[0]&4&&it(t,"--color25",e[31].color+"25"),H[0]&4&&it(t,"--color75",e[31].color+"75"),H[0]&4&&it(t,"--x",parseFloat(e[31].x)+"vw"),H[0]&4&&it(t,"--y",parseFloat(e[31].y)+"vh")},d(M){M&&yi(t),ee()}}}function _o(i){let e;return{c(){e=$e("div"),q(e,"id","focus_mode_dialog"),q(e,"role","dialog"),q(e,"class","svelte-10y2zdk")},m(t,n){Ti(t,e,n)},d(t){t&&yi(e)}}}function Uh(i){let e,t,n,s=i[1]&&i[2]&&Eo(i),r=i[0]&&_o();return{c(){e=$e("div"),s&&s.c(),t=an(),r&&r.c(),n=Ac(),q(e,"id","liveroom-client-element"),q(e,"class","svelte-10y2zdk")},m(o,a){Ti(o,e,a),s&&s.m(e,null),Ti(o,t,a),r&&r.m(o,a),Ti(o,n,a)},p(o,a){o[1]&&o[2]?s?s.p(o,a):(s=Eo(o),s.c(),s.m(e,null)):s&&(s.d(1),s=null),o[0]?r||(r=_o(),r.c(),r.m(n.parentNode,n)):r&&(r.d(1),r=null)},i:kn,o:kn,d(o){o&&(yi(e),yi(t),yi(n)),s&&s.d(),r&&r.d(o)}}}function sr(i,e){if(i.tagName==="BODY")return window;if(rr(i))return i;const{overflowY:t,overflowX:n}=getComputedStyle(i);return e==="vertical"&&["auto","scroll"].includes(t)&&i.scrollHeight>i.clientHeight||e==="horizontal"&&["auto","scroll"].includes(n)&&i.scrollWidth>i.clientWidth?i:i.parentElement?sr(i.parentElement,e):window}function rr(i){return i.tagName==="ION-CONTENT"&&typeof i.scrollByPoint=="function"}function Fh(i,e,t){let{version:n}=e,{url:s}=e,{room_id:r}=e,{room_token:o}=e,{user_name:a=void 0}=e,{user_color:c=void 0}=e,u,l,h=!1,f=!1,p=Mh(),y=Dh(),v,w,S,E,J={},K;Uc(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${a}')... (v${n})`),de()}),Fc(()=>{U(),Zi(),t(0,f=!1)});async function me(){if(console.log("[LiveKit] Beginning setup..."),t(11,l=new fc({dynacast:!0}).on(_.TrackSubscribed,async(O,ge,ve)=>{switch(console.log("[LiveKit] Track Subscribed",O,ge,ve),console.table({identity:ve.identity,source:ge.source}),ge.source){case C.Source.Camera:{const Z=J[ve.identity];Z&&(console.log(`[LiveKit] Attaching user camera (identity ${ve.identity})`),O.attach(Z));break}}})),console.log("[LiveKit] Created room",l.name),!S)throw new Error("LiveKit websocket URL not set");if(!E)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${S}'...`),await l.connect(S,E,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",l.name)}function de(){console.log(`[Liveroom] Starting session on room ${r}`),u=new Qu({url:s,topic:`liveroom-livestate:rooms:${r}`,params:{room_id:r,room_token:o,user_name:a,user_color:c,referrer:document.referrer,current_url:window.location.href,window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,language:window.navigator.language,user_agent:window.navigator.userAgent},socketOptions:{logger:(O,ge,ve)=>{switch(O){case"error":console.error("Error in socket",ge,ve);break}}}}),u.addEventListener("wheel-from-another-user",({detail:{delta_x:O,delta_y:ge,x:ve,y:Z}})=>{const Ee=parseInt(O),Ii=parseInt(ge),oe=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(ve)/100,clientY:window.innerHeight*parseFloat(Z)/100,deltaX:Ee,deltaY:Ii,deltaMode:0}),Mn=document.head.contains(y);Mn&&document.head.removeChild(y);const Ni=document.elementFromPoint(oe.clientX,oe.clientY);if(Mn&&document.head.appendChild(y),Ni instanceof HTMLElement||Ni instanceof SVGElement)if(Math.abs(Ii)>=Math.abs(Ee)){const Pt=sr(Ni,"vertical");rr(Pt)?Pt.scrollByPoint(0,Ii,0):Pt.scrollBy({top:Ii,left:0,behavior:"instant"})}else{const Pt=sr(Ni,"horizontal");rr(Pt)?Pt.scrollByPoint(Ee,0,0):Pt.scrollBy({top:0,left:Ee,behavior:"instant"})}}),u.addEventListener("click-from-another-user",({detail:{x:O,y:ge}})=>{const ve=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(O)/100,clientY:window.innerHeight*parseFloat(ge)/100}),Z=document.head.contains(y);Z&&document.head.removeChild(y);const Ee=document.elementFromPoint(ve.clientX,ve.clientY);Ee==null||Ee.dispatchEvent(ve),Z&&document.head.appendChild(y)}),u.addEventListener("livestate-change",({detail:{state:O}})=>{var ge,ve;(ge=O==null?void 0:O.me)!=null&&ge.name&&O.me.name!=(v==null?void 0:v.name)&&(sessionStorage==null||sessionStorage.setItem(Pr.SESSION_STORAGE_KEY_USER_NAME,O.me.name)),(ve=O==null?void 0:O.me)!=null&&ve.color&&O.me.color!=(v==null?void 0:v.color)&&(sessionStorage==null||sessionStorage.setItem(Pr.SESSION_STORAGE_KEY_USER_COLOR,O.me.color)),t(5,r=O.room_id),t(1,v=O.me),t(2,w=O.users),t(13,S=O.livekit_ws_url),t(14,E=O.livekit_token)}),u.connect(),window.addEventListener("mousemove",ee),window.addEventListener("mousedown",M),window.addEventListener("mouseup",H),window.addEventListener("keydown",tt),window.addEventListener("keyup",Qi),window.addEventListener("resize",xi)}function U(){window.removeEventListener("resize",xi),window.removeEventListener("keyup",Qi),window.removeEventListener("keydown",tt),window.removeEventListener("mouseup",H),window.removeEventListener("mousedown",M),window.removeEventListener("mousemove",ee),u==null||u.disconnect(),u=void 0,l==null||l.disconnect(),t(11,l=void 0)}function ee(O){u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:v.id,x:Number(O.clientX/window.innerWidth*100).toFixed(2),y:Number(O.clientY/window.innerHeight*100).toFixed(2)}}))}function M(){u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:v.id}}))}function H(){u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:v.id}}))}const Et=["Shift"];function tt(O){!O.repeat&&Et.includes(O.key)&&u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("key_down",{detail:{key:O.key,user_id:v.id}}))}function Qi(O){Et.includes(O.key)&&u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("key_up",{detail:{key:O.key,user_id:v.id}}))}function xi(){setTimeout(()=>{u&&(v!=null&&v.id)&&u.dispatchEvent(new CustomEvent("window_resize",{detail:{window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,user_id:v.id}}))},100)}function Nn(){document.head.appendChild(p),document.head.appendChild(y),t(12,h=!0)}function Zi(){document.head.removeChild(p),document.head.removeChild(y),t(12,h=!1)}function An(O,ge){_s[O?"unshift":"push"](()=>{J[ge.id]=O,t(3,J)})}return i.$$set=O=>{"version"in O&&t(6,n=O.version),"url"in O&&t(7,s=O.url),"room_id"in O&&t(5,r=O.room_id),"room_token"in O&&t(8,o=O.room_token),"user_name"in O&&t(9,a=O.user_name),"user_color"in O&&t(10,c=O.user_color)},i.$$.update=()=>{i.$$.dirty[0]&26630&&!l&&v&&w&&S&&E&&me(),i.$$.dirty[0]&4&&t(4,K=Object.keys(w||{}).length),i.$$.dirty[0]&4100&&!h&&w&&Object.values(w).some(O=>O.type=="admin"&&O.is_b_key_down)&&Nn(),i.$$.dirty[0]&4100&&h&&w&&Object.values(w).filter(O=>O.type=="admin").every(O=>!O.is_b_key_down)&&Zi(),i.$$.dirty[0]&5&&!f&&w&&Object.values(w).some(O=>O.type=="admin"&&O.is_f_key_down)&&t(0,f=!0),i.$$.dirty[0]&5&&f&&w&&Object.values(w).filter(O=>O.type=="admin").every(O=>!O.is_f_key_down)&&t(0,f=!1)},[f,v,w,J,K,r,n,s,o,a,c,l,h,S,E,An]}class gc extends Xc{constructor(e){super(),Kc(this,e,Fh,Uh,Rc,{version:6,url:7,room_id:5,room_token:8,user_name:9,user_color:10},Lh,[-1,-1])}get version(){return this.$$.ctx[6]}set version(e){this.$$set({version:e}),hi()}get url(){return this.$$.ctx[7]}set url(e){this.$$set({url:e}),hi()}get room_id(){return this.$$.ctx[5]}set room_id(e){this.$$set({room_id:e}),hi()}get room_token(){return this.$$.ctx[8]}set room_token(e){this.$$set({room_token:e}),hi()}get user_name(){return this.$$.ctx[9]}set user_name(e){this.$$set({user_name:e}),hi()}get user_color(){return this.$$.ctx[10]}set user_color(e){this.$$set({user_color:e}),hi()}}customElements.define("liveroom-client-element",Yc(gc,{version:{},url:{},room_id:{},room_token:{},user_name:{},user_color:{}},[],[],!0));module.exports=gc;
|