liveroom-client-element 0.0.34 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var Uo=Object.defineProperty;var Fo=(i,e,t)=>e in i?Uo(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var L=(i,e,t)=>(Fo(i,typeof e!="symbol"?e+"":e,t),t);function Yi(){}function Vr(i){return i()}function Vs(){return Object.create(null)}function rn(i){i.forEach(Vr)}function $r(i){return typeof i=="function"}function Bo(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}function Jo(i){return Object.keys(i).length===0}function Oe(i,e){i.appendChild(e)}function jo(i,e,t){const n=Vo(i);if(!n.getElementById(e)){const s=Ye("style");s.id=e,s.textContent=t,$o(n,s)}}function Vo(i){if(!i)return document;const e=i.getRootNode?i.getRootNode():i.ownerDocument;return e&&e.host?e:i.ownerDocument}function $o(i,e){return Oe(i.head||i,e),e.sheet}function Ln(i,e,t){i.insertBefore(e,t||null)}function an(i){i.parentNode&&i.parentNode.removeChild(i)}function Ye(i){return document.createElement(i)}function $s(i){return document.createElementNS("http://www.w3.org/2000/svg",i)}function qr(i){return document.createTextNode(i)}function cn(){return qr(" ")}function z(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function qo(i){return Array.from(i.childNodes)}function Ho(i,e){e=""+e,i.data!==e&&(i.data=e)}function hi(i,e,t,n){t==null?i.style.removeProperty(e):i.style.setProperty(e,t,n?"important":"")}function Wo(i){const e={};return i.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let Xi;function ji(i){Xi=i}function Hr(){if(!Xi)throw new Error("Function called outside component initialization");return Xi}function Go(i){Hr().$$.on_mount.push(i)}function zo(i){Hr().$$.on_destroy.push(i)}const mi=[],ts=[];let bi=[];const qs=[],Ko=Promise.resolve();let is=!1;function Yo(){is||(is=!0,Ko.then(vi))}function ns(i){bi.push(i)}const Vn=new Set;let fi=0;function vi(){if(fi!==0)return;const i=Xi;do{try{for(;fi<mi.length;){const e=mi[fi];fi++,ji(e),Xo(e.$$)}}catch(e){throw mi.length=0,fi=0,e}for(ji(null),mi.length=0,fi=0;ts.length;)ts.pop()();for(let e=0;e<bi.length;e+=1){const t=bi[e];Vn.has(t)||(Vn.add(t),t())}bi.length=0}while(mi.length);for(;qs.length;)qs.pop()();is=!1,Vn.clear(),ji(i)}function Xo(i){if(i.fragment!==null){i.update(),rn(i.before_update);const e=i.dirty;i.dirty=[-1],i.fragment&&i.fragment.p(i.ctx,e),i.after_update.forEach(ns)}}function Qo(i){const e=[],t=[];bi.forEach(n=>i.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),bi=e}const Zo=new Set;function Wr(i,e){i&&i.i&&(Zo.delete(i),i.i(e))}function Hs(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function ec(i,e){i.d(1),e.delete(i.key)}function tc(i,e,t,n,s,r,a,o,c,u,d,h){let f=i.length,m=r.length,b=f;const T={};for(;b--;)T[i[b].key]=b;const w=[],I=new Map,D=new Map,Q=[];for(b=m;b--;){const q=h(s,r,b),K=t(q);let x=a.get(K);x?n&&Q.push(()=>x.p(q,e)):(x=u(K,q),x.c()),I.set(K,w[b]=x),K in T&&D.set(K,Math.abs(b-T[K]))}const j=new Set,ce=new Set;function ae(q){Wr(q,1),q.m(o,d),a.set(q.key,q),d=q.first,m--}for(;f&&m;){const q=w[m-1],K=i[f-1],x=q.key,F=K.key;q===K?(d=q.first,f--,m--):I.has(F)?!a.has(x)||j.has(x)?ae(q):ce.has(F)?f--:D.get(x)>D.get(F)?(ce.add(x),ae(q)):(j.add(F),f--):(c(K,a),f--)}for(;f--;){const q=i[f];I.has(q.key)||c(q,a)}for(;m;)ae(w[m-1]);return rn(Q),w}function ic(i,e,t){const{fragment:n,after_update:s}=i.$$;n&&n.m(e,t),ns(()=>{const r=i.$$.on_mount.map(Vr).filter($r);i.$$.on_destroy?i.$$.on_destroy.push(...r):rn(r),i.$$.on_mount=[]}),s.forEach(ns)}function nc(i,e){const t=i.$$;t.fragment!==null&&(Qo(t.after_update),rn(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function sc(i,e){i.$$.dirty[0]===-1&&(mi.push(i),Yo(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<<e%31}function rc(i,e,t,n,s,r,a=null,o=[-1]){const c=Xi;ji(i);const u=i.$$={fragment:null,ctx:[],props:r,update:Yi,not_equal:s,bound:Vs(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:Vs(),dirty:o,skip_bound:!1,root:e.target||c.$$.root};a&&a(u.root);let d=!1;if(u.ctx=t?t(i,e.props||{},(h,f,...m)=>{const b=m.length?m[0]:f;return u.ctx&&s(u.ctx[h],u.ctx[h]=b)&&(!u.skip_bound&&u.bound[h]&&u.bound[h](b),d&&sc(i,h)),f}):[],u.update(),d=!0,rn(u.before_update),u.fragment=n?n(u.ctx):!1,e.target){if(e.hydrate){const h=qo(e.target);u.fragment&&u.fragment.l(h),h.forEach(an)}else u.fragment&&u.fragment.c();e.intro&&Wr(i.$$.fragment),ic(i,e.target,e.anchor),vi()}ji(c)}let Gr;typeof HTMLElement=="function"&&(Gr=class extends HTMLElement{constructor(e,t,n){super();L(this,"$$ctor");L(this,"$$s");L(this,"$$c");L(this,"$$cn",!1);L(this,"$$d",{});L(this,"$$r",!1);L(this,"$$p_d",{});L(this,"$$l",{});L(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 a;return{c:function(){a=Ye("slot"),r!=="default"&&z(a,"name",r)},m:function(u,d){Ln(u,a,d)},d:function(u){u&&an(a)}}}};if(await Promise.resolve(),!this.$$cn)return;const t={},n=Wo(this);for(const r of this.$$s)r in n&&(t[r]=[e(r)]);for(const r of this.attributes){const a=this.$$g_p(r.name);a in this.$$d||(this.$$d[a]=pn(a,r.value,this.$$p_d,"toProp"))}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 a=pn(r,this.$$d[r],this.$$p_d,"toAttribute");a==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,a)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const a of this.$$l[r]){const o=this.$$c.$on(r,a);this.$$l_u.set(a,o)}this.$$l={}}}attributeChangedCallback(e,t,n){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=pn(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 pn(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 ac(i,e,t,n,s,r){let a=class extends Gr{constructor(){super(i,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(o=>(e[o].attribute||o).toLowerCase())}};return Object.keys(e).forEach(o=>{Object.defineProperty(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){var u;c=pn(o,c,e),this.$$d[o]=c,(u=this.$$c)==null||u.$set({[o]:c})}})}),n.forEach(o=>{Object.defineProperty(a.prototype,o,{get(){var c;return(c=this.$$c)==null?void 0:c[o]}})}),r&&(a=r(a)),i.element=a,a}class oc{constructor(){L(this,"$$");L(this,"$$set")}$destroy(){nc(this,1),this.$destroy=Yi}$on(e,t){if(!$r(t))return Yi;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&&!Jo(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const cc="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(cc);const{isArray:uc}=Array,dc=Object.keys,Qi=i=>{if(!i)return i;if(uc(i)){const e=[],t=i.length;for(let n=0;n<t;n++)e.push(Qi(i[n]));return e}else if(typeof i=="object"){const e=dc(i),t=e.length,n={};for(let s=0;s<t;s++){const r=e[s];n[r]=Qi(i[r])}return n}return i};class Me{constructor(e){L(this,"path");L(this,"from");this.path=e}}const lc=/~1/g,hc=/~0/g,fc=/~/g,pc=/\//g;function mc(i){return i.indexOf("~")===-1?i:i.replace(lc,"/").replace(hc,"~")}function gc(i){return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(fc,"~0").replace(pc,"~1")}function vc(i){return i?i.slice(1).split("/").map(mc):[]}function G(i){return yc(i)?"":"/"+i.map(e=>gc(String(e))).join("/")}const $=i=>typeof i=="string"?vc(i):i,yc=i=>!i.length,bc=Object.prototype.hasOwnProperty;function kc(i,e){return bc.call(i,e)}const{isArray:zr}=Array,ee=(i,e)=>{const t=e.length;if(!t)return{val:i};let n,s;for(let a=0;a<t;a++)if(n=i,s=e[a],zr(n)){const o=n.length;if(s==="-")s=o;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=kc(n,s)?n[s]:void 0;else throw new Error("NOT_FOUND");return{val:i,obj:n,key:s}},on=i=>zr(i.obj)&&typeof i.key=="number",Nn=i=>typeof i.obj=="object"&&typeof i.key=="string";class _s extends Me{constructor(t,n){super(t);L(this,"value");this.value=n}op(){return"add"}code(){return 0}apply(t){const{val:n,key:s,obj:r}=ee(t,this.path),a=Qi(this.value);if(!r)t=a;else if(typeof s=="string")r[s]=a;else{const o=r.length;if(s<o)r.splice(s,0,a);else{if(s>o)throw new Error("INVALID_INDEX");r.push(a)}}return{doc:t,old:n}}toJson(t){return{op:"add",path:G(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 Kr extends Me{constructor(t,n){super(t);L(this,"oldValue");this.oldValue=n}op(){return"remove"}code(){return 1}apply(t){const n=ee(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return Nn(n)?delete n.obj[n.key]:on(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:G(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 Tc extends Me{constructor(t,n,s){super(t);L(this,"value");L(this,"oldValue");this.value=n,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const n=ee(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return Nn(n)?n.obj[n.key]=this.value:on(n)?n.obj[n.key]=this.value:t=this.value,{doc:t,old:n.val}}toJson(t){const n={op:"replace",path:G(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 Sc extends Me{constructor(t,n){super(t);L(this,"from");this.from=n}op(){return"move"}code(){return 4}apply(t){const n=new Kr($(this.from),void 0).apply(t);return new _s(this.path,n.old).apply(n.doc)}toJson(t){return{op:"move",path:G(this.path),from:G(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 Cc extends Me{constructor(t,n){super(t);L(this,"from");this.from=n}op(){return"copy"}code(){return 3}apply(t){const{val:n}=ee(t,this.from);if(n===void 0)throw new Error("NOT_FOUND");return new _s(this.path,Qi(n)).apply(t)}toJson(t){return{op:"copy",path:G(this.path),from:G(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 Ce extends Me{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const Pn=(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(!Pn(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(!Pn(i[r],e[r]))return!1}return!0}return!1};class wc extends Ce{constructor(t,n,s){super(t);L(this,"value");L(this,"not");this.value=n,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:n}=ee(t,this.path);if(n===void 0)return!!this.not;const s=Pn(n,this.value);return this.not?!s:s}toJson(t){const n={op:"test",path:G(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 Ec extends Me{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=ee(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:G(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 Pc extends Me{constructor(t,n){super(t);L(this,"inc");this.inc=n}op(){return"inc"}code(){return 9}apply(t){const n=ee(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:G(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 Rc extends Me{constructor(t,n,s){super(t);L(this,"pos");L(this,"str");this.pos=n,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:n,key:s,obj:r}=ee(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 a=typeof n=="string"?n:"",o=Math.min(this.pos,a.length),c=a.slice(0,o),u=a.slice(o),d=c+this.str+u;return r?r[s]=d:t=d,{doc:t,old:n}}toJson(t){return{op:"str_ins",path:G(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 _c extends Me{constructor(t,n,s,r){super(t);L(this,"pos");L(this,"str");L(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}=ee(t,this.path);if(typeof n!="string")throw new Error("NOT_A_STRING");const a=n.length,o=Math.min(this.pos,n.length),c=Math.min(o,a),u=this.str!==void 0?this.str.length:this.len,d=Math.min(o+u,a),h=n.slice(0,c),f=n.substr(d),m=h+f;return r?r[s]=m:t=m,{doc:t,old:n}}toJson(t){return typeof this.str=="string"?{op:"str_del",path:G(this.path),pos:this.pos,str:this.str}:{op:"str_del",path:G(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:Ic}=Array,ss=i=>!!i&&typeof i=="object"&&typeof i.text=="string",rs=i=>!!i&&typeof i=="object"&&Ic(i.children),xc=(i,e)=>{const t=new RegExp(i,e?"i":void 0);return n=>t.test(n)};class Ac extends Me{constructor(t,n,s){super(t);L(this,"pos");L(this,"props");this.pos=n,this.props=s}op(){return"split"}code(){return 10}apply(t){const n=ee(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");const s=this.split(n.val);return Nn(n)?n.obj[n.key]=s:on(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),a=t.slice(n);return s?[{...s,text:r},{...s,text:a}]:[r,a]}else if(ss(t)){const{pos:n,props:s}=this,r=t.text.slice(0,n),a=t.text.slice(n);return[{...t,...s,text:r},{...t,...s,text:a}]}else if(rs(t)){const{pos:n,props:s}=this,r=t.children.slice(0,n),a=t.children.slice(n);return[{...t,...s,children:r},{...t,...s,children:a}]}else if(typeof t=="number"){const{pos:n}=this;return[n,t-n]}else return[t,t]}toJson(t){const n={op:"split",path:G(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 Oc extends Me{constructor(t,n,s){super(t);L(this,"pos");L(this,"props");this.pos=n,this.props=s}op(){return"merge"}code(){return 11}apply(t){const n=ee(t,this.path);if(!on(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],a=this.merge(s,r);return n.obj[n.key-1]=a,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:ss(t)&&ss(n)?{...t,...n,text:t.text+n.text}:rs(t)&&rs(n)?{...t,...n,children:[...t.children,...n.children]}:[t,n]}toJson(t){const n={op:"merge",path:G(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:Lc}=Array;class Nc extends Me{constructor(t,n,s){super(t);L(this,"props");L(this,"deleteNull");this.props=n,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const n=ee(t,this.path);return on(n)?n.val!==void 0&&(n.obj[n.key]=this.extend(n.val)):Nn(n)?n.obj[n.key]=this.extend(n.val):t=this.extend(t),{doc:t}}extend(t){if(Lc(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:G(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 Dc extends Ce{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=ee(e,this.path);return t!==void 0}toJson(e){return{op:"defined",path:G(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 Mc extends Ce{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=ee(e,this.path);return t===void 0}catch(t){if(t.message==="NOT_FOUND")return!0;throw t}}toJson(e){return{op:"undefined",path:G(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:Uc}=Array;class Fc extends Ce{constructor(t,n){super(t);L(this,"type");this.type=n}op(){return"test_type"}code(){return 39}test(t){const{val:n}=ee(t,this.path);return n===null?this.type.indexOf("null")>-1:Uc(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:G(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 Bc extends Ce{constructor(t,n,s,r){super(t);L(this,"pos");L(this,"str");L(this,"not");this.pos=n,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:n}=ee(t,this.path);if(typeof n!="string")return!1;const s=n.length,r=Math.min(this.pos,s),a=Math.min(this.pos+this.str.length,s),o=n.substring(r,a)===this.str;return this.not?!o:o}toJson(t){const n={op:"test_string",path:G(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 Jc extends Ce{constructor(t,n,s){super(t);L(this,"len");L(this,"not");this.len=n,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:n}=ee(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:G(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 jc extends Ce{constructor(t,n,s){super(t);L(this,"value");L(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:n}=ee(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:G(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 Vc extends Ce{constructor(t,n,s){super(t);L(this,"value");L(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:n}=ee(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:G(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 $c extends Ce{constructor(t,n,s){super(t);L(this,"value");L(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:n}=ee(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:G(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 qc extends Ce{constructor(t,n){super(t);L(this,"value");this.value=n}op(){return"in"}code(){return 33}test(t){const{val:n}=ee(t,this.path);for(const s of this.value)if(Pn(n,s))return!0;return!1}toJson(t){return{op:"in",path:G(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 Hc extends Ce{constructor(t,n){super(t);L(this,"value");this.value=n}op(){return"less"}code(){return 34}test(t){const{val:n}=ee(t,this.path);return typeof n!="number"?!1:n<this.value}toJson(t){return{op:"less",path:G(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 Wc extends Ce{constructor(t,n){super(t);L(this,"value");this.value=n}op(){return"more"}code(){return 36}test(t){const{val:n}=ee(t,this.path);return typeof n!="number"?!1:n>this.value}toJson(t){return{op:"more",path:G(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 Is extends Ce{constructor(t,n){super(t);L(this,"ops");this.ops=n}}class Gc extends Is{constructor(t,n){super(t,n);L(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:G(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 a=0;a<r;a++)this.ops[a].encode(t,this)}}class zc extends Is{constructor(t,n){super(t,n);L(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:G(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 Kc extends Is{constructor(t,n){super(t,n);L(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:G(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 Yc extends Ce{constructor(t,n,s,r){super(t);L(this,"value");L(this,"ignore_case");L(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}=ee(t,this.path);return typeof n!="string"?!1:this.matcher(n)}toJson(t){const n={op:"matches",path:G(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:Xc}=Array;class Qc extends Ce{constructor(t,n){super(t);L(this,"value");this.value=n}op(){return"type"}code(){return 42}test(t){const{val:n}=ee(t,this.path);return n===null?this.value==="null":Xc(n)?this.value==="array":typeof n===this.value||typeof n=="number"&&n===Math.round(n)&&this.value==="integer"}toJson(t){return{op:"type",path:G(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 Zc=(i,e)=>{switch(i.op){case"add":return new _s($(i.path),i.value);case"remove":return new Kr($(i.path),i.oldValue);case"replace":return new Tc($(i.path),i.value,i.oldValue);case"move":return new Sc($(i.path),$(i.from));case"copy":return new Cc($(i.path),$(i.from));case"flip":return new Ec($(i.path));case"inc":return new Pc($(i.path),i.inc);case"str_ins":return new Rc($(i.path),i.pos,i.str);case"str_del":return new _c($(i.path),i.pos,i.str,i.len);case"split":return new Ac($(i.path),i.pos,i.props||null);case"merge":return new Oc($(i.path),i.pos,i.props||null);case"extend":return new Nc($(i.path),i.props,!!i.deleteNull);default:return mn(i,e)}},mn=(i,e)=>{switch(i.op){case"test":return new wc($(i.path),i.value,!!i.not);case"defined":return new Dc($(i.path));case"undefined":return new Mc($(i.path));case"type":return new Qc($(i.path),i.value);case"test_type":return new Fc($(i.path),i.type);case"test_string":return new Bc($(i.path),i.pos,i.str,!!i.not);case"test_string_len":return new Jc($(i.path),i.len,!!i.not);case"contains":return new jc($(i.path),i.value,!!i.ignore_case);case"ends":return new Vc($(i.path),i.value,!!i.ignore_case);case"starts":return new $c($(i.path),i.value,!!i.ignore_case);case"matches":return new Yc($(i.path),i.value,!!i.ignore_case,e.createMatcher||xc);case"in":return new qc($(i.path),i.value);case"less":return new Hc($(i.path),i.value);case"more":return new Wc($(i.path),i.value);case"and":{const t=$(i.path);return new Gc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}case"or":{const t=$(i.path);return new zc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}case"not":{const t=$(i.path);return new Kc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function eu(i,e,t){t.mutate||(i=Qi(i));const n=[],s=e.length;for(let r=0;r<s;r++){const o=Zc(e[r],t).apply(i);i=o.doc,n.push(o)}return{doc:i,res:n}}var Vi=i=>typeof i=="function"?i:function(){return i},tu=typeof self<"u"?self:null,Fi=typeof window<"u"?window:null,$i=tu||Fi||$i,iu="2.0.0",Xe={connecting:0,open:1,closing:2,closed:3},nu=1e4,su=1e3,Ae={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},bt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},as={longpoll:"longpoll",websocket:"websocket"},ru={complete:4},un=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})}},Yr=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))}},au=class{constructor(i,e,t){this.state=Ae.closed,this.topic=i,this.params=Vi(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new un(this,bt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Yr(()=>{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 un(this,bt.leave,Vi({}),this.timeout).send(),this.state=Ae.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(bt.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(bt.close,i)}onError(i){return this.on(bt.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 un(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(bt.close,"leave")},t=new un(this,bt.leave,Vi({}),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(a=>a.event===i);for(let a=0;a<r.length;a++)r[a].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}},Rn=class{static request(i,e,t,n,s,r,a){if($i.XDomainRequest){let o=new $i.XDomainRequest;return this.xdomainRequest(o,i,e,n,s,r,a)}else{let o=new $i.XMLHttpRequest;return this.xhrRequest(o,i,e,t,n,s,r,a)}}static xdomainRequest(i,e,t,n,s,r,a){return i.timeout=s,i.open(e,t),i.onload=()=>{let o=this.parseJSON(i.responseText);a&&a(o)},r&&(i.ontimeout=r),i.onprogress=()=>{},i.send(n),i}static xhrRequest(i,e,t,n,s,r,a,o){return i.open(e,t,!0),i.timeout=r,i.setRequestHeader("Content-Type",n),i.onerror=()=>o&&o(null),i.onreadystatechange=()=>{if(i.readyState===ru.complete&&o){let c=this.parseJSON(i.responseText);o(c)}},a&&(i.ontimeout=a),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)}`}},$n=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=Xe.connecting,this.poll()}normalizeEndpoint(i){return i.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+as.websocket),"$1/"+as.longpoll)}endpointURL(){return Rn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(i,e,t){this.close(i,e,t),this.readyState=Xe.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Xe.open||this.readyState===Xe.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=Xe.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=Xe.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=Rn.request(i,this.endpointURL(),"application/json",e,this.timeout,r,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),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,a]=JSON.parse(i);return e({join_ref:t,ref:n,topic:s,event:r,payload:a})}},binaryEncode(i){let{join_ref:e,ref:t,event:n,topic:s,payload:r}=i,a=this.META_LENGTH+e.length+t.length+s.length+n.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),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 d=new Uint8Array(o.byteLength+r.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(r),o.byteLength),d.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),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=t.decode(i.slice(a,a+n));a=a+n;let c=t.decode(i.slice(a,a+s));a=a+s;let u=t.decode(i.slice(a,a+r));a=a+r;let d=i.slice(a,i.byteLength);return{join_ref:o,ref:null,topic:c,event:u,payload:d}},decodeReply(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(i.slice(o,o+n));o=o+n;let u=t.decode(i.slice(o,o+s));o=o+s;let d=t.decode(i.slice(o,o+r));o=o+r;let h=t.decode(i.slice(o,o+a));o=o+a;let f=i.slice(o,i.byteLength),m={status:h,response:f};return{join_ref:c,ref:u,topic:d,event:bt.reply,payload:m}},decodeBroadcast(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,a=t.decode(i.slice(r,r+n));r=r+n;let o=t.decode(i.slice(r,r+s));r=r+s;let c=i.slice(r,i.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},ou=class{constructor(i,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||nu,this.transport=e.transport||$i.WebSocket||$n,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!==$n?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;Fi&&Fi.addEventListener&&(Fi.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),t=this.connectClock)}),Fi.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=Vi(e.params||{}),this.endPoint=`${i}/${as.websocket}`,this.vsn=e.vsn||iu,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Yr(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return $n}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=Rn.appendParams(Rn.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=Vi(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(),su,"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===Xe.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(bt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Xe.connecting:return"connecting";case Xe.open:return"open";case Xe.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 au(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:a}=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 o=0;o<this.channels.length;o++){const c=this.channels[o];c.isMember(t,n,s,a)&&c.trigger(n,s,r,a)}for(let o=0;o<this.stateChangeCallbacks.message.length;o++){let[,c]=this.stateChangeCallbacks.message[o];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 cu{constructor(e){this.connected=!1,this.config=e,this.socket=new ou(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.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)}emitError(e,t){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:{kind:e,error:t}}))}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}=eu(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)}}Promise.resolve();var Ws=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};/*! *****************************************************************************
1
+ "use strict";var Fo=Object.defineProperty;var Bo=(i,e,t)=>e in i?Fo(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var x=(i,e,t)=>(Bo(i,typeof e!="symbol"?e+"":e,t),t);const $s=require("./constants-d9d958c9.cjs");function Gi(){}function qr(i){return i()}function qs(){return Object.create(null)}function tn(i){i.forEach(qr)}function Hr(i){return typeof i=="function"}function Jo(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}function jo(i){return Object.keys(i).length===0}function Ne(i,e){i.appendChild(e)}function Vo(i,e,t){const n=$o(i);if(!n.getElementById(e)){const s=Ye("style");s.id=e,s.textContent=t,qo(n,s)}}function $o(i){if(!i)return document;const e=i.getRootNode?i.getRootNode():i.ownerDocument;return e&&e.host?e:i.ownerDocument}function qo(i,e){return Ne(i.head||i,e),e.sheet}function Nn(i,e,t){i.insertBefore(e,t||null)}function nn(i){i.parentNode&&i.parentNode.removeChild(i)}function Ye(i){return document.createElement(i)}function Hs(i){return document.createElementNS("http://www.w3.org/2000/svg",i)}function Wr(i){return document.createTextNode(i)}function cn(){return Wr(" ")}function z(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function Ho(i){return Array.from(i.childNodes)}function Wo(i,e){e=""+e,i.data!==e&&(i.data=e)}function hi(i,e,t,n){t==null?i.style.removeProperty(e):i.style.setProperty(e,t,n?"important":"")}function Go(i){const e={};return i.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let zi;function Fi(i){zi=i}function Gr(){if(!zi)throw new Error("Function called outside component initialization");return zi}function zo(i){Gr().$$.on_mount.push(i)}function Ko(i){Gr().$$.on_destroy.push(i)}const mi=[],is=[];let yi=[];const Ws=[],Yo=Promise.resolve();let ns=!1;function Xo(){ns||(ns=!0,Yo.then(ii))}function ss(i){yi.push(i)}const $n=new Set;let fi=0;function ii(){if(fi!==0)return;const i=zi;do{try{for(;fi<mi.length;){const e=mi[fi];fi++,Fi(e),Qo(e.$$)}}catch(e){throw mi.length=0,fi=0,e}for(Fi(null),mi.length=0,fi=0;is.length;)is.pop()();for(let e=0;e<yi.length;e+=1){const t=yi[e];$n.has(t)||($n.add(t),t())}yi.length=0}while(mi.length);for(;Ws.length;)Ws.pop()();ns=!1,$n.clear(),Fi(i)}function Qo(i){if(i.fragment!==null){i.update(),tn(i.before_update);const e=i.dirty;i.dirty=[-1],i.fragment&&i.fragment.p(i.ctx,e),i.after_update.forEach(ss)}}function Zo(i){const e=[],t=[];yi.forEach(n=>i.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),yi=e}const ec=new Set;function zr(i,e){i&&i.i&&(ec.delete(i),i.i(e))}function Gs(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function tc(i,e){i.d(1),e.delete(i.key)}function ic(i,e,t,n,s,r,a,o,c,u,d,h){let f=i.length,p=r.length,b=f;const T={};for(;b--;)T[i[b].key]=b;const w=[],_=new Map,M=new Map,Q=[];for(b=p;b--;){const q=h(s,r,b),K=t(q);let A=a.get(K);A?n&&Q.push(()=>A.p(q,e)):(A=u(K,q),A.c()),_.set(K,w[b]=A),K in T&&M.set(K,Math.abs(b-T[K]))}const j=new Set,he=new Set;function ae(q){zr(q,1),q.m(o,d),a.set(q.key,q),d=q.first,p--}for(;f&&p;){const q=w[p-1],K=i[f-1],A=q.key,F=K.key;q===K?(d=q.first,f--,p--):_.has(F)?!a.has(A)||j.has(A)?ae(q):he.has(F)?f--:M.get(A)>M.get(F)?(he.add(A),ae(q)):(j.add(F),f--):(c(K,a),f--)}for(;f--;){const q=i[f];_.has(q.key)||c(q,a)}for(;p;)ae(w[p-1]);return tn(Q),w}function nc(i,e,t){const{fragment:n,after_update:s}=i.$$;n&&n.m(e,t),ss(()=>{const r=i.$$.on_mount.map(qr).filter(Hr);i.$$.on_destroy?i.$$.on_destroy.push(...r):tn(r),i.$$.on_mount=[]}),s.forEach(ss)}function sc(i,e){const t=i.$$;t.fragment!==null&&(Zo(t.after_update),tn(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function rc(i,e){i.$$.dirty[0]===-1&&(mi.push(i),Xo(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<<e%31}function ac(i,e,t,n,s,r,a=null,o=[-1]){const c=zi;Fi(i);const u=i.$$={fragment:null,ctx:[],props:r,update:Gi,not_equal:s,bound:qs(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:qs(),dirty:o,skip_bound:!1,root:e.target||c.$$.root};a&&a(u.root);let d=!1;if(u.ctx=t?t(i,e.props||{},(h,f,...p)=>{const b=p.length?p[0]:f;return u.ctx&&s(u.ctx[h],u.ctx[h]=b)&&(!u.skip_bound&&u.bound[h]&&u.bound[h](b),d&&rc(i,h)),f}):[],u.update(),d=!0,tn(u.before_update),u.fragment=n?n(u.ctx):!1,e.target){if(e.hydrate){const h=Ho(e.target);u.fragment&&u.fragment.l(h),h.forEach(nn)}else u.fragment&&u.fragment.c();e.intro&&zr(i.$$.fragment),nc(i,e.target,e.anchor),ii()}Fi(c)}let Kr;typeof HTMLElement=="function"&&(Kr=class extends HTMLElement{constructor(e,t,n){super();x(this,"$$ctor");x(this,"$$s");x(this,"$$c");x(this,"$$cn",!1);x(this,"$$d",{});x(this,"$$r",!1);x(this,"$$p_d",{});x(this,"$$l",{});x(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 a;return{c:function(){a=Ye("slot"),r!=="default"&&z(a,"name",r)},m:function(u,d){Nn(u,a,d)},d:function(u){u&&nn(a)}}}};if(await Promise.resolve(),!this.$$cn)return;const t={},n=Go(this);for(const r of this.$$s)r in n&&(t[r]=[e(r)]);for(const r of this.attributes){const a=this.$$g_p(r.name);a in this.$$d||(this.$$d[a]=pn(a,r.value,this.$$p_d,"toProp"))}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 a=pn(r,this.$$d[r],this.$$p_d,"toAttribute");a==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,a)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const a of this.$$l[r]){const o=this.$$c.$on(r,a);this.$$l_u.set(a,o)}this.$$l={}}}attributeChangedCallback(e,t,n){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=pn(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 pn(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 oc(i,e,t,n,s,r){let a=class extends Kr{constructor(){super(i,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(o=>(e[o].attribute||o).toLowerCase())}};return Object.keys(e).forEach(o=>{Object.defineProperty(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){var u;c=pn(o,c,e),this.$$d[o]=c,(u=this.$$c)==null||u.$set({[o]:c})}})}),n.forEach(o=>{Object.defineProperty(a.prototype,o,{get(){var c;return(c=this.$$c)==null?void 0:c[o]}})}),r&&(a=r(a)),i.element=a,a}class cc{constructor(){x(this,"$$");x(this,"$$set")}$destroy(){sc(this,1),this.$destroy=Gi}$on(e,t){if(!Hr(t))return Gi;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&&!jo(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const uc="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(uc);const{isArray:dc}=Array,lc=Object.keys,Ki=i=>{if(!i)return i;if(dc(i)){const e=[],t=i.length;for(let n=0;n<t;n++)e.push(Ki(i[n]));return e}else if(typeof i=="object"){const e=lc(i),t=e.length,n={};for(let s=0;s<t;s++){const r=e[s];n[r]=Ki(i[r])}return n}return i};class Ue{constructor(e){x(this,"path");x(this,"from");this.path=e}}const hc=/~1/g,fc=/~0/g,pc=/~/g,mc=/\//g;function gc(i){return i.indexOf("~")===-1?i:i.replace(hc,"/").replace(fc,"~")}function vc(i){return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(pc,"~0").replace(mc,"~1")}function yc(i){return i?i.slice(1).split("/").map(gc):[]}function G(i){return bc(i)?"":"/"+i.map(e=>vc(String(e))).join("/")}const $=i=>typeof i=="string"?yc(i):i,bc=i=>!i.length,kc=Object.prototype.hasOwnProperty;function Tc(i,e){return kc.call(i,e)}const{isArray:Yr}=Array,te=(i,e)=>{const t=e.length;if(!t)return{val:i};let n,s;for(let a=0;a<t;a++)if(n=i,s=e[a],Yr(n)){const o=n.length;if(s==="-")s=o;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=Tc(n,s)?n[s]:void 0;else throw new Error("NOT_FOUND");return{val:i,obj:n,key:s}},sn=i=>Yr(i.obj)&&typeof i.key=="number",xn=i=>typeof i.obj=="object"&&typeof i.key=="string";class Is extends Ue{constructor(t,n){super(t);x(this,"value");this.value=n}op(){return"add"}code(){return 0}apply(t){const{val:n,key:s,obj:r}=te(t,this.path),a=Ki(this.value);if(!r)t=a;else if(typeof s=="string")r[s]=a;else{const o=r.length;if(s<o)r.splice(s,0,a);else{if(s>o)throw new Error("INVALID_INDEX");r.push(a)}}return{doc:t,old:n}}toJson(t){return{op:"add",path:G(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 Xr extends Ue{constructor(t,n){super(t);x(this,"oldValue");this.oldValue=n}op(){return"remove"}code(){return 1}apply(t){const n=te(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return xn(n)?delete n.obj[n.key]:sn(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:G(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 Sc extends Ue{constructor(t,n,s){super(t);x(this,"value");x(this,"oldValue");this.value=n,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const n=te(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return xn(n)?n.obj[n.key]=this.value:sn(n)?n.obj[n.key]=this.value:t=this.value,{doc:t,old:n.val}}toJson(t){const n={op:"replace",path:G(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 Cc extends Ue{constructor(t,n){super(t);x(this,"from");this.from=n}op(){return"move"}code(){return 4}apply(t){const n=new Xr($(this.from),void 0).apply(t);return new Is(this.path,n.old).apply(n.doc)}toJson(t){return{op:"move",path:G(this.path),from:G(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 wc extends Ue{constructor(t,n){super(t);x(this,"from");this.from=n}op(){return"copy"}code(){return 3}apply(t){const{val:n}=te(t,this.from);if(n===void 0)throw new Error("NOT_FOUND");return new Is(this.path,Ki(n)).apply(t)}toJson(t){return{op:"copy",path:G(this.path),from:G(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 Ce extends Ue{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const Pn=(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(!Pn(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(!Pn(i[r],e[r]))return!1}return!0}return!1};class Ec extends Ce{constructor(t,n,s){super(t);x(this,"value");x(this,"not");this.value=n,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:n}=te(t,this.path);if(n===void 0)return!!this.not;const s=Pn(n,this.value);return this.not?!s:s}toJson(t){const n={op:"test",path:G(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 Pc extends Ue{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=te(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:G(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 Rc extends Ue{constructor(t,n){super(t);x(this,"inc");this.inc=n}op(){return"inc"}code(){return 9}apply(t){const n=te(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:G(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 _c extends Ue{constructor(t,n,s){super(t);x(this,"pos");x(this,"str");this.pos=n,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:n,key:s,obj:r}=te(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 a=typeof n=="string"?n:"",o=Math.min(this.pos,a.length),c=a.slice(0,o),u=a.slice(o),d=c+this.str+u;return r?r[s]=d:t=d,{doc:t,old:n}}toJson(t){return{op:"str_ins",path:G(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 Ic extends Ue{constructor(t,n,s,r){super(t);x(this,"pos");x(this,"str");x(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}=te(t,this.path);if(typeof n!="string")throw new Error("NOT_A_STRING");const a=n.length,o=Math.min(this.pos,n.length),c=Math.min(o,a),u=this.str!==void 0?this.str.length:this.len,d=Math.min(o+u,a),h=n.slice(0,c),f=n.substr(d),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:G(this.path),pos:this.pos,str:this.str}:{op:"str_del",path:G(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:Ac}=Array,rs=i=>!!i&&typeof i=="object"&&typeof i.text=="string",as=i=>!!i&&typeof i=="object"&&Ac(i.children),Oc=(i,e)=>{const t=new RegExp(i,e?"i":void 0);return n=>t.test(n)};class Lc extends Ue{constructor(t,n,s){super(t);x(this,"pos");x(this,"props");this.pos=n,this.props=s}op(){return"split"}code(){return 10}apply(t){const n=te(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");const s=this.split(n.val);return xn(n)?n.obj[n.key]=s:sn(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),a=t.slice(n);return s?[{...s,text:r},{...s,text:a}]:[r,a]}else if(rs(t)){const{pos:n,props:s}=this,r=t.text.slice(0,n),a=t.text.slice(n);return[{...t,...s,text:r},{...t,...s,text:a}]}else if(as(t)){const{pos:n,props:s}=this,r=t.children.slice(0,n),a=t.children.slice(n);return[{...t,...s,children:r},{...t,...s,children:a}]}else if(typeof t=="number"){const{pos:n}=this;return[n,t-n]}else return[t,t]}toJson(t){const n={op:"split",path:G(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 Nc extends Ue{constructor(t,n,s){super(t);x(this,"pos");x(this,"props");this.pos=n,this.props=s}op(){return"merge"}code(){return 11}apply(t){const n=te(t,this.path);if(!sn(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],a=this.merge(s,r);return n.obj[n.key-1]=a,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:rs(t)&&rs(n)?{...t,...n,text:t.text+n.text}:as(t)&&as(n)?{...t,...n,children:[...t.children,...n.children]}:[t,n]}toJson(t){const n={op:"merge",path:G(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:xc}=Array;class Dc extends Ue{constructor(t,n,s){super(t);x(this,"props");x(this,"deleteNull");this.props=n,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const n=te(t,this.path);return sn(n)?n.val!==void 0&&(n.obj[n.key]=this.extend(n.val)):xn(n)?n.obj[n.key]=this.extend(n.val):t=this.extend(t),{doc:t}}extend(t){if(xc(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:G(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 Mc extends Ce{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=te(e,this.path);return t!==void 0}toJson(e){return{op:"defined",path:G(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 Uc extends Ce{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=te(e,this.path);return t===void 0}catch(t){if(t.message==="NOT_FOUND")return!0;throw t}}toJson(e){return{op:"undefined",path:G(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:Fc}=Array;class Bc extends Ce{constructor(t,n){super(t);x(this,"type");this.type=n}op(){return"test_type"}code(){return 39}test(t){const{val:n}=te(t,this.path);return n===null?this.type.indexOf("null")>-1:Fc(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:G(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 Jc extends Ce{constructor(t,n,s,r){super(t);x(this,"pos");x(this,"str");x(this,"not");this.pos=n,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:n}=te(t,this.path);if(typeof n!="string")return!1;const s=n.length,r=Math.min(this.pos,s),a=Math.min(this.pos+this.str.length,s),o=n.substring(r,a)===this.str;return this.not?!o:o}toJson(t){const n={op:"test_string",path:G(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 jc extends Ce{constructor(t,n,s){super(t);x(this,"len");x(this,"not");this.len=n,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:n}=te(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:G(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 Vc extends Ce{constructor(t,n,s){super(t);x(this,"value");x(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:n}=te(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:G(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 $c extends Ce{constructor(t,n,s){super(t);x(this,"value");x(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:n}=te(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:G(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 qc extends Ce{constructor(t,n,s){super(t);x(this,"value");x(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:n}=te(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:G(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 Hc extends Ce{constructor(t,n){super(t);x(this,"value");this.value=n}op(){return"in"}code(){return 33}test(t){const{val:n}=te(t,this.path);for(const s of this.value)if(Pn(n,s))return!0;return!1}toJson(t){return{op:"in",path:G(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 Wc extends Ce{constructor(t,n){super(t);x(this,"value");this.value=n}op(){return"less"}code(){return 34}test(t){const{val:n}=te(t,this.path);return typeof n!="number"?!1:n<this.value}toJson(t){return{op:"less",path:G(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 Gc extends Ce{constructor(t,n){super(t);x(this,"value");this.value=n}op(){return"more"}code(){return 36}test(t){const{val:n}=te(t,this.path);return typeof n!="number"?!1:n>this.value}toJson(t){return{op:"more",path:G(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 As extends Ce{constructor(t,n){super(t);x(this,"ops");this.ops=n}}class zc extends As{constructor(t,n){super(t,n);x(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:G(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 a=0;a<r;a++)this.ops[a].encode(t,this)}}class Kc extends As{constructor(t,n){super(t,n);x(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:G(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 Yc extends As{constructor(t,n){super(t,n);x(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:G(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 Xc extends Ce{constructor(t,n,s,r){super(t);x(this,"value");x(this,"ignore_case");x(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}=te(t,this.path);return typeof n!="string"?!1:this.matcher(n)}toJson(t){const n={op:"matches",path:G(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:Qc}=Array;class Zc extends Ce{constructor(t,n){super(t);x(this,"value");this.value=n}op(){return"type"}code(){return 42}test(t){const{val:n}=te(t,this.path);return n===null?this.value==="null":Qc(n)?this.value==="array":typeof n===this.value||typeof n=="number"&&n===Math.round(n)&&this.value==="integer"}toJson(t){return{op:"type",path:G(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 eu=(i,e)=>{switch(i.op){case"add":return new Is($(i.path),i.value);case"remove":return new Xr($(i.path),i.oldValue);case"replace":return new Sc($(i.path),i.value,i.oldValue);case"move":return new Cc($(i.path),$(i.from));case"copy":return new wc($(i.path),$(i.from));case"flip":return new Pc($(i.path));case"inc":return new Rc($(i.path),i.inc);case"str_ins":return new _c($(i.path),i.pos,i.str);case"str_del":return new Ic($(i.path),i.pos,i.str,i.len);case"split":return new Lc($(i.path),i.pos,i.props||null);case"merge":return new Nc($(i.path),i.pos,i.props||null);case"extend":return new Dc($(i.path),i.props,!!i.deleteNull);default:return mn(i,e)}},mn=(i,e)=>{switch(i.op){case"test":return new Ec($(i.path),i.value,!!i.not);case"defined":return new Mc($(i.path));case"undefined":return new Uc($(i.path));case"type":return new Zc($(i.path),i.value);case"test_type":return new Bc($(i.path),i.type);case"test_string":return new Jc($(i.path),i.pos,i.str,!!i.not);case"test_string_len":return new jc($(i.path),i.len,!!i.not);case"contains":return new Vc($(i.path),i.value,!!i.ignore_case);case"ends":return new $c($(i.path),i.value,!!i.ignore_case);case"starts":return new qc($(i.path),i.value,!!i.ignore_case);case"matches":return new Xc($(i.path),i.value,!!i.ignore_case,e.createMatcher||Oc);case"in":return new Hc($(i.path),i.value);case"less":return new Wc($(i.path),i.value);case"more":return new Gc($(i.path),i.value);case"and":{const t=$(i.path);return new zc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}case"or":{const t=$(i.path);return new Kc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}case"not":{const t=$(i.path);return new Yc(t,i.apply.map(n=>mn({...n,path:[...t,...$(n.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function tu(i,e,t){t.mutate||(i=Ki(i));const n=[],s=e.length;for(let r=0;r<s;r++){const o=eu(e[r],t).apply(i);i=o.doc,n.push(o)}return{doc:i,res:n}}var Bi=i=>typeof i=="function"?i:function(){return i},iu=typeof self<"u"?self:null,Di=typeof window<"u"?window:null,Ji=iu||Di||Ji,nu="2.0.0",Xe={connecting:0,open:1,closing:2,closed:3},su=1e4,ru=1e3,Le={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},yt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},os={longpoll:"longpoll",websocket:"websocket"},au={complete:4},un=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})}},Qr=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))}},ou=class{constructor(i,e,t){this.state=Le.closed,this.topic=i,this.params=Bi(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new un(this,yt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Qr(()=>{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=Le.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=Le.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=Le.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=Le.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 un(this,yt.leave,Bi({}),this.timeout).send(),this.state=Le.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(yt.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(yt.close,i)}onError(i){return this.on(yt.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 un(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=Le.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(yt.close,"leave")},t=new un(this,yt.leave,Bi({}),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=Le.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(a=>a.event===i);for(let a=0;a<r.length;a++)r[a].callback(s,t,n||this.joinRef())}replyEventName(i){return`chan_reply_${i}`}isClosed(){return this.state===Le.closed}isErrored(){return this.state===Le.errored}isJoined(){return this.state===Le.joined}isJoining(){return this.state===Le.joining}isLeaving(){return this.state===Le.leaving}},Rn=class{static request(i,e,t,n,s,r,a){if(Ji.XDomainRequest){let o=new Ji.XDomainRequest;return this.xdomainRequest(o,i,e,n,s,r,a)}else{let o=new Ji.XMLHttpRequest;return this.xhrRequest(o,i,e,t,n,s,r,a)}}static xdomainRequest(i,e,t,n,s,r,a){return i.timeout=s,i.open(e,t),i.onload=()=>{let o=this.parseJSON(i.responseText);a&&a(o)},r&&(i.ontimeout=r),i.onprogress=()=>{},i.send(n),i}static xhrRequest(i,e,t,n,s,r,a,o){return i.open(e,t,!0),i.timeout=r,i.setRequestHeader("Content-Type",n),i.onerror=()=>o&&o(null),i.onreadystatechange=()=>{if(i.readyState===au.complete&&o){let c=this.parseJSON(i.responseText);o(c)}},a&&(i.ontimeout=a),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)}`}},qn=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=Xe.connecting,this.poll()}normalizeEndpoint(i){return i.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+os.websocket),"$1/"+os.longpoll)}endpointURL(){return Rn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(i,e,t){this.close(i,e,t),this.readyState=Xe.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Xe.open||this.readyState===Xe.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=Xe.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=Xe.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=Rn.request(i,this.endpointURL(),"application/json",e,this.timeout,r,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),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,a]=JSON.parse(i);return e({join_ref:t,ref:n,topic:s,event:r,payload:a})}},binaryEncode(i){let{join_ref:e,ref:t,event:n,topic:s,payload:r}=i,a=this.META_LENGTH+e.length+t.length+s.length+n.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),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 d=new Uint8Array(o.byteLength+r.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(r),o.byteLength),d.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),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=t.decode(i.slice(a,a+n));a=a+n;let c=t.decode(i.slice(a,a+s));a=a+s;let u=t.decode(i.slice(a,a+r));a=a+r;let d=i.slice(a,i.byteLength);return{join_ref:o,ref:null,topic:c,event:u,payload:d}},decodeReply(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(i.slice(o,o+n));o=o+n;let u=t.decode(i.slice(o,o+s));o=o+s;let d=t.decode(i.slice(o,o+r));o=o+r;let h=t.decode(i.slice(o,o+a));o=o+a;let f=i.slice(o,i.byteLength),p={status:h,response:f};return{join_ref:c,ref:u,topic:d,event:yt.reply,payload:p}},decodeBroadcast(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,a=t.decode(i.slice(r,r+n));r=r+n;let o=t.decode(i.slice(r,r+s));r=r+s;let c=i.slice(r,i.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},cu=class{constructor(i,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||su,this.transport=e.transport||Ji.WebSocket||qn,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!==qn?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;Di&&Di.addEventListener&&(Di.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),t=this.connectClock)}),Di.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=Bi(e.params||{}),this.endPoint=`${i}/${os.websocket}`,this.vsn=e.vsn||nu,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Qr(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return qn}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=Rn.appendParams(Rn.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=Bi(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(),ru,"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===Xe.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(yt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Xe.connecting:return"connecting";case Xe.open:return"open";case Xe.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 ou(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:a}=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 o=0;o<this.channels.length;o++){const c=this.channels[o];c.isMember(t,n,s,a)&&c.trigger(n,s,r,a)}for(let o=0;o<this.stateChangeCallbacks.message.length;o++){let[,c]=this.stateChangeCallbacks.message[o];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 uu{constructor(e){this.connected=!1,this.config=e,this.socket=new cu(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.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)}emitError(e,t){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:{kind:e,error:t}}))}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}=tu(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)}}Promise.resolve();var zs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};/*! *****************************************************************************
2
2
  Copyright (C) Microsoft. All rights reserved.
3
3
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4
4
  this file except in compliance with the License. You may obtain a copy of the
@@ -11,8 +11,8 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
11
11
 
12
12
  See the Apache Version 2.0 License for specific language governing permissions
13
13
  and limitations under the License.
14
- ***************************************************************************** */var Gs;(function(i){(function(e){var t=typeof Ws=="object"?Ws: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,a){return function(o,c){typeof r[o]!="function"&&Object.defineProperty(r,o,{configurable:!0,writable:!0,value:c}),a&&a(o,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",a=typeof Object.create=="function",o={__proto__:[]}instanceof Array,c=!a&&!o,u={create:a?function(){return jn(Object.create(null))}:o?function(){return jn({__proto__:null})}:function(){return jn({})},has:c?function(v,y){return t.call(v,y)}:function(v,y){return y in v},get:c?function(v,y){return t.call(v,y)?v[y]:void 0}:function(v,y){return v[y]}},d=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:No(),m=!h&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Do(),b=!h&&typeof WeakMap=="function"?WeakMap:Mo(),T=new b;function w(v,y,S,E){if(te(S)){if(!Fs(v))throw new TypeError;if(!Bs(y))throw new TypeError;return F(v,y)}else{if(!Fs(v))throw new TypeError;if(!re(y))throw new TypeError;if(!re(E)&&!te(E)&&!vt(E))throw new TypeError;return vt(E)&&(E=void 0),S=yt(S),le(v,y,S,E)}}e("decorate",w);function I(v,y){function S(E,N){if(!re(E))throw new TypeError;if(!te(N)&&!Io(N))throw new TypeError;fe(v,y,E,N)}return S}e("metadata",I);function D(v,y,S,E){if(!re(S))throw new TypeError;return te(E)||(E=yt(E)),fe(v,y,S,E)}e("defineMetadata",D);function Q(v,y,S){if(!re(y))throw new TypeError;return te(S)||(S=yt(S)),xi(v,y,S)}e("hasMetadata",Q);function j(v,y,S){if(!re(y))throw new TypeError;return te(S)||(S=yt(S)),Ai(v,y,S)}e("hasOwnMetadata",j);function ce(v,y,S){if(!re(y))throw new TypeError;return te(S)||(S=yt(S)),U(v,y,S)}e("getMetadata",ce);function ae(v,y,S){if(!re(y))throw new TypeError;return te(S)||(S=yt(S)),he(v,y,S)}e("getOwnMetadata",ae);function q(v,y){if(!re(v))throw new TypeError;return te(y)||(y=yt(y)),Ie(v,y)}e("getMetadataKeys",q);function K(v,y){if(!re(v))throw new TypeError;return te(y)||(y=yt(y)),xe(v,y)}e("getOwnMetadataKeys",K);function x(v,y,S){if(!re(y))throw new TypeError;te(S)||(S=yt(S));var E=Ue(y,S,!1);if(te(E)||!E.delete(v))return!1;if(E.size>0)return!0;var N=T.get(y);return N.delete(S),N.size>0||T.delete(y),!0}e("deleteMetadata",x);function F(v,y){for(var S=v.length-1;S>=0;--S){var E=v[S],N=E(y);if(!te(N)&&!vt(N)){if(!Bs(N))throw new TypeError;y=N}}return y}function le(v,y,S,E){for(var N=v.length-1;N>=0;--N){var ue=v[N],B=ue(y,S,E);if(!te(B)&&!vt(B)){if(!re(B))throw new TypeError;E=B}}return E}function Ue(v,y,S){var E=T.get(v);if(te(E)){if(!S)return;E=new f,T.set(v,E)}var N=E.get(y);if(te(N)){if(!S)return;N=new f,E.set(y,N)}return N}function xi(v,y,S){var E=Ai(v,y,S);if(E)return!0;var N=Jn(y);return vt(N)?!1:xi(v,N,S)}function Ai(v,y,S){var E=Ue(y,S,!1);return te(E)?!1:Ro(E.has(v))}function U(v,y,S){var E=Ai(v,y,S);if(E)return he(v,y,S);var N=Jn(y);if(!vt(N))return U(v,N,S)}function he(v,y,S){var E=Ue(y,S,!1);if(!te(E))return E.get(v)}function fe(v,y,S,E){var N=Ue(S,E,!0);N.set(v,y)}function Ie(v,y){var S=xe(v,y),E=Jn(v);if(E===null)return S;var N=Ie(E,y);if(N.length<=0)return S;if(S.length<=0)return N;for(var ue=new m,B=[],J=0,M=S;J<M.length;J++){var H=M[J],W=ue.has(H);W||(ue.add(H),B.push(H))}for(var zt=0,js=N;zt<js.length;zt++){var H=js[zt],W=ue.has(H);W||(ue.add(H),B.push(H))}return B}function xe(v,y){var S=[],E=Ue(v,y,!1);if(te(E))return S;for(var N=E.keys(),ue=xo(N),B=0;;){var J=Oo(ue);if(!J)return S.length=B,S;var M=Ao(J);try{S[B]=M}catch(H){try{Lo(ue)}finally{throw H}}B++}}function gt(v){if(v===null)return 1;switch(typeof v){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return v===null?1:6;default:return 6}}function te(v){return v===void 0}function vt(v){return v===null}function di(v){return typeof v=="symbol"}function re(v){return typeof v=="object"?v!==null:typeof v=="function"}function Eo(v,y){switch(gt(v)){case 0:return v;case 1:return v;case 2:return v;case 3:return v;case 4:return v;case 5:return v}var S=y===3?"string":y===5?"number":"default",E=Js(v,s);if(E!==void 0){var N=E.call(v,S);if(re(N))throw new TypeError;return N}return Po(v,S==="default"?"number":S)}function Po(v,y){if(y==="string"){var S=v.toString;if(li(S)){var E=S.call(v);if(!re(E))return E}var N=v.valueOf;if(li(N)){var E=N.call(v);if(!re(E))return E}}else{var N=v.valueOf;if(li(N)){var E=N.call(v);if(!re(E))return E}var ue=v.toString;if(li(ue)){var E=ue.call(v);if(!re(E))return E}}throw new TypeError}function Ro(v){return!!v}function _o(v){return""+v}function yt(v){var y=Eo(v,3);return di(y)?y:_o(y)}function Fs(v){return Array.isArray?Array.isArray(v):v instanceof Object?v instanceof Array:Object.prototype.toString.call(v)==="[object Array]"}function li(v){return typeof v=="function"}function Bs(v){return typeof v=="function"}function Io(v){switch(gt(v)){case 3:return!0;case 4:return!0;default:return!1}}function Js(v,y){var S=v[y];if(S!=null){if(!li(S))throw new TypeError;return S}}function xo(v){var y=Js(v,r);if(!li(y))throw new TypeError;var S=y.call(v);if(!re(S))throw new TypeError;return S}function Ao(v){return v.value}function Oo(v){var y=v.next();return y.done?!1:y}function Lo(v){var y=v.return;y&&y.call(v)}function Jn(v){var y=Object.getPrototypeOf(v);if(typeof v!="function"||v===d||y!==d)return y;var S=v.prototype,E=S&&Object.getPrototypeOf(S);if(E==null||E===Object.prototype)return y;var N=E.constructor;return typeof N!="function"||N===v?y:N}function No(){var v={},y=[],S=function(){function B(J,M,H){this._index=0,this._keys=J,this._values=M,this._selector=H}return B.prototype["@@iterator"]=function(){return this},B.prototype[r]=function(){return this},B.prototype.next=function(){var J=this._index;if(J>=0&&J<this._keys.length){var M=this._selector(this._keys[J],this._values[J]);return J+1>=this._keys.length?(this._index=-1,this._keys=y,this._values=y):this._index++,{value:M,done:!1}}return{value:void 0,done:!0}},B.prototype.throw=function(J){throw this._index>=0&&(this._index=-1,this._keys=y,this._values=y),J},B.prototype.return=function(J){return this._index>=0&&(this._index=-1,this._keys=y,this._values=y),{value:J,done:!0}},B}();return function(){function B(){this._keys=[],this._values=[],this._cacheKey=v,this._cacheIndex=-2}return Object.defineProperty(B.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),B.prototype.has=function(J){return this._find(J,!1)>=0},B.prototype.get=function(J){var M=this._find(J,!1);return M>=0?this._values[M]:void 0},B.prototype.set=function(J,M){var H=this._find(J,!0);return this._values[H]=M,this},B.prototype.delete=function(J){var M=this._find(J,!1);if(M>=0){for(var H=this._keys.length,W=M+1;W<H;W++)this._keys[W-1]=this._keys[W],this._values[W-1]=this._values[W];return this._keys.length--,this._values.length--,J===this._cacheKey&&(this._cacheKey=v,this._cacheIndex=-2),!0}return!1},B.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=v,this._cacheIndex=-2},B.prototype.keys=function(){return new S(this._keys,this._values,E)},B.prototype.values=function(){return new S(this._keys,this._values,N)},B.prototype.entries=function(){return new S(this._keys,this._values,ue)},B.prototype["@@iterator"]=function(){return this.entries()},B.prototype[r]=function(){return this.entries()},B.prototype._find=function(J,M){return this._cacheKey!==J&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=J)),this._cacheIndex<0&&M&&(this._cacheIndex=this._keys.length,this._keys.push(J),this._values.push(void 0)),this._cacheIndex},B}();function E(B,J){return B}function N(B,J){return J}function ue(B,J){return[B,J]}}function Do(){return function(){function v(){this._map=new f}return Object.defineProperty(v.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),v.prototype.has=function(y){return this._map.has(y)},v.prototype.add=function(y){return this._map.set(y,y),this},v.prototype.delete=function(y){return this._map.delete(y)},v.prototype.clear=function(){this._map.clear()},v.prototype.keys=function(){return this._map.keys()},v.prototype.values=function(){return this._map.values()},v.prototype.entries=function(){return this._map.entries()},v.prototype["@@iterator"]=function(){return this.keys()},v.prototype[r]=function(){return this.keys()},v}()}function Mo(){var v=16,y=u.create(),S=E();return function(){function M(){this._key=E()}return M.prototype.has=function(H){var W=N(H,!1);return W!==void 0?u.has(W,this._key):!1},M.prototype.get=function(H){var W=N(H,!1);return W!==void 0?u.get(W,this._key):void 0},M.prototype.set=function(H,W){var zt=N(H,!0);return zt[this._key]=W,this},M.prototype.delete=function(H){var W=N(H,!1);return W!==void 0?delete W[this._key]:!1},M.prototype.clear=function(){this._key=E()},M}();function E(){var M;do M="@@WeakMap@@"+J();while(u.has(y,M));return y[M]=!0,M}function N(M,H){if(!t.call(M,S)){if(!H)return;Object.defineProperty(M,S,{value:u.create()})}return M[S]}function ue(M,H){for(var W=0;W<H;++W)M[W]=Math.random()*255|0;return M}function B(M){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(M)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(M)):ue(new Uint8Array(M),M):ue(new Array(M),M)}function J(){var M=B(v);M[6]=M[6]&79|64,M[8]=M[8]&191|128;for(var H="",W=0;W<v;++W){var zt=M[W];(W===4||W===6||W===8)&&(H+="-"),zt<16&&(H+="0"),H+=zt.toString(16).toLowerCase()}return H}}function jn(v){return v.__=void 0,delete v.__,v}})})(Gs||(Gs={}));function uu(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 du=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Xr={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(du,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(T,w){var I=T[w];if(typeof I.bind=="function")return I.bind(T);try{return Function.prototype.bind.call(I,T)}catch{return function(){return Function.prototype.apply.apply(I,[T,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(T){return T==="debug"&&(T="log"),typeof console===t?!1:T==="trace"&&n?a:console[T]!==void 0?r(console,T):console.log!==void 0?r(console,"log"):e}function c(T,w){for(var I=0;I<s.length;I++){var D=s[I];this[D]=I<T?e:this.methodFactory(D,T,w)}this.log=this.debug}function u(T,w,I){return function(){typeof console!==t&&(c.call(this,w,I),this[T].apply(this,arguments))}}function d(T,w,I){return o(T)||u.apply(this,arguments)}function h(T,w,I){var D=this,Q;w=w??"WARN";var j="loglevel";typeof T=="string"?j+=":"+T:typeof T=="symbol"&&(j=void 0);function ce(x){var F=(s[x]||"silent").toUpperCase();if(!(typeof window===t||!j)){try{window.localStorage[j]=F;return}catch{}try{window.document.cookie=encodeURIComponent(j)+"="+F+";"}catch{}}}function ae(){var x;if(!(typeof window===t||!j)){try{x=window.localStorage[j]}catch{}if(typeof x===t)try{var F=window.document.cookie,le=F.indexOf(encodeURIComponent(j)+"=");le!==-1&&(x=/^([^;]+)/.exec(F.slice(le))[1])}catch{}return D.levels[x]===void 0&&(x=void 0),x}}function q(){if(!(typeof window===t||!j)){try{window.localStorage.removeItem(j);return}catch{}try{window.document.cookie=encodeURIComponent(j)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}D.name=T,D.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},D.methodFactory=I||d,D.getLevel=function(){return Q},D.setLevel=function(x,F){if(typeof x=="string"&&D.levels[x.toUpperCase()]!==void 0&&(x=D.levels[x.toUpperCase()]),typeof x=="number"&&x>=0&&x<=D.levels.SILENT){if(Q=x,F!==!1&&ce(x),c.call(D,x,T),typeof console===t&&x<D.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+x},D.setDefaultLevel=function(x){w=x,ae()||D.setLevel(x,!1)},D.resetLevel=function(){D.setLevel(w,!1),q()},D.enableAll=function(x){D.setLevel(D.levels.TRACE,x)},D.disableAll=function(x){D.setLevel(D.levels.SILENT,x)};var K=ae();K==null&&(K=w),D.setLevel(K,!1)}var f=new h,m={};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 I=m[w];return I||(I=m[w]=new h(w,f.getLevel(),f.methodFactory)),I};var b=typeof window!==t?window.log:void 0;return f.noConflict=function(){return typeof window!==t&&window.log===f&&(window.log=b),f},f.getLoggers=function(){return m},f.default=f,f})})(Xr);var Qr=Xr.exports,os;(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"})(os||(os={}));const p=Qr.getLogger("livekit");p.setDefaultLevel(os.info);Qr.getLogger("lk-e2ee");function Ee(i,e){if(!i)throw new Error(e)}const hu=34028234663852886e22,fu=-34028234663852886e22,pu=4294967295,mu=2147483647,gu=-2147483648;function gn(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>mu||i<gu)throw new Error("invalid int 32: "+i)}function cs(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>pu||i<0)throw new Error("invalid uint 32: "+i)}function Zr(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>hu||i<fu))throw new Error("invalid float 32: "+i)}const ea=Symbol("@bufbuild/protobuf/enum-type");function vu(i){const e=i[ea];return Ee(e,"missing enum type on enum object"),e}function ta(i,e,t,n){i[ea]=ia(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function ia(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=na(a);r.push(o),n[a.name]=o,s[a.no]=o}return{typeName:i,values:r,findName(a){return n[a]},findNumber(a){return s[a]}}}function yu(i,e,t){const n={};for(const s of e){const r=na(s);n[r.localName]=r.no,n[r.no]=r.localName}return ta(n,i,e),n}function na(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class _{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 bu(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),a={[r]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new _),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function ku(i,e,t,n){return{syntax:i,json:e,bin:t,util:n,makeMessageType(s,r,a){return bu(this,s,r,a)},makeEnum:yu,makeEnumType:ia,getEnumType:vu}}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={}));function Tu(){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 qn(i,e,t){for(let r=0;r<28;r=r+7){const a=i>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)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 a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const vn=4294967296;function zs(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(a,o){const c=Number(i.slice(a,o));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?ra(n,s):xs(n,s)}function Su(i,e){let t=xs(i,e);const n=t.hi&2147483648;n&&(t=ra(t.lo,t.hi));const s=sa(t.lo,t.hi);return n?"-"+s:s}function sa(i,e){if({lo:i,hi:e}=Cu(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,a=n+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Ks(a)+Ks(r)}function Cu(i,e){return{lo:i>>>0,hi:e>>>0}}function xs(i,e){return{lo:i|0,hi:e|0}}function ra(i,e){return e=~e,i?i=~i+1:e+=1,xs(i,e)}const Ks=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Ys(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 wu(){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 Eu(){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"),a=BigInt("0"),o=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>o||u<a)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=>Ee(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Ee(/^[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),zs(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),zs(s)},dec(s,r){return Su(s,r)},uDec(s,r){return sa(s,r)}}}const V=Eu();var ne;(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"})(ne||(ne={}));class Pu{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(cs(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return gn(e),Ys(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){Zr(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){cs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){gn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return gn(e),e=(e<<1^e>>31)>>>0,Ys(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=V.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=V.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return qn(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return qn(s,r,this.buf),this}uint64(e){let t=V.uEnc(e);return qn(t.lo,t.hi,this.buf),this}}class Ru{constructor(e,t){this.varint64=Tu,this.uint32=wu,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 ne.Varint:for(;this.buf[this.pos++]&128;);break;case ne.Bit64:this.pos+=4;case ne.Bit32:this.pos+=4;break;case ne.LengthDelimited:let n=this.uint32();this.pos+=n;break;case ne.StartGroup:let s;for(;(s=this.tag()[1])!==ne.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 V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,V.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 V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.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 us(i,e){return e instanceof _||!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 Kt(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 ds(i){switch(i){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return V.zero;case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function aa(i,e){const t=e===void 0;let n=ne.Varint,s=e===0;switch(i){case k.STRING:s=t||!e.length,n=ne.LengthDelimited;break;case k.BOOL:s=e===!1;break;case k.DOUBLE:n=ne.Bit64;break;case k.FLOAT:n=ne.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=ne.Bit64;break;case k.BYTES:s=t||!e.byteLength,n=ne.LengthDelimited;break;case k.FIXED32:n=ne.Bit32;break;case k.SFIXED32:n=ne.Bit32;break;case k.SFIXED64:s=t||e==0,n=ne.Bit64;break;case k.SINT64:s=t||e==0;break}const r=k[i].toLowerCase();return[n,r,t||s]}const pi=Symbol("@bufbuild/protobuf/unknown-fields"),Xs={readUnknownFields:!0,readerFactory:i=>new Ru(i)},Qs={writeUnknownFields:!0,writerFactory:()=>new Pu};function _u(i){return i?Object.assign(Object.assign({},Xs),i):Xs}function Iu(i){return i?Object.assign(Object.assign({},Qs),i):Qs}function xu(){return{makeReadOptions:_u,makeWriteOptions:Iu,listUnknownFields(i){var e;return(e=i[pi])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[pi]},writeUnknownFields(i,e){const n=i[pi];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[pi])||(s[pi]=[]),s[pi].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[a,o]=e.tag(),c=s.fields.find(a);if(!c){const f=e.skip(o);n.readUnknownFields&&this.onUnknownField(i,a,o,f);continue}let u=i,d=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;if(d){let w=u[h];if(o==ne.LengthDelimited&&f!=k.STRING&&f!=k.BYTES){let I=e.uint32()+e.pos;for(;e.pos<I;)w.push(qi(e,f))}else w.push(qi(e,f))}else u[h]=qi(e,f);break;case"message":const m=c.T;d?u[h].push(yn(e,new m,n)):u[h]instanceof _?yn(e,u[h],n):(u[h]=yn(e,new m,n),m.fieldWrapper&&!c.oneof&&!c.repeated&&(u[h]=m.fieldWrapper.unwrapField(u[h])));break;case"map":let[b,T]=Au(c,e,n);u[h][b]=T;break}}}}}function yn(i,e,t){return e.getType().runtime.bin.readMessage(e,i,i.uint32(),t),e}function Au(i,e,t){const n=e.uint32(),s=e.pos+n;let r,a;for(;e.pos<s;){let[o]=e.tag();switch(o){case 1:r=qi(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=qi(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=yn(e,new i.V.T,t);break}break}}if(r===void 0){let o=ds(i.K);r=i.K==k.BOOL?o.toString():o}if(typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=ds(i.V.T);break;case"enum":a=0;break;case"message":a=new i.V.T;break}return[r,a]}function qi(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 Ou(i,e,t,n,s){i.tag(t.no,ne.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:Ee(n=="true"||n=="false"),r=n=="true";break}switch(Hi(i,t.K,1,r,!0),t.V.kind){case"scalar":Hi(i,t.V.T,2,s,!0);break;case"enum":Hi(i,k.INT32,2,s,!0);break;case"message":ls(i,e,t.V.T,2,s);break}i.join()}function ls(i,e,t,n,s){if(s!==void 0){const r=us(t,s);i.tag(n,ne.LengthDelimited).bytes(r.toBinary(e))}}function Hi(i,e,t,n,s){let[r,a,o]=aa(e,n);(!o||s)&&i.tag(t,r)[a](n)}function Lu(i,e,t,n){if(!n.length)return;i.tag(t,ne.LengthDelimited).fork();let[,s]=aa(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Nu(){return Object.assign(Object.assign({},xu()),{writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){let r,a=s.repeated,o=s.localName;if(s.oneof){const c=i[s.oneof.localName];if(c.case!==o)continue;r=c.value}else r=i[o];switch(s.kind){case"scalar":case"enum":let c=s.kind=="enum"?k.INT32:s.T;if(a)if(s.packed)Lu(e,c,s.no,r);else for(const u of r)Hi(e,c,s.no,u,!0);else r!==void 0&&Hi(e,c,s.no,r,!!s.oneof||s.opt);break;case"message":if(a)for(const u of r)ls(e,t,s.T,s.no,u);else ls(e,t,s.T,s.no,r);break;case"map":for(const[u,d]of Object.entries(r))Ou(e,t,s,u,d);break}}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e}})}let Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Dn=[];for(let i=0;i<Tt.length;i++)Dn[Tt[i].charCodeAt(0)]=i;Dn["-".charCodeAt(0)]=Tt.indexOf("+");Dn["_".charCodeAt(0)]=Tt.indexOf("/");const oa={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,a=0;for(let o=0;o<i.length;o++){if(r=Dn[i.charCodeAt(o)],r===void 0)switch(i[o]){case"=":s=0;case`
15
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[n++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[n++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[n++]=(a&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+=Tt[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=Tt[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=Tt[s|n>>6],e+=Tt[n&63],t=0;break}return t&&(e+=Tt[s],e+="=",t==1&&(e+="=")),e}},Zs={ignoreUnknownFields:!1},er={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Du(i){return i?Object.assign(Object.assign({},Zs),i):Zs}function Mu(i){return i?Object.assign(Object.assign({},er),i):er}function Uu(i){const e=i(Fu,tr);return{makeReadOptions:Du,makeWriteOptions:Mu,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 a={};for(const[o,c]of Object.entries(n)){const u=t.fields.findJsonName(o);if(!u){if(!s.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'));continue}let d=u.localName,h=r;if(u.oneof){if(c===null&&u.kind=="scalar")continue;const f=a[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(o,'"'));a[u.oneof.localName]=o,h=h[u.oneof.localName]={case:d},d="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[d];for(const m of c){if(m===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(m)));let b;switch(u.kind){case"message":b=u.T.fromJson(m,s);break;case"enum":if(b=Hn(u.T,m,s.ignoreUnknownFields),b===void 0)continue;break;case"scalar":try{b=Oi(u.T,m)}catch(T){let w="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(m));throw T instanceof Error&&T.message.length>0&&(w+=": ".concat(T.message)),new Error(w)}break}f.push(b)}}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[d];for(const[m,b]of Object.entries(c)){if(b===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: map value null"));let T;switch(u.V.kind){case"message":T=u.V.T.fromJson(b,s);break;case"enum":if(T=Hn(u.V.T,b,s.ignoreUnknownFields),T===void 0)continue;break;case"scalar":try{T=Oi(u.V.T,b)}catch(w){let I="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&&(I+=": ".concat(w.message)),new Error(I)}break}try{f[Oi(u.K,u.K==k.BOOL?m=="true"?!0:m=="false"?!1:m:m).toString()]=T}catch(w){let I="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&&(I+=": ".concat(w.message)),new Error(I)}}}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(o,'"'));continue}h[d]instanceof _?h[d].fromJson(c,s):(h[d]=f.fromJson(c,s),f.fieldWrapper&&!u.oneof&&(h[d]=f.fieldWrapper.unwrapField(h[d])));break;case"enum":const m=Hn(u.T,c,s.ignoreUnknownFields);m!==void 0&&(h[d]=m);break;case"scalar":try{h[d]=Oi(u.T,c)}catch(b){let T="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw b instanceof Error&&b.message.length>0&&(T+=": ".concat(b.message)),new Error(T)}break}}return r},writeMessage(t,n){const s=t.getType(),r={};let a;try{for(const o of s.fields.byMember()){let c;if(o.kind=="oneof"){const u=t[o.localName];if(u.value===void 0)continue;if(a=o.findField(u.case),!a)throw"oneof case not found: "+u.case;c=e(a,u.value,n)}else a=o,c=e(a,t[a.localName],n);c!==void 0&&(r[n.useProtoFieldName?a.name:a.jsonName]=c)}}catch(o){const c=a?"cannot encode field ".concat(s.typeName,".").concat(a.name," to JSON"):"cannot encode message ".concat(s.typeName," to JSON"),u=o instanceof Error?o.message:String(o);throw new Error(c+(u.length>0?": ".concat(u):""))}return r},readScalar:Oi,writeScalar:tr,debug:ca}}function ca(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 Oi(i,e){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 t=Number(e);if(Number.isNaN(t)||!Number.isFinite(t))break;return i==k.FLOAT&&Zr(t),t;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(e===null)return 0;let n;if(typeof e=="number"?n=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(n=Number(e)),n===void 0)break;return i==k.UINT32?cs(n):gn(n),n;case k.INT64:case k.SFIXED64:case k.SINT64:if(e===null)return V.zero;if(typeof e!="number"&&typeof e!="string")break;return V.parse(e);case k.FIXED64:case k.UINT64:if(e===null)return V.zero;if(typeof e!="number"&&typeof e!="string")break;return V.uParse(e);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 oa.dec(e)}throw new Error}function Hn(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(ca(e)))}function Fu(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 tr(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 Ee(typeof e=="number"),e!=0||t?e:void 0;case k.FLOAT:case k.DOUBLE:return Ee(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 Ee(typeof e=="string"),e.length>0||t?e:void 0;case k.BOOL:return Ee(typeof e=="boolean"),e||t?e:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return Ee(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case k.BYTES:return Ee(e instanceof Uint8Array),t||e.byteLength>0?oa.enc(e):void 0}}function Bu(){return Uu((i,e)=>function(n,s,r){if(n.kind=="map"){const a={};switch(n.V.kind){case"scalar":for(const[c,u]of Object.entries(s)){const d=e(n.V.T,u,!0);Ee(d!==void 0),a[c.toString()]=d}break;case"message":for(const[c,u]of Object.entries(s))a[c.toString()]=u.toJson(r);break;case"enum":const o=n.V.T;for(const[c,u]of Object.entries(s)){Ee(u===void 0||typeof u=="number");const d=i(o,u,!0,r.enumAsInteger);Ee(d!==void 0),a[c.toString()]=d}break}return r.emitDefaultValues||Object.keys(a).length>0?a:void 0}else if(n.repeated){const a=[];switch(n.kind){case"scalar":for(let o=0;o<s.length;o++)a.push(e(n.T,s[o],!0));break;case"enum":for(let o=0;o<s.length;o++)a.push(i(n.T,s[o],!0,r.enumAsInteger));break;case"message":for(let o=0;o<s.length;o++)a.push(us(n.T,s[o]).toJson(r));break}return r.emitDefaultValues||a.length>0?a: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?us(n.T,s).toJson(r):void 0}})}function Ju(){return{setEnumType:ta,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,a=i;if(a[s]!==void 0)switch(n.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=n.findField(o);let u=a[s].value;c&&c.kind=="message"&&!(u instanceof c.T)?u=new c.T(u):c&&c.kind==="scalar"&&c.T===k.BYTES&&(u=Li(u)),r[s]={case:o,value:u};break;case"scalar":case"enum":let d=a[s];n.T===k.BYTES&&(d=n.repeated?d.map(Li):Li(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===k.BYTES)for(const[m,b]of Object.entries(a[s]))r[s][m]=Li(b);else Object.assign(r[s],a[s]);break;case"message":const f=n.V.T;for(const m of Object.keys(a[s])){let b=a[s][m];f.fieldWrapper||(b=new f(b)),r[s][m]=b}break}break;case"message":const h=n.T;if(n.repeated)r[s]=a[s].map(f=>f instanceof h?f:new h(f));else if(a[s]!==void 0){const f=a[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?r[s]=Li(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((a,o)=>n.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>Kt(n.T,a,r[o]));case"enum":return s.every((a,o)=>Kt(k.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(s,r);case"enum":return Kt(k.INT32,s,r);case"scalar":return Kt(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=n.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return Kt(k.INT32,s.value,r.value);case"scalar":return Kt(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const c=n.V.T;return o.every(d=>c.equals(s[d],r[d]));case"enum":return o.every(d=>Kt(k.INT32,s[d],r[d]));case"scalar":const u=n.V.T;return o.every(d=>Kt(u,s[d],r[d]))}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 a;if(s.repeated)a=r.map(ln);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=ln(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:ln(r.value)}:{case:void 0}:a=ln(r);n[s.localName]=a}return t}}}function ln(i){if(i===void 0)return i;if(i instanceof _)return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Li(i){return i instanceof Uint8Array?i:new Uint8Array(i)}class ju{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 ua(i,e){const t=da(i);return e?t:Gu(Wu(t))}function Vu(i){return ua(i,!1)}const $u=da;function da(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 qu=new Set(["constructor","toString","toJSON","valueOf"]),Hu=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),la=i=>"".concat(i,"$"),Wu=i=>Hu.has(i)?la(i):i,Gu=i=>qu.has(i)?la(i):i;class zu{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=Vu(e)}addField(e){Ee(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 l=ku("proto3",Bu(),Nu(),Object.assign(Object.assign({},Ju()),{newFieldList(i){return new ju(i,Ku)},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]=ds(e.T);break}}}}));function Ku(i){var e,t,n;const s=[];let r;for(const a of typeof i=="function"?i():i){const o=a;if(o.localName=ua(a.name,a.oneof!==void 0),o.jsonName=(e=a.jsonName)!==null&&e!==void 0?e:$u(a.name),o.repeated=(t=a.repeated)!==null&&t!==void 0?t:!1,o.packed=(n=a.packed)!==null&&n!==void 0?n:a.kind=="enum"||a.kind=="scalar"&&a.T!=k.BYTES&&a.T!=k.STRING,a.oneof!==void 0){const c=typeof a.oneof=="string"?a.oneof:a.oneof.name;(!r||r.name!=c)&&(r=new zu(c)),o.oneof=r,r.addField(o)}s.push(o)}return s}class me extends _{constructor(e){super(),this.seconds=V.zero,this.nanos=0,l.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(l.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=V.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 me.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new me({seconds:V.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new me().fromBinary(e,t)}static fromJson(e,t){return new me().fromJson(e,t)}static fromJsonString(e,t){return new me().fromJsonString(e,t)}static equals(e,t){return l.util.equals(me,e,t)}}me.runtime=l;me.typeName="google.protobuf.Timestamp";me.fields=l.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var hs;(function(i){i[i.DEFAULT_AC=0]="DEFAULT_AC",i[i.OPUS=1]="OPUS",i[i.AAC=2]="AAC"})(hs||(hs={}));l.util.setEnumType(hs,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]);var fs;(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"})(fs||(fs={}));l.util.setEnumType(fs,"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 ge;(function(i){i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.DATA=2]="DATA"})(ge||(ge={}));l.util.setEnumType(ge,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]);var se;(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"})(se||(se={}));l.util.setEnumType(se,"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 oe;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH",i[i.OFF=3]="OFF"})(oe||(oe={}));l.util.setEnumType(oe,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]);var ti;(function(i){i[i.POOR=0]="POOR",i[i.GOOD=1]="GOOD",i[i.EXCELLENT=2]="EXCELLENT"})(ti||(ti={}));l.util.setEnumType(ti,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"}]);var Ke;(function(i){i[i.UNSET=0]="UNSET",i[i.DISABLED=1]="DISABLED",i[i.ENABLED=2]="ENABLED"})(Ke||(Ke={}));l.util.setEnumType(Ke,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]);var Wt;(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"})(Wt||(Wt={}));l.util.setEnumType(Wt,"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"}]);var Fe;(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"})(Fe||(Fe={}));l.util.setEnumType(Fe,"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 Zi;(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"})(Zi||(Zi={}));l.util.setEnumType(Zi,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let Pi=class Bi extends _{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=V.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new Bi().fromBinary(e,t)}static fromJson(e,t){return new Bi().fromJson(e,t)}static fromJsonString(e,t){return new Bi().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Bi,e,t)}};Pi.runtime=l;Pi.typeName="livekit.Room";Pi.fields=l.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:$e,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:12,name:"playout_delay",kind:"message",T:St}]);class $e extends _{constructor(e){super(),this.mime="",this.fmtpLine="",l.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 l.util.equals($e,e,t)}}$e.runtime=l;$e.typeName="livekit.Codec";$e.fields=l.util.newFieldList(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);class St extends _{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,l.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 l.util.equals(St,e,t)}}St.runtime=l;St.typeName="livekit.PlayoutDelay";St.fields=l.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 Ct extends _{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,l.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 l.util.equals(Ct,e,t)}}Ct.runtime=l;Ct.typeName="livekit.ParticipantPermission";Ct.fields=l.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:l.getEnumType(se),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8}]);class De extends _{constructor(e){super(),this.sid="",this.identity="",this.state=ai.JOINING,this.tracks=[],this.metadata="",this.joinedAt=V.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,l.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 l.util.equals(De,e,t)}}De.runtime=l;De.typeName="livekit.ParticipantInfo";De.fields=l.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:l.getEnumType(ai)},{no:4,name:"tracks",kind:"message",T:Pe,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:Ct},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8}]);var ai;(function(i){i[i.JOINING=0]="JOINING",i[i.JOINED=1]="JOINED",i[i.ACTIVE=2]="ACTIVE",i[i.DISCONNECTED=3]="DISCONNECTED"})(ai||(ai={}));l.util.setEnumType(ai,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);class Yt extends _{constructor(e){super(),l.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 l.util.equals(Yt,e,t)}}Yt.runtime=l;Yt.typeName="livekit.Encryption";Yt.fields=l.util.newFieldList(()=>[]);var ke;(function(i){i[i.NONE=0]="NONE",i[i.GCM=1]="GCM",i[i.CUSTOM=2]="CUSTOM"})(ke||(ke={}));l.util.setEnumType(ke,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class wt extends _{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],l.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 l.util.equals(wt,e,t)}}wt.runtime=l;wt.typeName="livekit.SimulcastCodecInfo";wt.fields=l.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:Te,repeated:!0}]);class Pe extends _{constructor(e){super(),this.sid="",this.type=ge.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=se.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=ke.NONE,this.stream="",l.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 l.util.equals(Pe,e,t)}}Pe.runtime=l;Pe.typeName="livekit.TrackInfo";Pe.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:l.getEnumType(ge)},{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:l.getEnumType(se)},{no:10,name:"layers",kind:"message",T:Te,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:wt,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:l.getEnumType(ke)},{no:17,name:"stream",kind:"scalar",T:9}]);class Te extends _{constructor(e){super(),this.quality=oe.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new Te().fromBinary(e,t)}static fromJson(e,t){return new Te().fromJson(e,t)}static fromJsonString(e,t){return new Te().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Te,e,t)}}Te.runtime=l;Te.typeName="livekit.VideoLayer";Te.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(oe)},{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 Ze extends _{constructor(e){super(),this.kind=de.RELIABLE,this.value={case:void 0},l.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 l.util.equals(Ze,e,t)}}Ze.runtime=l;Ze.typeName="livekit.DataPacket";Ze.fields=l.util.newFieldList(()=>[{no:1,name:"kind",kind:"enum",T:l.getEnumType(de)},{no:2,name:"user",kind:"message",T:tt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Et,oneof:"value"}]);var de;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY"})(de||(de={}));l.util.setEnumType(de,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class Et extends _{constructor(e){super(),this.speakers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Et().fromBinary(e,t)}static fromJson(e,t){return new Et().fromJson(e,t)}static fromJsonString(e,t){return new Et().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Et,e,t)}}Et.runtime=l;Et.typeName="livekit.ActiveSpeakerUpdate";Et.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:et,repeated:!0}]);class et extends _{constructor(e){super(),this.sid="",this.level=0,this.active=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new et().fromBinary(e,t)}static fromJson(e,t){return new et().fromJson(e,t)}static fromJsonString(e,t){return new et().fromJsonString(e,t)}static equals(e,t){return l.util.equals(et,e,t)}}et.runtime=l;et.typeName="livekit.SpeakerInfo";et.fields=l.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 tt extends _{constructor(e){super(),this.participantSid="",this.payload=new Uint8Array(0),this.destinationSids=[],l.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 l.util.equals(tt,e,t)}}tt.runtime=l;tt.typeName="livekit.UserPacket";tt.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0}]);class it extends _{constructor(e){super(),this.participantSid="",this.trackSids=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new it().fromBinary(e,t)}static fromJson(e,t){return new it().fromJson(e,t)}static fromJsonString(e,t){return new it().fromJsonString(e,t)}static equals(e,t){return l.util.equals(it,e,t)}}it.runtime=l;it.typeName="livekit.ParticipantTracks";it.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]);class Pt extends _{constructor(e){super(),this.edition=wi.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",l.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 l.util.equals(Pt,e,t)}}Pt.runtime=l;Pt.typeName="livekit.ServerInfo";Pt.fields=l.util.newFieldList(()=>[{no:1,name:"edition",kind:"enum",T:l.getEnumType(wi)},{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 wi;(function(i){i[i.Standard=0]="Standard",i[i.Cloud=1]="Cloud"})(wi||(wi={}));l.util.setEnumType(wi,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class Rt extends _{constructor(e){super(),this.sdk=Ei.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",l.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 l.util.equals(Rt,e,t)}}Rt.runtime=l;Rt.typeName="livekit.ClientInfo";Rt.fields=l.util.newFieldList(()=>[{no:1,name:"sdk",kind:"enum",T:l.getEnumType(Ei)},{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 Ei;(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"})(Ei||(Ei={}));l.util.setEnumType(Ei,"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"}]);class nt extends _{constructor(e){super(),this.resumeConnection=Ke.UNSET,this.forceRelay=Ke.UNSET,l.util.initPartial(e,this)}static fromBinary(e,t){return new nt().fromBinary(e,t)}static fromJson(e,t){return new nt().fromJson(e,t)}static fromJsonString(e,t){return new nt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(nt,e,t)}}nt.runtime=l;nt.typeName="livekit.ClientConfiguration";nt.fields=l.util.newFieldList(()=>[{no:1,name:"video",kind:"message",T:st},{no:2,name:"screen",kind:"message",T:st},{no:3,name:"resume_connection",kind:"enum",T:l.getEnumType(Ke)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:l.getEnumType(Ke)}]);class st extends _{constructor(e){super(),this.hardwareEncoder=Ke.UNSET,l.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 l.util.equals(st,e,t)}}st.runtime=l;st.typeName="livekit.VideoConfiguration";st.fields=l.util.newFieldList(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:l.getEnumType(Ke)}]);class _t extends _{constructor(e){super(),this.codecs=[],this.publish=[],l.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 l.util.equals(_t,e,t)}}_t.runtime=l;_t.typeName="livekit.DisabledCodecs";_t.fields=l.util.newFieldList(()=>[{no:1,name:"codecs",kind:"message",T:$e,repeated:!0},{no:2,name:"publish",kind:"message",T:$e,repeated:!0}]);class Xt extends _{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=V.zero,this.headerBytes=V.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=V.zero,this.headerBytesDuplicate=V.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=V.zero,this.headerBytesPadding=V.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,this.sampleRate=0,this.driftMs=0,l.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 l.util.equals(Xt,e,t)}}Xt.runtime=l;Xt.typeName="livekit.RTPStats";Xt.fields=l.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:me},{no:2,name:"end_time",kind:"message",T:me},{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:me},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:me},{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:me},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:me},{no:42,name:"sample_rate",kind:"scalar",T:1},{no:43,name:"drift_ms",kind:"scalar",T:1}]);class Qt extends _{constructor(e){super(),this.unixMicro=V.zero,this.ticks=0,l.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 l.util.equals(Qt,e,t)}}Qt.runtime=l;Qt.typeName="livekit.TimedVersion";Qt.fields=l.util.newFieldList(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]);const Ni=7e3,Yu=[0,300,2*2*300,3*3*300,4*4*300,Ni,Ni,Ni,Ni,Ni];class Xu{constructor(e){this._retryDelays=e!==void 0?[...e]:Yu}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 g(i,e,t,n){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(d){try{u(n.next(d))}catch(h){a(h)}}function c(d){try{u(n.throw(d))}catch(h){a(h)}}function u(d){d.done?r(d.value):s(d.value).then(o,c)}u((n=n.apply(i,e||[])).next())})}function ir(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 gi(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 ir=="function"?ir(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(a){return new Promise(function(o,c){a=i[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(u){r({value:u,done:o})},a)}}var As={exports:{}},ki=typeof Reflect=="object"?Reflect:null,nr=ki&&typeof ki.apply=="function"?ki.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},bn;ki&&typeof ki.ownKeys=="function"?bn=ki.ownKeys:Object.getOwnPropertySymbols?bn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:bn=function(e){return Object.getOwnPropertyNames(e)};function Qu(i){console&&console.warn&&console.warn(i)}var ha=Number.isNaN||function(e){return e!==e};function X(){X.init.call(this)}As.exports=X;As.exports.once=id;X.EventEmitter=X;X.prototype._events=void 0;X.prototype._eventsCount=0;X.prototype._maxListeners=void 0;var sr=10;function Mn(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(X,"defaultMaxListeners",{enumerable:!0,get:function(){return sr},set:function(i){if(typeof i!="number"||i<0||ha(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");sr=i}});X.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};X.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ha(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 fa(i){return i._maxListeners===void 0?X.defaultMaxListeners:i._maxListeners}X.prototype.getMaxListeners=function(){return fa(this)};X.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 a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=r[e];if(c===void 0)return!1;if(typeof c=="function")nr(c,this,t);else for(var u=c.length,d=ya(c,u),n=0;n<u;++n)nr(d[n],this,t);return!0};function pa(i,e,t,n){var s,r,a;if(Mn(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),a=r[e]),a===void 0)a=r[e]=t,++i._eventsCount;else if(typeof a=="function"?a=r[e]=n?[t,a]:[a,t]:n?a.unshift(t):a.push(t),s=fa(i),s>0&&a.length>s&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=i,o.type=e,o.count=a.length,Qu(o)}return i}X.prototype.addListener=function(e,t){return pa(this,e,t,!1)};X.prototype.on=X.prototype.addListener;X.prototype.prependListener=function(e,t){return pa(this,e,t,!0)};function Zu(){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 ma(i,e,t){var n={fired:!1,wrapFn:void 0,target:i,type:e,listener:t},s=Zu.bind(n);return s.listener=t,n.wrapFn=s,s}X.prototype.once=function(e,t){return Mn(t),this.on(e,ma(this,e,t)),this};X.prototype.prependOnceListener=function(e,t){return Mn(t),this.prependListener(e,ma(this,e,t)),this};X.prototype.removeListener=function(e,t){var n,s,r,a,o;if(Mn(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,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,r=a;break}if(r<0)return this;r===0?n.shift():ed(n,r),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,o||t)}return this};X.prototype.off=X.prototype.removeListener;X.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),a;for(s=0;s<r.length;++s)a=r[s],a!=="removeListener"&&this.removeAllListeners(a);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 ga(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?td(s):ya(s,s.length)}X.prototype.listeners=function(e){return ga(this,e,!0)};X.prototype.rawListeners=function(e){return ga(this,e,!1)};X.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):va.call(i,e)};X.prototype.listenerCount=va;function va(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}X.prototype.eventNames=function(){return this._eventsCount>0?bn(this._events):[]};function ya(i,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=i[n];return t}function ed(i,e){for(;e+1<i.length;e++)i[e]=i[e+1];i.pop()}function td(i){for(var e=new Array(i.length),t=0;t<e.length;++t)e[t]=i[t].listener||i[t];return e}function id(i,e){return new Promise(function(t,n){function s(a){i.removeListener(e,r),n(a)}function r(){typeof i.removeListener=="function"&&i.removeListener("error",s),t([].slice.call(arguments))}ba(i,e,r,{once:!0}),e!=="error"&&nd(i,s,{once:!0})})}function nd(i,e,t){typeof i.on=="function"&&ba(i,"error",e,t)}function ba(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 mt=As.exports;let ka=!0,Ta=!0;function kn(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function ui(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=u=>{const d=t(u);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function sd(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(ka=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function rd(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ta=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Sa(){if(typeof window=="object"){if(ka)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Os(i,e){Ta&&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=kn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=kn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=kn(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 rr(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ca(i){return rr(i)?Object.keys(i).reduce(function(e,t){const n=rr(i[t]),s=n?Ca(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function ps(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?ps(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{ps(i,i.get(s),t)})}))}function ar(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&ps(i,o,s)})}),s}const or=Sa;function wa(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(u=>{if(u==="require"||u==="advanced"||u==="mediaSource")return;const d=typeof o[u]=="object"?o[u]:{ideal:o[u]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const h=function(f,m){return f?f+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(d.ideal!==void 0){c.optional=c.optional||[];let f={};typeof d.ideal=="number"?(f[h("min",u)]=d.ideal,c.optional.push(f),f={},f[h("max",u)]=d.ideal,c.optional.push(f)):(f[h("",u)]=d.ideal,c.optional.push(f))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",u)]=d.exact):["min","max"].forEach(f=>{d[f]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(f,u)]=d[f])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const u=function(d,h,f){h in d&&!(f in d)&&(d[f]=d[h],delete d[h])};o=JSON.parse(JSON.stringify(o)),u(o.audio,"autoGainControl","googAutoGainControl"),u(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let u=o.video.facingMode;u=u&&(typeof u=="object"?u:{ideal:u});const d=e.version<66;if(u&&(u.exact==="user"||u.exact==="environment"||u.ideal==="user"||u.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete o.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(b=>b.kind==="videoinput");let m=f.find(b=>h.some(T=>b.label.toLowerCase().includes(T)));return!m&&f.length&&h.includes("back")&&(m=f[f.length-1]),m&&(o.video.deviceId=u.exact?{exact:m.deviceId}:{ideal:m.deviceId}),o.video=n(o.video),or("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return or("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,u){s(o,d=>{t.webkitGetUserMedia(d,c,h=>{u&&u(r(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,u=>o(u).then(d=>{if(u.audio&&!d.getAudioTracks().length||u.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function od(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,a=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:o||3}},r&&(n.video.mandatory.maxWidth=r),a&&(n.video.mandatory.maxHeight=a),i.navigator.mediaDevices.getUserMedia(n)})}}}function Ea(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Pa(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(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else ui(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ra(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(o,c){let u=s.apply(this,arguments);return u||(u=e(this,o),this._senders.push(u)),u};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);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(a=>{this._senders.push(e(this,a))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 _a(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 a=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(m=>{f[m]=h.stat(m)}),u[f.id]=f}),u},o=function(c){return new Map(Object.keys(c).map(u=>[u,c[u]]))};if(arguments.length>=2){const c=function(u){s(o(a(u)))};return e.apply(this,[c,n])}return new Promise((c,u)=>{e.apply(this,[function(d){c(o(a(d)))},u])}).then(s,r)}}function Ia(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(a=>a._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(a=>ar(a,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}),ui(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>ar(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,a;return this.getSenders().forEach(o=>{o.track===n&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===n&&(r?a=!0:r=o),o.track===n)),a||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 xa(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(u=>o.indexOf(u)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Aa(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return xa(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(m=>m.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const h=new i.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,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(T=>T===d))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(T=>T.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const b=this._streams[h.id];if(b)b.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const T=new i.MediaStream([d]);this._streams[h.id]=T,this._reverseStreams[T.id]=h,this.addStream(T)}return this.getSenders().find(T=>T.track===d)};function r(u,d){let h=d.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const m=u._reverseStreams[f],b=u._streams[m.id];h=h.replace(new RegExp(b.id,"g"),m.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function a(u,d){let h=d.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const m=u._reverseStreams[f],b=u._streams[m.id];h=h.replace(new RegExp(m.id,"g"),b.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(u){const d=i.RTCPeerConnection.prototype[u],h={[u](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[b=>{const T=r(this,b);f[0].apply(null,[T])},b=>{f[1]&&f[1].apply(null,b)},arguments[2]]):d.apply(this,arguments).then(b=>r(this,b))}};i.RTCPeerConnection.prototype[u]=h[u]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const 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(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let f;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(T=>d.track===T)&&(f=this._streams[m])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ms(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 Oa(i,e){ui(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var cr=Object.freeze({__proto__:null,fixNegotiationNeeded:Oa,shimAddTrackRemoveTrack:Aa,shimAddTrackRemoveTrackWithNative:xa,shimGetDisplayMedia:od,shimGetSendersWithDtmf:Ra,shimGetStats:_a,shimGetUserMedia:wa,shimMediaStream:Ea,shimOnTrack:Pa,shimPeerConnection:ms,shimSenderReceiverGetStats:Ia});function La(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){Os("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function cd(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 Na(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 gs(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],a={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=a[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,a,o]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(u=>{u.type=t[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;c.forEach((d,h)=>{c.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(a,o)}}function Da(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 Ma(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}),ui(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ua(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Os("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Fa(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Ba(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(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Ja(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 ja(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 Va(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 ur=Object.freeze({__proto__:null,shimAddTransceiver:Ba,shimCreateAnswer:Va,shimCreateOffer:ja,shimGetDisplayMedia:cd,shimGetParameters:Ja,shimGetUserMedia:La,shimOnTrack:Na,shimPeerConnection:gs,shimRTCDataChannel:Fa,shimReceiverGetStats:Ma,shimRemoveStream:Ua,shimSenderGetStats:Da});function $a(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),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),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 qa(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 a=new Event("addstream");a.stream=r,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Ha(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,a=e.addIceCandidate;e.createOffer=function(u,d){const h=arguments.length>=2?arguments[2]:arguments[0],f=t.apply(this,[h]);return d?(f.then(u,d),Promise.resolve()):f},e.createAnswer=function(u,d){const h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return d?(f.then(u,d),Promise.resolve()):f};let o=function(c,u,d){const h=s.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h};e.setLocalDescription=o,o=function(c,u,d){const h=r.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h},e.setRemoteDescription=o,o=function(c,u,d){const h=a.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h},e.addIceCandidate=o}function Wa(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(Ga(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Ga(i){return i&&i.video!==void 0?Object.assign({},i,{video:Ca(i.video)}):i}function za(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Os("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(n.iceServers[a])}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 Ka(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 Ya(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(a=>a.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(a=>a.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 Xa(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var dr=Object.freeze({__proto__:null,shimAudioContext:Xa,shimCallbacksAPI:Ha,shimConstraints:Ga,shimCreateOfferLegacy:Ya,shimGetUserMedia:Wa,shimLocalStreamsAPI:$a,shimRTCIceServerUrls:za,shimRemoteStreamsAPI:qa,shimTrackEventTransceiver:Ka}),Qa={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(`
14
+ ***************************************************************************** */var Ks;(function(i){(function(e){var t=typeof zs=="object"?zs: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,a){return function(o,c){typeof r[o]!="function"&&Object.defineProperty(r,o,{configurable:!0,writable:!0,value:c}),a&&a(o,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",a=typeof Object.create=="function",o={__proto__:[]}instanceof Array,c=!a&&!o,u={create:a?function(){return Vn(Object.create(null))}:o?function(){return Vn({__proto__:null})}:function(){return Vn({})},has:c?function(v,y){return t.call(v,y)}:function(v,y){return y in v},get:c?function(v,y){return t.call(v,y)?v[y]:void 0}:function(v,y){return v[y]}},d=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:Do(),p=!h&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Mo(),b=!h&&typeof WeakMap=="function"?WeakMap:Uo(),T=new b;function w(v,y,S,E){if(Z(S)){if(!Bs(v))throw new TypeError;if(!Js(y))throw new TypeError;return F(v,y)}else{if(!Bs(v))throw new TypeError;if(!ie(y))throw new TypeError;if(!ie(E)&&!Z(E)&&!gt(E))throw new TypeError;return gt(E)&&(E=void 0),S=vt(S),fe(v,y,S,E)}}e("decorate",w);function _(v,y){function S(E,D){if(!ie(E))throw new TypeError;if(!Z(D)&&!Ao(D))throw new TypeError;oe(v,y,E,D)}return S}e("metadata",_);function M(v,y,S,E){if(!ie(S))throw new TypeError;return Z(E)||(E=vt(E)),oe(v,y,S,E)}e("defineMetadata",M);function Q(v,y,S){if(!ie(y))throw new TypeError;return Z(S)||(S=vt(S)),rn(v,y,S)}e("hasMetadata",Q);function j(v,y,S){if(!ie(y))throw new TypeError;return Z(S)||(S=vt(S)),di(v,y,S)}e("hasOwnMetadata",j);function he(v,y,S){if(!ie(y))throw new TypeError;return Z(S)||(S=vt(S)),an(v,y,S)}e("getMetadata",he);function ae(v,y,S){if(!ie(y))throw new TypeError;return Z(S)||(S=vt(S)),O(v,y,S)}e("getOwnMetadata",ae);function q(v,y){if(!ie(v))throw new TypeError;return Z(y)||(y=vt(y)),ce(v,y)}e("getMetadataKeys",q);function K(v,y){if(!ie(v))throw new TypeError;return Z(y)||(y=vt(y)),Ae(v,y)}e("getOwnMetadataKeys",K);function A(v,y,S){if(!ie(y))throw new TypeError;Z(S)||(S=vt(S));var E=Ie(y,S,!1);if(Z(E)||!E.delete(v))return!1;if(E.size>0)return!0;var D=T.get(y);return D.delete(S),D.size>0||T.delete(y),!0}e("deleteMetadata",A);function F(v,y){for(var S=v.length-1;S>=0;--S){var E=v[S],D=E(y);if(!Z(D)&&!gt(D)){if(!Js(D))throw new TypeError;y=D}}return y}function fe(v,y,S,E){for(var D=v.length-1;D>=0;--D){var de=v[D],B=de(y,S,E);if(!Z(B)&&!gt(B)){if(!ie(B))throw new TypeError;E=B}}return E}function Ie(v,y,S){var E=T.get(v);if(Z(E)){if(!S)return;E=new f,T.set(v,E)}var D=E.get(y);if(Z(D)){if(!S)return;D=new f,E.set(y,D)}return D}function rn(v,y,S){var E=di(v,y,S);if(E)return!0;var D=jn(y);return gt(D)?!1:rn(v,D,S)}function di(v,y,S){var E=Ie(y,S,!1);return Z(E)?!1:_o(E.has(v))}function an(v,y,S){var E=di(v,y,S);if(E)return O(v,y,S);var D=jn(y);if(!gt(D))return an(v,D,S)}function O(v,y,S){var E=Ie(y,S,!1);if(!Z(E))return E.get(v)}function oe(v,y,S,E){var D=Ie(S,E,!0);D.set(v,y)}function ce(v,y){var S=Ae(v,y),E=jn(v);if(E===null)return S;var D=ce(E,y);if(D.length<=0)return S;if(S.length<=0)return D;for(var de=new p,B=[],J=0,U=S;J<U.length;J++){var H=U[J],W=de.has(H);W||(de.add(H),B.push(H))}for(var Gt=0,Vs=D;Gt<Vs.length;Gt++){var H=Vs[Gt],W=de.has(H);W||(de.add(H),B.push(H))}return B}function Ae(v,y){var S=[],E=Ie(v,y,!1);if(Z(E))return S;for(var D=E.keys(),de=Oo(D),B=0;;){var J=No(de);if(!J)return S.length=B,S;var U=Lo(J);try{S[B]=U}catch(H){try{xo(de)}finally{throw H}}B++}}function Oe(v){if(v===null)return 1;switch(typeof v){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return v===null?1:6;default:return 6}}function Z(v){return v===void 0}function gt(v){return v===null}function on(v){return typeof v=="symbol"}function ie(v){return typeof v=="object"?v!==null:typeof v=="function"}function Jn(v,y){switch(Oe(v)){case 0:return v;case 1:return v;case 2:return v;case 3:return v;case 4:return v;case 5:return v}var S=y===3?"string":y===5?"number":"default",E=js(v,s);if(E!==void 0){var D=E.call(v,S);if(ie(D))throw new TypeError;return D}return Ro(v,S==="default"?"number":S)}function Ro(v,y){if(y==="string"){var S=v.toString;if(li(S)){var E=S.call(v);if(!ie(E))return E}var D=v.valueOf;if(li(D)){var E=D.call(v);if(!ie(E))return E}}else{var D=v.valueOf;if(li(D)){var E=D.call(v);if(!ie(E))return E}var de=v.toString;if(li(de)){var E=de.call(v);if(!ie(E))return E}}throw new TypeError}function _o(v){return!!v}function Io(v){return""+v}function vt(v){var y=Jn(v,3);return on(y)?y:Io(y)}function Bs(v){return Array.isArray?Array.isArray(v):v instanceof Object?v instanceof Array:Object.prototype.toString.call(v)==="[object Array]"}function li(v){return typeof v=="function"}function Js(v){return typeof v=="function"}function Ao(v){switch(Oe(v)){case 3:return!0;case 4:return!0;default:return!1}}function js(v,y){var S=v[y];if(S!=null){if(!li(S))throw new TypeError;return S}}function Oo(v){var y=js(v,r);if(!li(y))throw new TypeError;var S=y.call(v);if(!ie(S))throw new TypeError;return S}function Lo(v){return v.value}function No(v){var y=v.next();return y.done?!1:y}function xo(v){var y=v.return;y&&y.call(v)}function jn(v){var y=Object.getPrototypeOf(v);if(typeof v!="function"||v===d||y!==d)return y;var S=v.prototype,E=S&&Object.getPrototypeOf(S);if(E==null||E===Object.prototype)return y;var D=E.constructor;return typeof D!="function"||D===v?y:D}function Do(){var v={},y=[],S=function(){function B(J,U,H){this._index=0,this._keys=J,this._values=U,this._selector=H}return B.prototype["@@iterator"]=function(){return this},B.prototype[r]=function(){return this},B.prototype.next=function(){var J=this._index;if(J>=0&&J<this._keys.length){var U=this._selector(this._keys[J],this._values[J]);return J+1>=this._keys.length?(this._index=-1,this._keys=y,this._values=y):this._index++,{value:U,done:!1}}return{value:void 0,done:!0}},B.prototype.throw=function(J){throw this._index>=0&&(this._index=-1,this._keys=y,this._values=y),J},B.prototype.return=function(J){return this._index>=0&&(this._index=-1,this._keys=y,this._values=y),{value:J,done:!0}},B}();return function(){function B(){this._keys=[],this._values=[],this._cacheKey=v,this._cacheIndex=-2}return Object.defineProperty(B.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),B.prototype.has=function(J){return this._find(J,!1)>=0},B.prototype.get=function(J){var U=this._find(J,!1);return U>=0?this._values[U]:void 0},B.prototype.set=function(J,U){var H=this._find(J,!0);return this._values[H]=U,this},B.prototype.delete=function(J){var U=this._find(J,!1);if(U>=0){for(var H=this._keys.length,W=U+1;W<H;W++)this._keys[W-1]=this._keys[W],this._values[W-1]=this._values[W];return this._keys.length--,this._values.length--,J===this._cacheKey&&(this._cacheKey=v,this._cacheIndex=-2),!0}return!1},B.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=v,this._cacheIndex=-2},B.prototype.keys=function(){return new S(this._keys,this._values,E)},B.prototype.values=function(){return new S(this._keys,this._values,D)},B.prototype.entries=function(){return new S(this._keys,this._values,de)},B.prototype["@@iterator"]=function(){return this.entries()},B.prototype[r]=function(){return this.entries()},B.prototype._find=function(J,U){return this._cacheKey!==J&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=J)),this._cacheIndex<0&&U&&(this._cacheIndex=this._keys.length,this._keys.push(J),this._values.push(void 0)),this._cacheIndex},B}();function E(B,J){return B}function D(B,J){return J}function de(B,J){return[B,J]}}function Mo(){return function(){function v(){this._map=new f}return Object.defineProperty(v.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),v.prototype.has=function(y){return this._map.has(y)},v.prototype.add=function(y){return this._map.set(y,y),this},v.prototype.delete=function(y){return this._map.delete(y)},v.prototype.clear=function(){this._map.clear()},v.prototype.keys=function(){return this._map.keys()},v.prototype.values=function(){return this._map.values()},v.prototype.entries=function(){return this._map.entries()},v.prototype["@@iterator"]=function(){return this.keys()},v.prototype[r]=function(){return this.keys()},v}()}function Uo(){var v=16,y=u.create(),S=E();return function(){function U(){this._key=E()}return U.prototype.has=function(H){var W=D(H,!1);return W!==void 0?u.has(W,this._key):!1},U.prototype.get=function(H){var W=D(H,!1);return W!==void 0?u.get(W,this._key):void 0},U.prototype.set=function(H,W){var Gt=D(H,!0);return Gt[this._key]=W,this},U.prototype.delete=function(H){var W=D(H,!1);return W!==void 0?delete W[this._key]:!1},U.prototype.clear=function(){this._key=E()},U}();function E(){var U;do U="@@WeakMap@@"+J();while(u.has(y,U));return y[U]=!0,U}function D(U,H){if(!t.call(U,S)){if(!H)return;Object.defineProperty(U,S,{value:u.create()})}return U[S]}function de(U,H){for(var W=0;W<H;++W)U[W]=Math.random()*255|0;return U}function B(U){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(U)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(U)):de(new Uint8Array(U),U):de(new Array(U),U)}function J(){var U=B(v);U[6]=U[6]&79|64,U[8]=U[8]&191|128;for(var H="",W=0;W<v;++W){var Gt=U[W];(W===4||W===6||W===8)&&(H+="-"),Gt<16&&(H+="0"),H+=Gt.toString(16).toLowerCase()}return H}}function Vn(v){return v.__=void 0,delete v.__,v}})})(Ks||(Ks={}));function du(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 lu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function hu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Zr={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(lu,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(T,w){var _=T[w];if(typeof _.bind=="function")return _.bind(T);try{return Function.prototype.bind.call(_,T)}catch{return function(){return Function.prototype.apply.apply(_,[T,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(T){return T==="debug"&&(T="log"),typeof console===t?!1:T==="trace"&&n?a:console[T]!==void 0?r(console,T):console.log!==void 0?r(console,"log"):e}function c(T,w){for(var _=0;_<s.length;_++){var M=s[_];this[M]=_<T?e:this.methodFactory(M,T,w)}this.log=this.debug}function u(T,w,_){return function(){typeof console!==t&&(c.call(this,w,_),this[T].apply(this,arguments))}}function d(T,w,_){return o(T)||u.apply(this,arguments)}function h(T,w,_){var M=this,Q;w=w??"WARN";var j="loglevel";typeof T=="string"?j+=":"+T:typeof T=="symbol"&&(j=void 0);function he(A){var F=(s[A]||"silent").toUpperCase();if(!(typeof window===t||!j)){try{window.localStorage[j]=F;return}catch{}try{window.document.cookie=encodeURIComponent(j)+"="+F+";"}catch{}}}function ae(){var A;if(!(typeof window===t||!j)){try{A=window.localStorage[j]}catch{}if(typeof A===t)try{var F=window.document.cookie,fe=F.indexOf(encodeURIComponent(j)+"=");fe!==-1&&(A=/^([^;]+)/.exec(F.slice(fe))[1])}catch{}return M.levels[A]===void 0&&(A=void 0),A}}function q(){if(!(typeof window===t||!j)){try{window.localStorage.removeItem(j);return}catch{}try{window.document.cookie=encodeURIComponent(j)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}M.name=T,M.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},M.methodFactory=_||d,M.getLevel=function(){return Q},M.setLevel=function(A,F){if(typeof A=="string"&&M.levels[A.toUpperCase()]!==void 0&&(A=M.levels[A.toUpperCase()]),typeof A=="number"&&A>=0&&A<=M.levels.SILENT){if(Q=A,F!==!1&&he(A),c.call(M,A,T),typeof console===t&&A<M.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+A},M.setDefaultLevel=function(A){w=A,ae()||M.setLevel(A,!1)},M.resetLevel=function(){M.setLevel(w,!1),q()},M.enableAll=function(A){M.setLevel(M.levels.TRACE,A)},M.disableAll=function(A){M.setLevel(M.levels.SILENT,A)};var K=ae();K==null&&(K=w),M.setLevel(K,!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 _=p[w];return _||(_=p[w]=new h(w,f.getLevel(),f.methodFactory)),_};var b=typeof window!==t?window.log:void 0;return f.noConflict=function(){return typeof window!==t&&window.log===f&&(window.log=b),f},f.getLoggers=function(){return p},f.default=f,f})})(Zr);var ea=Zr.exports,cs;(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"})(cs||(cs={}));const m=ea.getLogger("livekit");m.setDefaultLevel(cs.info);ea.getLogger("lk-e2ee");function Ee(i,e){if(!i)throw new Error(e)}const fu=34028234663852886e22,pu=-34028234663852886e22,mu=4294967295,gu=2147483647,vu=-2147483648;function gn(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>gu||i<vu)throw new Error("invalid int 32: "+i)}function us(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>mu||i<0)throw new Error("invalid uint 32: "+i)}function ta(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>fu||i<pu))throw new Error("invalid float 32: "+i)}const ia=Symbol("@bufbuild/protobuf/enum-type");function yu(i){const e=i[ia];return Ee(e,"missing enum type on enum object"),e}function na(i,e,t,n){i[ia]=sa(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function sa(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=ra(a);r.push(o),n[a.name]=o,s[a.no]=o}return{typeName:i,values:r,findName(a){return n[a]},findNumber(a){return s[a]}}}function bu(i,e,t){const n={};for(const s of e){const r=ra(s);n[r.localName]=r.no,n[r.no]=r.localName}return na(n,i,e),n}function ra(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class I{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 ku(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),a={[r]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new I),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Tu(i,e,t,n){return{syntax:i,json:e,bin:t,util:n,makeMessageType(s,r,a){return ku(this,s,r,a)},makeEnum:bu,makeEnumType:sa,getEnumType:yu}}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={}));function Su(){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 Hn(i,e,t){for(let r=0;r<28;r=r+7){const a=i>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)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 a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const vn=4294967296;function Ys(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(a,o){const c=Number(i.slice(a,o));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?oa(n,s):Os(n,s)}function Cu(i,e){let t=Os(i,e);const n=t.hi&2147483648;n&&(t=oa(t.lo,t.hi));const s=aa(t.lo,t.hi);return n?"-"+s:s}function aa(i,e){if({lo:i,hi:e}=wu(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,a=n+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Xs(a)+Xs(r)}function wu(i,e){return{lo:i>>>0,hi:e>>>0}}function Os(i,e){return{lo:i|0,hi:e|0}}function oa(i,e){return e=~e,i?i=~i+1:e+=1,Os(i,e)}const Xs=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Qs(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 Eu(){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 Pu(){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"),a=BigInt("0"),o=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>o||u<a)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=>Ee(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Ee(/^[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),Ys(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Ys(s)},dec(s,r){return Cu(s,r)},uDec(s,r){return aa(s,r)}}}const V=Pu();var se;(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"})(se||(se={}));class Ru{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(us(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return gn(e),Qs(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){ta(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){us(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){gn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return gn(e),e=(e<<1^e>>31)>>>0,Qs(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=V.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=V.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return Hn(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Hn(s,r,this.buf),this}uint64(e){let t=V.uEnc(e);return Hn(t.lo,t.hi,this.buf),this}}class _u{constructor(e,t){this.varint64=Su,this.uint32=Eu,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 se.Varint:for(;this.buf[this.pos++]&128;);break;case se.Bit64:this.pos+=4;case se.Bit32:this.pos+=4;break;case se.LengthDelimited:let n=this.uint32();this.pos+=n;break;case se.StartGroup:let s;for(;(s=this.tag()[1])!==se.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 V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,V.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 V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.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 I||!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 zt(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){switch(i){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return V.zero;case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function ca(i,e){const t=e===void 0;let n=se.Varint,s=e===0;switch(i){case k.STRING:s=t||!e.length,n=se.LengthDelimited;break;case k.BOOL:s=e===!1;break;case k.DOUBLE:n=se.Bit64;break;case k.FLOAT:n=se.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=se.Bit64;break;case k.BYTES:s=t||!e.byteLength,n=se.LengthDelimited;break;case k.FIXED32:n=se.Bit32;break;case k.SFIXED32:n=se.Bit32;break;case k.SFIXED64:s=t||e==0,n=se.Bit64;break;case k.SINT64:s=t||e==0;break}const r=k[i].toLowerCase();return[n,r,t||s]}const pi=Symbol("@bufbuild/protobuf/unknown-fields"),Zs={readUnknownFields:!0,readerFactory:i=>new _u(i)},er={writeUnknownFields:!0,writerFactory:()=>new Ru};function Iu(i){return i?Object.assign(Object.assign({},Zs),i):Zs}function Au(i){return i?Object.assign(Object.assign({},er),i):er}function Ou(){return{makeReadOptions:Iu,makeWriteOptions:Au,listUnknownFields(i){var e;return(e=i[pi])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[pi]},writeUnknownFields(i,e){const n=i[pi];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[pi])||(s[pi]=[]),s[pi].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[a,o]=e.tag(),c=s.fields.find(a);if(!c){const f=e.skip(o);n.readUnknownFields&&this.onUnknownField(i,a,o,f);continue}let u=i,d=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;if(d){let w=u[h];if(o==se.LengthDelimited&&f!=k.STRING&&f!=k.BYTES){let _=e.uint32()+e.pos;for(;e.pos<_;)w.push(ji(e,f))}else w.push(ji(e,f))}else u[h]=ji(e,f);break;case"message":const p=c.T;d?u[h].push(yn(e,new p,n)):u[h]instanceof I?yn(e,u[h],n):(u[h]=yn(e,new p,n),p.fieldWrapper&&!c.oneof&&!c.repeated&&(u[h]=p.fieldWrapper.unwrapField(u[h])));break;case"map":let[b,T]=Lu(c,e,n);u[h][b]=T;break}}}}}function yn(i,e,t){return e.getType().runtime.bin.readMessage(e,i,i.uint32(),t),e}function Lu(i,e,t){const n=e.uint32(),s=e.pos+n;let r,a;for(;e.pos<s;){let[o]=e.tag();switch(o){case 1:r=ji(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=ji(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=yn(e,new i.V.T,t);break}break}}if(r===void 0){let o=ls(i.K);r=i.K==k.BOOL?o.toString():o}if(typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=ls(i.V.T);break;case"enum":a=0;break;case"message":a=new i.V.T;break}return[r,a]}function ji(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 Nu(i,e,t,n,s){i.tag(t.no,se.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:Ee(n=="true"||n=="false"),r=n=="true";break}switch(Vi(i,t.K,1,r,!0),t.V.kind){case"scalar":Vi(i,t.V.T,2,s,!0);break;case"enum":Vi(i,k.INT32,2,s,!0);break;case"message":hs(i,e,t.V.T,2,s);break}i.join()}function hs(i,e,t,n,s){if(s!==void 0){const r=ds(t,s);i.tag(n,se.LengthDelimited).bytes(r.toBinary(e))}}function Vi(i,e,t,n,s){let[r,a,o]=ca(e,n);(!o||s)&&i.tag(t,r)[a](n)}function xu(i,e,t,n){if(!n.length)return;i.tag(t,se.LengthDelimited).fork();let[,s]=ca(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Du(){return Object.assign(Object.assign({},Ou()),{writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){let r,a=s.repeated,o=s.localName;if(s.oneof){const c=i[s.oneof.localName];if(c.case!==o)continue;r=c.value}else r=i[o];switch(s.kind){case"scalar":case"enum":let c=s.kind=="enum"?k.INT32:s.T;if(a)if(s.packed)xu(e,c,s.no,r);else for(const u of r)Vi(e,c,s.no,u,!0);else r!==void 0&&Vi(e,c,s.no,r,!!s.oneof||s.opt);break;case"message":if(a)for(const u of r)hs(e,t,s.T,s.no,u);else hs(e,t,s.T,s.no,r);break;case"map":for(const[u,d]of Object.entries(r))Nu(e,t,s,u,d);break}}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e}})}let kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Dn=[];for(let i=0;i<kt.length;i++)Dn[kt[i].charCodeAt(0)]=i;Dn["-".charCodeAt(0)]=kt.indexOf("+");Dn["_".charCodeAt(0)]=kt.indexOf("/");const ua={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,a=0;for(let o=0;o<i.length;o++){if(r=Dn[i.charCodeAt(o)],r===void 0)switch(i[o]){case"=":s=0;case`
15
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[n++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[n++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[n++]=(a&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+=kt[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=kt[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=kt[s|n>>6],e+=kt[n&63],t=0;break}return t&&(e+=kt[s],e+="=",t==1&&(e+="=")),e}},tr={ignoreUnknownFields:!1},ir={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Mu(i){return i?Object.assign(Object.assign({},tr),i):tr}function Uu(i){return i?Object.assign(Object.assign({},ir),i):ir}function Fu(i){const e=i(Bu,nr);return{makeReadOptions:Mu,makeWriteOptions:Uu,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 a={};for(const[o,c]of Object.entries(n)){const u=t.fields.findJsonName(o);if(!u){if(!s.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'));continue}let d=u.localName,h=r;if(u.oneof){if(c===null&&u.kind=="scalar")continue;const f=a[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(o,'"'));a[u.oneof.localName]=o,h=h[u.oneof.localName]={case:d},d="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[d];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 b;switch(u.kind){case"message":b=u.T.fromJson(p,s);break;case"enum":if(b=Wn(u.T,p,s.ignoreUnknownFields),b===void 0)continue;break;case"scalar":try{b=Ii(u.T,p)}catch(T){let w="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(p));throw T instanceof Error&&T.message.length>0&&(w+=": ".concat(T.message)),new Error(w)}break}f.push(b)}}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[d];for(const[p,b]of Object.entries(c)){if(b===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: map value null"));let T;switch(u.V.kind){case"message":T=u.V.T.fromJson(b,s);break;case"enum":if(T=Wn(u.V.T,b,s.ignoreUnknownFields),T===void 0)continue;break;case"scalar":try{T=Ii(u.V.T,b)}catch(w){let _="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&&(_+=": ".concat(w.message)),new Error(_)}break}try{f[Ii(u.K,u.K==k.BOOL?p=="true"?!0:p=="false"?!1:p:p).toString()]=T}catch(w){let _="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&&(_+=": ".concat(w.message)),new Error(_)}}}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(o,'"'));continue}h[d]instanceof I?h[d].fromJson(c,s):(h[d]=f.fromJson(c,s),f.fieldWrapper&&!u.oneof&&(h[d]=f.fieldWrapper.unwrapField(h[d])));break;case"enum":const p=Wn(u.T,c,s.ignoreUnknownFields);p!==void 0&&(h[d]=p);break;case"scalar":try{h[d]=Ii(u.T,c)}catch(b){let T="cannot decode field ".concat(t.typeName,".").concat(u.name," from JSON: ").concat(this.debug(c));throw b instanceof Error&&b.message.length>0&&(T+=": ".concat(b.message)),new Error(T)}break}}return r},writeMessage(t,n){const s=t.getType(),r={};let a;try{for(const o of s.fields.byMember()){let c;if(o.kind=="oneof"){const u=t[o.localName];if(u.value===void 0)continue;if(a=o.findField(u.case),!a)throw"oneof case not found: "+u.case;c=e(a,u.value,n)}else a=o,c=e(a,t[a.localName],n);c!==void 0&&(r[n.useProtoFieldName?a.name:a.jsonName]=c)}}catch(o){const c=a?"cannot encode field ".concat(s.typeName,".").concat(a.name," to JSON"):"cannot encode message ".concat(s.typeName," to JSON"),u=o instanceof Error?o.message:String(o);throw new Error(c+(u.length>0?": ".concat(u):""))}return r},readScalar:Ii,writeScalar:nr,debug:da}}function da(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 Ii(i,e){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 t=Number(e);if(Number.isNaN(t)||!Number.isFinite(t))break;return i==k.FLOAT&&ta(t),t;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:if(e===null)return 0;let n;if(typeof e=="number"?n=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(n=Number(e)),n===void 0)break;return i==k.UINT32?us(n):gn(n),n;case k.INT64:case k.SFIXED64:case k.SINT64:if(e===null)return V.zero;if(typeof e!="number"&&typeof e!="string")break;return V.parse(e);case k.FIXED64:case k.UINT64:if(e===null)return V.zero;if(typeof e!="number"&&typeof e!="string")break;return V.uParse(e);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 ua.dec(e)}throw new Error}function Wn(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(da(e)))}function Bu(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 nr(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 Ee(typeof e=="number"),e!=0||t?e:void 0;case k.FLOAT:case k.DOUBLE:return Ee(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 Ee(typeof e=="string"),e.length>0||t?e:void 0;case k.BOOL:return Ee(typeof e=="boolean"),e||t?e:void 0;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return Ee(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case k.BYTES:return Ee(e instanceof Uint8Array),t||e.byteLength>0?ua.enc(e):void 0}}function Ju(){return Fu((i,e)=>function(n,s,r){if(n.kind=="map"){const a={};switch(n.V.kind){case"scalar":for(const[c,u]of Object.entries(s)){const d=e(n.V.T,u,!0);Ee(d!==void 0),a[c.toString()]=d}break;case"message":for(const[c,u]of Object.entries(s))a[c.toString()]=u.toJson(r);break;case"enum":const o=n.V.T;for(const[c,u]of Object.entries(s)){Ee(u===void 0||typeof u=="number");const d=i(o,u,!0,r.enumAsInteger);Ee(d!==void 0),a[c.toString()]=d}break}return r.emitDefaultValues||Object.keys(a).length>0?a:void 0}else if(n.repeated){const a=[];switch(n.kind){case"scalar":for(let o=0;o<s.length;o++)a.push(e(n.T,s[o],!0));break;case"enum":for(let o=0;o<s.length;o++)a.push(i(n.T,s[o],!0,r.enumAsInteger));break;case"message":for(let o=0;o<s.length;o++)a.push(ds(n.T,s[o]).toJson(r));break}return r.emitDefaultValues||a.length>0?a: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 ju(){return{setEnumType:na,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,a=i;if(a[s]!==void 0)switch(n.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=n.findField(o);let u=a[s].value;c&&c.kind=="message"&&!(u instanceof c.T)?u=new c.T(u):c&&c.kind==="scalar"&&c.T===k.BYTES&&(u=Ai(u)),r[s]={case:o,value:u};break;case"scalar":case"enum":let d=a[s];n.T===k.BYTES&&(d=n.repeated?d.map(Ai):Ai(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===k.BYTES)for(const[p,b]of Object.entries(a[s]))r[s][p]=Ai(b);else Object.assign(r[s],a[s]);break;case"message":const f=n.V.T;for(const p of Object.keys(a[s])){let b=a[s][p];f.fieldWrapper||(b=new f(b)),r[s][p]=b}break}break;case"message":const h=n.T;if(n.repeated)r[s]=a[s].map(f=>f instanceof h?f:new h(f));else if(a[s]!==void 0){const f=a[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?r[s]=Ai(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((a,o)=>n.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>zt(n.T,a,r[o]));case"enum":return s.every((a,o)=>zt(k.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(s,r);case"enum":return zt(k.INT32,s,r);case"scalar":return zt(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=n.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return zt(k.INT32,s.value,r.value);case"scalar":return zt(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const c=n.V.T;return o.every(d=>c.equals(s[d],r[d]));case"enum":return o.every(d=>zt(k.INT32,s[d],r[d]));case"scalar":const u=n.V.T;return o.every(d=>zt(u,s[d],r[d]))}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 a;if(s.repeated)a=r.map(ln);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=ln(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:ln(r.value)}:{case:void 0}:a=ln(r);n[s.localName]=a}return t}}}function ln(i){if(i===void 0)return i;if(i instanceof I)return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Ai(i){return i instanceof Uint8Array?i:new Uint8Array(i)}class Vu{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 la(i,e){const t=ha(i);return e?t:zu(Gu(t))}function $u(i){return la(i,!1)}const qu=ha;function ha(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 Hu=new Set(["constructor","toString","toJSON","valueOf"]),Wu=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),fa=i=>"".concat(i,"$"),Gu=i=>Wu.has(i)?fa(i):i,zu=i=>Hu.has(i)?fa(i):i;class Ku{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=$u(e)}addField(e){Ee(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 l=Tu("proto3",Ju(),Du(),Object.assign(Object.assign({},ju()),{newFieldList(i){return new Vu(i,Yu)},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);break}}}}));function Yu(i){var e,t,n;const s=[];let r;for(const a of typeof i=="function"?i():i){const o=a;if(o.localName=la(a.name,a.oneof!==void 0),o.jsonName=(e=a.jsonName)!==null&&e!==void 0?e:qu(a.name),o.repeated=(t=a.repeated)!==null&&t!==void 0?t:!1,o.packed=(n=a.packed)!==null&&n!==void 0?n:a.kind=="enum"||a.kind=="scalar"&&a.T!=k.BYTES&&a.T!=k.STRING,a.oneof!==void 0){const c=typeof a.oneof=="string"?a.oneof:a.oneof.name;(!r||r.name!=c)&&(r=new Ku(c)),o.oneof=r,r.addField(o)}s.push(o)}return s}class me extends I{constructor(e){super(),this.seconds=V.zero,this.nanos=0,l.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(l.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=V.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 me.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new me({seconds:V.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new me().fromBinary(e,t)}static fromJson(e,t){return new me().fromJson(e,t)}static fromJsonString(e,t){return new me().fromJsonString(e,t)}static equals(e,t){return l.util.equals(me,e,t)}}me.runtime=l;me.typeName="google.protobuf.Timestamp";me.fields=l.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={}));l.util.setEnumType(fs,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]);var ps;(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"})(ps||(ps={}));l.util.setEnumType(ps,"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 ge;(function(i){i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.DATA=2]="DATA"})(ge||(ge={}));l.util.setEnumType(ge,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]);var re;(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"})(re||(re={}));l.util.setEnumType(re,"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 ue;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH",i[i.OFF=3]="OFF"})(ue||(ue={}));l.util.setEnumType(ue,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]);var ei;(function(i){i[i.POOR=0]="POOR",i[i.GOOD=1]="GOOD",i[i.EXCELLENT=2]="EXCELLENT"})(ei||(ei={}));l.util.setEnumType(ei,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"}]);var Ke;(function(i){i[i.UNSET=0]="UNSET",i[i.DISABLED=1]="DISABLED",i[i.ENABLED=2]="ENABLED"})(Ke||(Ke={}));l.util.setEnumType(Ke,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]);var Ht;(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"})(Ht||(Ht={}));l.util.setEnumType(Ht,"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"}]);var Fe;(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"})(Fe||(Fe={}));l.util.setEnumType(Fe,"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 Yi;(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"})(Yi||(Yi={}));l.util.setEnumType(Yi,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let Ei=class Mi extends I{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=V.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,l.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 l.util.equals(Mi,e,t)}};Ei.runtime=l;Ei.typeName="livekit.Room";Ei.fields=l.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:$e,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:12,name:"playout_delay",kind:"message",T:Tt}]);class $e extends I{constructor(e){super(),this.mime="",this.fmtpLine="",l.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 l.util.equals($e,e,t)}}$e.runtime=l;$e.typeName="livekit.Codec";$e.fields=l.util.newFieldList(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);class Tt extends I{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,l.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 l.util.equals(Tt,e,t)}}Tt.runtime=l;Tt.typeName="livekit.PlayoutDelay";Tt.fields=l.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 St extends I{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,l.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 l.util.equals(St,e,t)}}St.runtime=l;St.typeName="livekit.ParticipantPermission";St.fields=l.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:l.getEnumType(re),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}]);class Me extends I{constructor(e){super(),this.sid="",this.identity="",this.state=ai.JOINING,this.tracks=[],this.metadata="",this.joinedAt=V.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new Me().fromBinary(e,t)}static fromJson(e,t){return new Me().fromJson(e,t)}static fromJsonString(e,t){return new Me().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Me,e,t)}}Me.runtime=l;Me.typeName="livekit.ParticipantInfo";Me.fields=l.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:l.getEnumType(ai)},{no:4,name:"tracks",kind:"message",T:Pe,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:St},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8}]);var ai;(function(i){i[i.JOINING=0]="JOINING",i[i.JOINED=1]="JOINED",i[i.ACTIVE=2]="ACTIVE",i[i.DISCONNECTED=3]="DISCONNECTED"})(ai||(ai={}));l.util.setEnumType(ai,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);class Kt extends I{constructor(e){super(),l.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 l.util.equals(Kt,e,t)}}Kt.runtime=l;Kt.typeName="livekit.Encryption";Kt.fields=l.util.newFieldList(()=>[]);var ke;(function(i){i[i.NONE=0]="NONE",i[i.GCM=1]="GCM",i[i.CUSTOM=2]="CUSTOM"})(ke||(ke={}));l.util.setEnumType(ke,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class Ct extends I{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],l.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 l.util.equals(Ct,e,t)}}Ct.runtime=l;Ct.typeName="livekit.SimulcastCodecInfo";Ct.fields=l.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:Te,repeated:!0}]);class Pe extends I{constructor(e){super(),this.sid="",this.type=ge.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=re.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=ke.NONE,this.stream="",l.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 l.util.equals(Pe,e,t)}}Pe.runtime=l;Pe.typeName="livekit.TrackInfo";Pe.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:l.getEnumType(ge)},{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:l.getEnumType(re)},{no:10,name:"layers",kind:"message",T:Te,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:Ct,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:l.getEnumType(ke)},{no:17,name:"stream",kind:"scalar",T:9}]);class Te extends I{constructor(e){super(),this.quality=ue.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new Te().fromBinary(e,t)}static fromJson(e,t){return new Te().fromJson(e,t)}static fromJsonString(e,t){return new Te().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Te,e,t)}}Te.runtime=l;Te.typeName="livekit.VideoLayer";Te.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(ue)},{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 Ze extends I{constructor(e){super(),this.kind=le.RELIABLE,this.value={case:void 0},l.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 l.util.equals(Ze,e,t)}}Ze.runtime=l;Ze.typeName="livekit.DataPacket";Ze.fields=l.util.newFieldList(()=>[{no:1,name:"kind",kind:"enum",T:l.getEnumType(le)},{no:2,name:"user",kind:"message",T:tt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:wt,oneof:"value"}]);var le;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY"})(le||(le={}));l.util.setEnumType(le,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class wt extends I{constructor(e){super(),this.speakers=[],l.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 l.util.equals(wt,e,t)}}wt.runtime=l;wt.typeName="livekit.ActiveSpeakerUpdate";wt.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:et,repeated:!0}]);class et extends I{constructor(e){super(),this.sid="",this.level=0,this.active=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new et().fromBinary(e,t)}static fromJson(e,t){return new et().fromJson(e,t)}static fromJsonString(e,t){return new et().fromJsonString(e,t)}static equals(e,t){return l.util.equals(et,e,t)}}et.runtime=l;et.typeName="livekit.SpeakerInfo";et.fields=l.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 tt extends I{constructor(e){super(),this.participantSid="",this.payload=new Uint8Array(0),this.destinationSids=[],l.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 l.util.equals(tt,e,t)}}tt.runtime=l;tt.typeName="livekit.UserPacket";tt.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0}]);class it extends I{constructor(e){super(),this.participantSid="",this.trackSids=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new it().fromBinary(e,t)}static fromJson(e,t){return new it().fromJson(e,t)}static fromJsonString(e,t){return new it().fromJsonString(e,t)}static equals(e,t){return l.util.equals(it,e,t)}}it.runtime=l;it.typeName="livekit.ParticipantTracks";it.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]);class Et extends I{constructor(e){super(),this.edition=Ci.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Et().fromBinary(e,t)}static fromJson(e,t){return new Et().fromJson(e,t)}static fromJsonString(e,t){return new Et().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Et,e,t)}}Et.runtime=l;Et.typeName="livekit.ServerInfo";Et.fields=l.util.newFieldList(()=>[{no:1,name:"edition",kind:"enum",T:l.getEnumType(Ci)},{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 Ci;(function(i){i[i.Standard=0]="Standard",i[i.Cloud=1]="Cloud"})(Ci||(Ci={}));l.util.setEnumType(Ci,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class Pt extends I{constructor(e){super(),this.sdk=wi.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",l.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 l.util.equals(Pt,e,t)}}Pt.runtime=l;Pt.typeName="livekit.ClientInfo";Pt.fields=l.util.newFieldList(()=>[{no:1,name:"sdk",kind:"enum",T:l.getEnumType(wi)},{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 wi;(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"})(wi||(wi={}));l.util.setEnumType(wi,"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"}]);class nt extends I{constructor(e){super(),this.resumeConnection=Ke.UNSET,this.forceRelay=Ke.UNSET,l.util.initPartial(e,this)}static fromBinary(e,t){return new nt().fromBinary(e,t)}static fromJson(e,t){return new nt().fromJson(e,t)}static fromJsonString(e,t){return new nt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(nt,e,t)}}nt.runtime=l;nt.typeName="livekit.ClientConfiguration";nt.fields=l.util.newFieldList(()=>[{no:1,name:"video",kind:"message",T:st},{no:2,name:"screen",kind:"message",T:st},{no:3,name:"resume_connection",kind:"enum",T:l.getEnumType(Ke)},{no:4,name:"disabled_codecs",kind:"message",T:Rt},{no:5,name:"force_relay",kind:"enum",T:l.getEnumType(Ke)}]);class st extends I{constructor(e){super(),this.hardwareEncoder=Ke.UNSET,l.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 l.util.equals(st,e,t)}}st.runtime=l;st.typeName="livekit.VideoConfiguration";st.fields=l.util.newFieldList(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:l.getEnumType(Ke)}]);class Rt extends I{constructor(e){super(),this.codecs=[],this.publish=[],l.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 l.util.equals(Rt,e,t)}}Rt.runtime=l;Rt.typeName="livekit.DisabledCodecs";Rt.fields=l.util.newFieldList(()=>[{no:1,name:"codecs",kind:"message",T:$e,repeated:!0},{no:2,name:"publish",kind:"message",T:$e,repeated:!0}]);class Yt extends I{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=V.zero,this.headerBytes=V.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=V.zero,this.headerBytesDuplicate=V.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=V.zero,this.headerBytesPadding=V.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,this.sampleRate=0,this.driftMs=0,l.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 l.util.equals(Yt,e,t)}}Yt.runtime=l;Yt.typeName="livekit.RTPStats";Yt.fields=l.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:me},{no:2,name:"end_time",kind:"message",T:me},{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:me},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:me},{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:me},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:me},{no:42,name:"sample_rate",kind:"scalar",T:1},{no:43,name:"drift_ms",kind:"scalar",T:1}]);class Xt extends I{constructor(e){super(),this.unixMicro=V.zero,this.ticks=0,l.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 l.util.equals(Xt,e,t)}}Xt.runtime=l;Xt.typeName="livekit.TimedVersion";Xt.fields=l.util.newFieldList(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]);const Oi=7e3,Xu=[0,300,2*2*300,3*3*300,4*4*300,Oi,Oi,Oi,Oi,Oi];class Qu{constructor(e){this._retryDelays=e!==void 0?[...e]:Xu}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 g(i,e,t,n){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(d){try{u(n.next(d))}catch(h){a(h)}}function c(d){try{u(n.throw(d))}catch(h){a(h)}}function u(d){d.done?r(d.value):s(d.value).then(o,c)}u((n=n.apply(i,e||[])).next())})}function sr(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 gi(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 sr=="function"?sr(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(a){return new Promise(function(o,c){a=i[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(u){r({value:u,done:o})},a)}}var Ls={exports:{}},bi=typeof Reflect=="object"?Reflect:null,rr=bi&&typeof bi.apply=="function"?bi.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},bn;bi&&typeof bi.ownKeys=="function"?bn=bi.ownKeys:Object.getOwnPropertySymbols?bn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:bn=function(e){return Object.getOwnPropertyNames(e)};function Zu(i){console&&console.warn&&console.warn(i)}var pa=Number.isNaN||function(e){return e!==e};function X(){X.init.call(this)}Ls.exports=X;Ls.exports.once=nd;X.EventEmitter=X;X.prototype._events=void 0;X.prototype._eventsCount=0;X.prototype._maxListeners=void 0;var ar=10;function Mn(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(X,"defaultMaxListeners",{enumerable:!0,get:function(){return ar},set:function(i){if(typeof i!="number"||i<0||pa(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");ar=i}});X.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};X.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||pa(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 ma(i){return i._maxListeners===void 0?X.defaultMaxListeners:i._maxListeners}X.prototype.getMaxListeners=function(){return ma(this)};X.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 a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=r[e];if(c===void 0)return!1;if(typeof c=="function")rr(c,this,t);else for(var u=c.length,d=ka(c,u),n=0;n<u;++n)rr(d[n],this,t);return!0};function ga(i,e,t,n){var s,r,a;if(Mn(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),a=r[e]),a===void 0)a=r[e]=t,++i._eventsCount;else if(typeof a=="function"?a=r[e]=n?[t,a]:[a,t]:n?a.unshift(t):a.push(t),s=ma(i),s>0&&a.length>s&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=i,o.type=e,o.count=a.length,Zu(o)}return i}X.prototype.addListener=function(e,t){return ga(this,e,t,!1)};X.prototype.on=X.prototype.addListener;X.prototype.prependListener=function(e,t){return ga(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 va(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}X.prototype.once=function(e,t){return Mn(t),this.on(e,va(this,e,t)),this};X.prototype.prependOnceListener=function(e,t){return Mn(t),this.prependListener(e,va(this,e,t)),this};X.prototype.removeListener=function(e,t){var n,s,r,a,o;if(Mn(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,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,r=a;break}if(r<0)return this;r===0?n.shift():td(n,r),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,o||t)}return this};X.prototype.off=X.prototype.removeListener;X.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),a;for(s=0;s<r.length;++s)a=r[s],a!=="removeListener"&&this.removeAllListeners(a);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 ya(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):ka(s,s.length)}X.prototype.listeners=function(e){return ya(this,e,!0)};X.prototype.rawListeners=function(e){return ya(this,e,!1)};X.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):ba.call(i,e)};X.prototype.listenerCount=ba;function ba(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}X.prototype.eventNames=function(){return this._eventsCount>0?bn(this._events):[]};function ka(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(a){i.removeListener(e,r),n(a)}function r(){typeof i.removeListener=="function"&&i.removeListener("error",s),t([].slice.call(arguments))}Ta(i,e,r,{once:!0}),e!=="error"&&sd(i,s,{once:!0})})}function sd(i,e,t){typeof i.on=="function"&&Ta(i,"error",e,t)}function Ta(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 mt=Ls.exports;let Sa=!0,Ca=!0;function kn(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function ui(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=u=>{const d=t(u);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function rd(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Sa=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function ad(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ca=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function wa(){if(typeof window=="object"){if(Sa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Ns(i,e){Ca&&console.warn(i+" is deprecated, please use "+e+" instead.")}function od(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=kn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=kn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=kn(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 or(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ea(i){return or(i)?Object.keys(i).reduce(function(e,t){const n=or(i[t]),s=n?Ea(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function ms(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?ms(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{ms(i,i.get(s),t)})}))}function cr(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&ms(i,o,s)})}),s}const ur=wa;function Pa(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(u=>{if(u==="require"||u==="advanced"||u==="mediaSource")return;const d=typeof o[u]=="object"?o[u]:{ideal:o[u]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const h=function(f,p){return f?f+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(d.ideal!==void 0){c.optional=c.optional||[];let f={};typeof d.ideal=="number"?(f[h("min",u)]=d.ideal,c.optional.push(f),f={},f[h("max",u)]=d.ideal,c.optional.push(f)):(f[h("",u)]=d.ideal,c.optional.push(f))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",u)]=d.exact):["min","max"].forEach(f=>{d[f]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(f,u)]=d[f])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const u=function(d,h,f){h in d&&!(f in d)&&(d[f]=d[h],delete d[h])};o=JSON.parse(JSON.stringify(o)),u(o.audio,"autoGainControl","googAutoGainControl"),u(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let u=o.video.facingMode;u=u&&(typeof u=="object"?u:{ideal:u});const d=e.version<66;if(u&&(u.exact==="user"||u.exact==="environment"||u.ideal==="user"||u.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete o.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(b=>b.kind==="videoinput");let p=f.find(b=>h.some(T=>b.label.toLowerCase().includes(T)));return!p&&f.length&&h.includes("back")&&(p=f[f.length-1]),p&&(o.video.deviceId=u.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=n(o.video),ur("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return ur("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,u){s(o,d=>{t.webkitGetUserMedia(d,c,h=>{u&&u(r(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,u=>o(u).then(d=>{if(u.audio&&!d.getAudioTracks().length||u.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}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,a=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:o||3}},r&&(n.video.mandatory.maxWidth=r),a&&(n.video.mandatory.maxHeight=a),i.navigator.mediaDevices.getUserMedia(n)})}}}function Ra(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function _a(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(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else ui(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ia(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(o,c){let u=s.apply(this,arguments);return u||(u=e(this,o),this._senders.push(u)),u};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);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(a=>{this._senders.push(e(this,a))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 Aa(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 a=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},o=function(c){return new Map(Object.keys(c).map(u=>[u,c[u]]))};if(arguments.length>=2){const c=function(u){s(o(a(u)))};return e.apply(this,[c,n])}return new Promise((c,u)=>{e.apply(this,[function(d){c(o(a(d)))},u])}).then(s,r)}}function Oa(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(a=>a._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(a=>cr(a,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}),ui(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>cr(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,a;return this.getSenders().forEach(o=>{o.track===n&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===n&&(r?a=!0:r=o),o.track===n)),a||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 La(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(u=>o.indexOf(u)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Na(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return La(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(p=>p.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const h=new i.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,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(T=>T===d))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(T=>T.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const b=this._streams[h.id];if(b)b.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const T=new i.MediaStream([d]);this._streams[h.id]=T,this._reverseStreams[T.id]=h,this.addStream(T)}return this.getSenders().find(T=>T.track===d)};function r(u,d){let h=d.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],b=u._streams[p.id];h=h.replace(new RegExp(b.id,"g"),p.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function a(u,d){let h=d.sdp;return Object.keys(u._reverseStreams||[]).forEach(f=>{const p=u._reverseStreams[f],b=u._streams[p.id];h=h.replace(new RegExp(p.id,"g"),b.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(u){const d=i.RTCPeerConnection.prototype[u],h={[u](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[b=>{const T=r(this,b);f[0].apply(null,[T])},b=>{f[1]&&f[1].apply(null,b)},arguments[2]]):d.apply(this,arguments).then(b=>r(this,b))}};i.RTCPeerConnection.prototype[u]=h[u]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const 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(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._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(T=>d.track===T)&&(f=this._streams[p])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function gs(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 xa(i,e){ui(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var dr=Object.freeze({__proto__:null,fixNegotiationNeeded:xa,shimAddTrackRemoveTrack:Na,shimAddTrackRemoveTrackWithNative:La,shimGetDisplayMedia:cd,shimGetSendersWithDtmf:Ia,shimGetStats:Aa,shimGetUserMedia:Pa,shimMediaStream:Ra,shimOnTrack:_a,shimPeerConnection:gs,shimSenderReceiverGetStats:Oa});function Da(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){Ns("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}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 Ma(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 vs(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],a={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=a[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,a,o]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(u=>{u.type=t[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;c.forEach((d,h)=>{c.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(a,o)}}function Ua(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 Fa(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}),ui(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ba(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Ns("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ja(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function ja(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(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Va(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 $a(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 qa(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 lr=Object.freeze({__proto__:null,shimAddTransceiver:ja,shimCreateAnswer:qa,shimCreateOffer:$a,shimGetDisplayMedia:ud,shimGetParameters:Va,shimGetUserMedia:Da,shimOnTrack:Ma,shimPeerConnection:vs,shimRTCDataChannel:Ja,shimReceiverGetStats:Fa,shimRemoveStream:Ba,shimSenderGetStats:Ua});function Ha(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),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),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 Wa(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 a=new Event("addstream");a.stream=r,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Ga(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,a=e.addIceCandidate;e.createOffer=function(u,d){const h=arguments.length>=2?arguments[2]:arguments[0],f=t.apply(this,[h]);return d?(f.then(u,d),Promise.resolve()):f},e.createAnswer=function(u,d){const h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return d?(f.then(u,d),Promise.resolve()):f};let o=function(c,u,d){const h=s.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h};e.setLocalDescription=o,o=function(c,u,d){const h=r.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h},e.setRemoteDescription=o,o=function(c,u,d){const h=a.apply(this,[c]);return d?(h.then(u,d),Promise.resolve()):h},e.addIceCandidate=o}function za(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(Ka(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Ka(i){return i&&i.video!==void 0?Object.assign({},i,{video:Ea(i.video)}):i}function Ya(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Ns("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(n.iceServers[a])}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 Xa(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(a=>a.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(a=>a.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 Za(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var hr=Object.freeze({__proto__:null,shimAudioContext:Za,shimCallbacksAPI:Ga,shimConstraints:Ka,shimCreateOfferLegacy:Qa,shimGetUserMedia:za,shimLocalStreamsAPI:Ha,shimRTCIceServerUrls:Ya,shimRemoteStreamsAPI:Wa,shimTrackEventTransceiver:Xa}),eo={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(`
16
16
  `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
17
17
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
18
18
  `)},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
@@ -29,7 +29,7 @@ a=ice-pwd:`+t.password+`\r
29
29
  `,s+=`c=IN IP4 0.0.0.0\r
30
30
  `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
31
31
  `,n.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let r=0;return n.codecs.forEach(a=>{a.maxptime>r&&(r=a.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r
32
- `),n.headerExtensions&&n.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.attribute==="cname"),c=o.length>0&&o[0].ssrc;let u;const d=e.matchPrefix(t,"a=ssrc-group:FID").map(f=>f.substring(17).split(" ").map(b=>parseInt(b,10)));d.length>0&&d[0].length>1&&d[0][0]===c&&(u=d[0][1]),s.codecs.forEach(f=>{if(f.name.toUpperCase()==="RTX"&&f.parameters.apt){let m={ssrc:c,codecPayloadType:parseInt(f.parameters.apt,10)};c&&u&&(m.rtx={ssrc:u}),n.push(m),r&&(m=JSON.parse(JSON.stringify(m)),m.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},n.push(m))}}),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(o=>e.parseSsrcMedia(o)).filter(o=>o.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 a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
32
+ `),n.headerExtensions&&n.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.attribute==="cname"),c=o.length>0&&o[0].ssrc;let u;const d=e.matchPrefix(t,"a=ssrc-group:FID").map(f=>f.substring(17).split(" ").map(b=>parseInt(b,10)));d.length>0&&d[0].length>1&&d[0][0]===c&&(u=d[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:a?"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(o=>e.parseSsrcMedia(o)).filter(o=>o.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 a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
33
33
  `),t.mux&&(n+=`a=rtcp-mux\r
34
34
  `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
35
35
  `),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(a=>e.parseSsrcMedia(a)).filter(a=>a.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 a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[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
@@ -43,18 +43,18 @@ a=ice-pwd:`+t.password+`\r
43
43
  o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r
44
44
  s=-\r
45
45
  t=0 0\r
46
- `},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})(Qa);var Za=Qa.exports,Ti=lu(Za),ud=uu({__proto__:null,default:Ti},[Za]);function Tn(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=Ti.parseCandidate(n.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});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,ui(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function vs(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||ui(i,"icecandidate",e=>{if(e.candidate){const t=Ti.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Sn(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(o){if(!o||!o.sdp)return!1;const c=Ti.splitSections(o.sdp);return c.shift(),c.some(u=>{const d=Ti.parseMLine(u);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.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(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let u=65536;e.browser==="firefox"&&e.version===57&&(u=65535);const d=Ti.matchPrefix(o.sdp,"a=max-message-size:");return d.length>0?u=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(u=2147483637),u},a=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),d=r(arguments[0],c);let h;u===0&&d===0?h=Number.POSITIVE_INFINITY:u===0||d===0?h=Math.max(u,d):h=Math.min(u,d);const f={};Object.defineProperty(f,"maxMessageSize",{get(){return h}}),this._sctp=f}return a.apply(this,arguments)}}function Cn(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const o=arguments[0],c=o.length||o.size||o.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},ui(i,"datachannel",n=>(e(n.channel,n.target),n))}function ys(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 a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function bs(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(`
46
+ `},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})(eo);var to=eo.exports,ki=hu(to),dd=du({__proto__:null,default:ki},[to]);function Tn(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=ki.parseCandidate(n.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});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,ui(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function ys(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||ui(i,"icecandidate",e=>{if(e.candidate){const t=ki.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Sn(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(o){if(!o||!o.sdp)return!1;const c=ki.splitSections(o.sdp);return c.shift(),c.some(u=>{const d=ki.parseMLine(u);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.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(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let u=65536;e.browser==="firefox"&&e.version===57&&(u=65535);const d=ki.matchPrefix(o.sdp,"a=max-message-size:");return d.length>0?u=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(u=2147483637),u},a=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),d=r(arguments[0],c);let h;u===0&&d===0?h=Number.POSITIVE_INFINITY:u===0||d===0?h=Math.max(u,d):h=Math.min(u,d);const f={};Object.defineProperty(f,"maxMessageSize",{get(){return h}}),this._sctp=f}return a.apply(this,arguments)}}function Cn(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const o=arguments[0],c=o.length||o.size||o.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},ui(i,"datachannel",n=>(e(n.channel,n.target),n))}function bs(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 a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ks(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(`
47
47
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
48
48
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
49
- `);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 En(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(a=>t.apply(this,[a]))})}var dd=Object.freeze({__proto__:null,removeExtmapAllowMixed:bs,shimAddIceCandidateNullOrEmpty:wn,shimConnectionState:ys,shimMaxMessageSize:Sn,shimParameterlessSetLocalDescription:En,shimRTCIceCandidate:Tn,shimRTCIceCandidateRelayProtocol:vs,shimSendThrowTypeError:Cn});function ld(){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=Sa,n=ad(i),s={browserDetails:n,commonShim:dd,extractVersion:kn,disableLog:sd,disableWarnings:rd,sdp:ud};switch(n.browser){case"chrome":if(!cr||!ms||!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=cr,wn(i,n),En(i),wa(i,n),Ea(i),ms(i,n),Pa(i),Aa(i,n),Ra(i),_a(i),Ia(i),Oa(i,n),Tn(i),vs(i),ys(i),Sn(i,n),Cn(i),bs(i,n);break;case"firefox":if(!ur||!gs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=ur,wn(i,n),En(i),La(i,n),gs(i,n),Na(i),Ua(i),Da(i),Ma(i),Fa(i),Ba(i),Ja(i),ja(i),Va(i),Tn(i),ys(i),Sn(i,n),Cn(i);break;case"safari":if(!dr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=dr,wn(i,n),En(i),za(i),Ya(i),Ha(i),$a(i),qa(i),Ka(i),Wa(i),Xa(i),Tn(i),vs(i),Sn(i,n),Cn(i),bs(i,n);break;default:t("Unsupported browser!");break}return s}ld({window:typeof window>"u"?void 0:window});var Re;(function(i){i[i.PUBLISHER=0]="PUBLISHER",i[i.SUBSCRIBER=1]="SUBSCRIBER"})(Re||(Re={}));l.util.setEnumType(Re,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]);var oi;(function(i){i[i.ACTIVE=0]="ACTIVE",i[i.PAUSED=1]="PAUSED"})(oi||(oi={}));l.util.setEnumType(oi,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);var _n;(function(i){i[i.UDP=0]="UDP",i[i.TCP=1]="TCP",i[i.TLS=2]="TLS"})(_n||(_n={}));l.util.setEnumType(_n,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class It extends _{constructor(e){super(),this.message={case:void 0},l.util.initPartial(e,this)}static fromBinary(e,t){return new It().fromBinary(e,t)}static fromJson(e,t){return new It().fromJson(e,t)}static fromJsonString(e,t){return new It().fromJsonString(e,t)}static equals(e,t){return l.util.equals(It,e,t)}}It.runtime=l;It.typeName="livekit.SignalRequest";It.fields=l.util.newFieldList(()=>[{no:1,name:"offer",kind:"message",T:Se,oneof:"message"},{no:2,name:"answer",kind:"message",T:Se,oneof:"message"},{no:3,name:"trickle",kind:"message",T:He,oneof:"message"},{no:4,name:"add_track",kind:"message",T:qe,oneof:"message"},{no:5,name:"mute",kind:"message",T:We,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Je,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:at,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ot,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:lt,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ht,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:ct,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:pt,oneof:"message"}]);class rt extends _{constructor(e){super(),this.message={case:void 0},l.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 l.util.equals(rt,e,t)}}rt.runtime=l;rt.typeName="livekit.SignalResponse";rt.fields=l.util.newFieldList(()=>[{no:1,name:"join",kind:"message",T:xt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Se,oneof:"message"},{no:3,name:"offer",kind:"message",T:Se,oneof:"message"},{no:4,name:"trickle",kind:"message",T:He,oneof:"message"},{no:5,name:"update",kind:"message",T:Lt,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ge,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:9,name:"mute",kind:"message",T:We,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Nt,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Dt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Ut,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Bt,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:jt,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Vt,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ot,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:At,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:$t,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ht,oneof:"message"}]);class Be extends _{constructor(e){super(),this.codec="",this.cid="",this.enableSimulcastLayers=!1,l.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 l.util.equals(Be,e,t)}}Be.runtime=l;Be.typeName="livekit.SimulcastCodec";Be.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:3,name:"enable_simulcast_layers",kind:"scalar",T:8}]);class qe extends _{constructor(e){super(),this.cid="",this.name="",this.type=ge.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=se.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=ke.NONE,this.stream="",l.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 l.util.equals(qe,e,t)}}qe.runtime=l;qe.typeName="livekit.AddTrackRequest";qe.fields=l.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:l.getEnumType(ge)},{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:l.getEnumType(se)},{no:9,name:"layers",kind:"message",T:Te,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Be,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:l.getEnumType(ke)},{no:15,name:"stream",kind:"scalar",T:9}]);class He extends _{constructor(e){super(),this.candidateInit="",this.target=Re.PUBLISHER,l.util.initPartial(e,this)}static fromBinary(e,t){return new He().fromBinary(e,t)}static fromJson(e,t){return new He().fromJson(e,t)}static fromJsonString(e,t){return new He().fromJsonString(e,t)}static equals(e,t){return l.util.equals(He,e,t)}}He.runtime=l;He.typeName="livekit.TrickleRequest";He.fields=l.util.newFieldList(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:l.getEnumType(Re)}]);class We extends _{constructor(e){super(),this.sid="",this.muted=!1,l.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 l.util.equals(We,e,t)}}We.runtime=l;We.typeName="livekit.MuteTrackRequest";We.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]);class xt extends _{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),l.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 l.util.equals(xt,e,t)}}xt.runtime=l;xt.typeName="livekit.JoinResponse";xt.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Pi},{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:ut,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:nt},{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:Pt},{no:13,name:"sif_trailer",kind:"scalar",T:12}]);class At extends _{constructor(e){super(),this.iceServers=[],l.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 l.util.equals(At,e,t)}}At.runtime=l;At.typeName="livekit.ReconnectResponse";At.fields=l.util.newFieldList(()=>[{no:1,name:"ice_servers",kind:"message",T:ut,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:nt}]);class Ge extends _{constructor(e){super(),this.cid="",l.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 l.util.equals(Ge,e,t)}}Ge.runtime=l;Ge.typeName="livekit.TrackPublishedResponse";Ge.fields=l.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Pe}]);class Ot extends _{constructor(e){super(),this.trackSid="",l.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 l.util.equals(Ot,e,t)}}Ot.runtime=l;Ot.typeName="livekit.TrackUnpublishedResponse";Ot.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);class Se extends _{constructor(e){super(),this.type="",this.sdp="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Se().fromBinary(e,t)}static fromJson(e,t){return new Se().fromJson(e,t)}static fromJsonString(e,t){return new Se().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Se,e,t)}}Se.runtime=l;Se.typeName="livekit.SessionDescription";Se.fields=l.util.newFieldList(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]);class Lt extends _{constructor(e){super(),this.participants=[],l.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 l.util.equals(Lt,e,t)}}Lt.runtime=l;Lt.typeName="livekit.ParticipantUpdate";Lt.fields=l.util.newFieldList(()=>[{no:1,name:"participants",kind:"message",T:De,repeated:!0}]);class Je extends _{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],l.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 l.util.equals(Je,e,t)}}Je.runtime=l;Je.typeName="livekit.UpdateSubscription";Je.fields=l.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:it,repeated:!0}]);class at extends _{constructor(e){super(),this.trackSids=[],this.disabled=!1,this.quality=oe.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,l.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 l.util.equals(at,e,t)}}at.runtime=l;at.typeName="livekit.UpdateTrackSettings";at.fields=l.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:l.getEnumType(oe)},{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 _{constructor(e){super(),this.canReconnect=!1,this.reason=Wt.UNKNOWN_REASON,l.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 l.util.equals(je,e,t)}}je.runtime=l;je.typeName="livekit.LeaveRequest";je.fields=l.util.newFieldList(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:l.getEnumType(Wt)}]);class ot extends _{constructor(e){super(),this.trackSid="",this.layers=[],l.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 l.util.equals(ot,e,t)}}ot.runtime=l;ot.typeName="livekit.UpdateVideoLayers";ot.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Te,repeated:!0}]);class ct extends _{constructor(e){super(),this.metadata="",this.name="",l.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 l.util.equals(ct,e,t)}}ct.runtime=l;ct.typeName="livekit.UpdateParticipantMetadata";ct.fields=l.util.newFieldList(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]);class ut extends _{constructor(e){super(),this.urls=[],this.username="",this.credential="",l.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 l.util.equals(ut,e,t)}}ut.runtime=l;ut.typeName="livekit.ICEServer";ut.fields=l.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 Nt extends _{constructor(e){super(),this.speakers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Nt().fromBinary(e,t)}static fromJson(e,t){return new Nt().fromJson(e,t)}static fromJsonString(e,t){return new Nt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Nt,e,t)}}Nt.runtime=l;Nt.typeName="livekit.SpeakersChanged";Nt.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:et,repeated:!0}]);class Dt extends _{constructor(e){super(),l.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 l.util.equals(Dt,e,t)}}Dt.runtime=l;Dt.typeName="livekit.RoomUpdate";Dt.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Pi}]);class Mt extends _{constructor(e){super(),this.participantSid="",this.quality=ti.POOR,this.score=0,l.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 l.util.equals(Mt,e,t)}}Mt.runtime=l;Mt.typeName="livekit.ConnectionQualityInfo";Mt.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:l.getEnumType(ti)},{no:3,name:"score",kind:"scalar",T:2}]);class Ut extends _{constructor(e){super(),this.updates=[],l.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 l.util.equals(Ut,e,t)}}Ut.runtime=l;Ut.typeName="livekit.ConnectionQualityUpdate";Ut.fields=l.util.newFieldList(()=>[{no:1,name:"updates",kind:"message",T:Mt,repeated:!0}]);class Ft extends _{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=oi.ACTIVE,l.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 l.util.equals(Ft,e,t)}}Ft.runtime=l;Ft.typeName="livekit.StreamStateInfo";Ft.fields=l.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:l.getEnumType(oi)}]);class Bt extends _{constructor(e){super(),this.streamStates=[],l.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 l.util.equals(Bt,e,t)}}Bt.runtime=l;Bt.typeName="livekit.StreamStateUpdate";Bt.fields=l.util.newFieldList(()=>[{no:1,name:"stream_states",kind:"message",T:Ft,repeated:!0}]);class ze extends _{constructor(e){super(),this.quality=oe.LOW,this.enabled=!1,l.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 l.util.equals(ze,e,t)}}ze.runtime=l;ze.typeName="livekit.SubscribedQuality";ze.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(oe)},{no:2,name:"enabled",kind:"scalar",T:8}]);class Jt extends _{constructor(e){super(),this.codec="",this.qualities=[],l.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 l.util.equals(Jt,e,t)}}Jt.runtime=l;Jt.typeName="livekit.SubscribedCodec";Jt.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ze,repeated:!0}]);class jt extends _{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],l.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 l.util.equals(jt,e,t)}}jt.runtime=l;jt.typeName="livekit.SubscribedQualityUpdate";jt.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ze,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Jt,repeated:!0}]);class dt extends _{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",l.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 l.util.equals(dt,e,t)}}dt.runtime=l;dt.typeName="livekit.TrackPermission";dt.fields=l.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 lt extends _{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],l.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 l.util.equals(lt,e,t)}}lt.runtime=l;lt.typeName="livekit.SubscriptionPermission";lt.fields=l.util.newFieldList(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:dt,repeated:!0}]);class Vt extends _{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,l.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 l.util.equals(Vt,e,t)}}Vt.runtime=l;Vt.typeName="livekit.SubscriptionPermissionUpdate";Vt.fields=l.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 ht extends _{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],l.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 l.util.equals(ht,e,t)}}ht.runtime=l;ht.typeName="livekit.SyncState";ht.fields=l.util.newFieldList(()=>[{no:1,name:"answer",kind:"message",T:Se},{no:2,name:"subscription",kind:"message",T:Je},{no:3,name:"publish_tracks",kind:"message",T:Ge,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ft,repeated:!0},{no:5,name:"offer",kind:"message",T:Se}]);class ft extends _{constructor(e){super(),this.label="",this.id=0,this.target=Re.PUBLISHER,l.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 l.util.equals(ft,e,t)}}ft.runtime=l;ft.typeName="livekit.DataChannelInfo";ft.fields=l.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:l.getEnumType(Re)}]);class ye extends _{constructor(e){super(),this.scenario={case:void 0},l.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 l.util.equals(ye,e,t)}}ye.runtime=l;ye.typeName="livekit.SimulateScenario";ye.fields=l.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:l.getEnumType(_n),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"}]);class pt extends _{constructor(e){super(),this.timestamp=V.zero,this.rtt=V.zero,l.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 l.util.equals(pt,e,t)}}pt.runtime=l;pt.typeName="livekit.Ping";pt.fields=l.util.newFieldList(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]);class $t extends _{constructor(e){super(),this.lastPingTimestamp=V.zero,this.timestamp=V.zero,l.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 l.util.equals($t,e,t)}}$t.runtime=l;$t.typeName="livekit.Pong";$t.fields=l.util.newFieldList(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]);class Zt extends _{constructor(e){super(),this.regions=[],l.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 l.util.equals(Zt,e,t)}}Zt.runtime=l;Zt.typeName="livekit.RegionSettings";Zt.fields=l.util.newFieldList(()=>[{no:1,name:"regions",kind:"message",T:qt,repeated:!0}]);class qt extends _{constructor(e){super(),this.region="",this.url="",this.distance=V.zero,l.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 l.util.equals(qt,e,t)}}qt.runtime=l;qt.typeName="livekit.RegionInfo";qt.fields=l.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 Ht extends _{constructor(e){super(),this.trackSid="",this.err=Zi.SE_UNKNOWN,l.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 l.util.equals(Ht,e,t)}}Ht.runtime=l;Ht.typeName="livekit.SubscriptionResponse";Ht.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:l.getEnumType(Zi)}]);class Ri extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ie extends Ri{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class Ls extends Ri{constructor(e){super(21,e??"device is unsupported")}}class Qe extends Ri{constructor(e){super(20,e??"track is invalid")}}class hd extends Ri{constructor(e){super(10,e??"unsupported server")}}class pe extends Ri{constructor(e){super(12,e??"unexpected connection state")}}class ks extends Ri{constructor(e){super(13,e??"unable to negotiate")}}var In;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(In||(In={}));(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})(In||(In={}));class ve{}ve.setTimeout=function(){return setTimeout(...arguments)};ve.setInterval=function(){return setInterval(...arguments)};ve.clearTimeout=function(){return clearTimeout(...arguments)};ve.clearInterval=function(){return clearInterval(...arguments)};const fd=/version\/(\d+(\.?_?\d+)+)/i;let Wn;function _i(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(Wn===void 0||e){const n=pd.find(s=>{let{test:r}=s;return r.test(t)});Wn=n==null?void 0:n.describe(t)}return Wn}const pd=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Gn(/(?: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:Gn(/(?: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:Gn(fd,i),os:i.includes("mobile/")?"iOS":"macOS"}}}];function Gn(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 md="1.13.4";const gd=md,vd=9;class Z{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 yd=["vp8","h264"],eo=["vp8","h264","vp9","av1"];function bd(i){return!!yd.find(e=>e===i)}function lr(i,e){return(i==null?void 0:i.toLowerCase().replace(/audio\/|video\//y,""))===(e==null?void 0:e.toLowerCase().replace(/audio\/|video\//y,""))}var xn;(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}})(xn||(xn={}));const en={h90:new Z(160,90,9e4,20),h180:new Z(320,180,16e4,20),h216:new Z(384,216,18e4,20),h360:new Z(640,360,45e4,20),h540:new Z(960,540,8e5,25),h720:new Z(1280,720,17e5,30),h1080:new Z(1920,1080,3e6,30),h1440:new Z(2560,1440,5e6,30),h2160:new Z(3840,2160,8e6,30)},Ts={h120:new Z(160,120,7e4,20),h180:new Z(240,180,125e3,20),h240:new Z(320,240,14e4,20),h360:new Z(480,360,33e4,20),h480:new Z(640,480,5e5,20),h540:new Z(720,540,6e5,25),h720:new Z(960,720,13e5,30),h1080:new Z(1440,1080,23e5,30),h1440:new Z(1920,1440,38e5,30)},Ns={h360fps3:new Z(640,360,2e5,3,"medium"),h720fps5:new Z(1280,720,4e5,5,"medium"),h720fps15:new Z(1280,720,15e5,15,"medium"),h720fps30:new Z(1280,720,2e6,30,"medium"),h1080fps15:new Z(1920,1080,25e5,15,"medium"),h1080fps30:new Z(1920,1080,4e6,30,"medium")};var P;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.StateChanged="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.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 A;(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.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded"})(A||(A={}));var O;(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"})(O||(O={}));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.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed"})(R||(R={}));const kd=5e3,Di=[];class C extends mt.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kd):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}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"&&(Di.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Di.splice(Di.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),yi(this.mediaStreamTrack,e);const n=e.srcObject.getTracks();return n.some(s=>s.kind==="audio")&&e.play().then(()=>{this.emit(R.AudioPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(R.AudioPlaybackFailed,s):p.warn("could not playback audio",s),e&&n.some(r=>r.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){Si(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=>{Si(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)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Di.forEach(n=>{n.parentElement||(t=!1)}),t&&Di.push(e)}}handleAppVisibilityChanged(){return g(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){_e()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_e()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function yi(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)),e.autoplay=!0,e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Fn()||tn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Si(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 ge.AUDIO;case e.Video:return ge.VIDEO;default:return ge.DATA}}i.kindToProto=s;function r(u){switch(u){case ge.AUDIO:return e.Audio;case ge.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(u){switch(u){case t.Camera:return se.CAMERA;case t.Microphone:return se.MICROPHONE;case t.ScreenShare:return se.SCREEN_SHARE;case t.ScreenShareAudio:return se.SCREEN_SHARE_AUDIO;default:return se.UNKNOWN}}i.sourceToProto=a;function o(u){switch(u){case se.CAMERA:return t.Camera;case se.MICROPHONE:return t.Microphone;case se.SCREEN_SHARE:return t.ScreenShare;case se.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(u){switch(u){case oi.ACTIVE:return n.Active;case oi.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(C||(C={}));function to(i,e,t){const n=Object.assign({},i);return n.audio===!0&&(n.audio={}),n.video===!0&&(n.video={}),n.audio&&Ss(n.audio,e),n.video&&Ss(n.video,t),n}function Ss(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Un(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":Ss(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 Td(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return g(this,void 0,void 0,function*(){const t=io();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 si(e),n.getByteTimeDomainData(r);const o=r.some(c=>c!==128&&c!==0);return t.close(),!o}return!1})}function io(){const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(i)return new i({latencyHint:"interactive"})}function Sd(i){return i===C.Source.Microphone?"audioinput":i===C.Source.Camera?"videoinput":void 0}function Cd(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&(n=typeof n=="boolean"?{}:n,Fn()?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}}const wd="|",hr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ed(i){const e=i.split(wd);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function si(i){return g(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,i))})}function fr(){return"addTransceiver"in RTCPeerConnection.prototype}function pr(){return"addTrack"in RTCPeerConnection.prototype}function Pd(){if(!("getCapabilities"in RTCRtpSender))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 Rd(){if(!("getCapabilities"in RTCRtpSender))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 Wi(i){return i==="av1"||i==="vp9"}function Cs(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}const _d={Chrome:"100",Safari:"15",Firefox:"100"};function Id(i){if(!_e()||!("setCodecPreferences"in i))return!1;const e=_i();if(!(e!=null&&e.name)||!e.version)return!1;const t=_d[e.name];return t?ao(e.version,t)>=0:!1}function tn(){var i;return((i=_i())===null||i===void 0?void 0:i.name)==="Firefox"}function xd(){var i;return((i=_i())===null||i===void 0?void 0:i.name)==="Chrome"}function Fn(){var i;return((i=_i())===null||i===void 0?void 0:i.name)==="Safari"}function no(){return _e()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _e(){return typeof document<"u"}function ci(){return navigator.product=="ReactNative"}function ws(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function so(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ro(){if(!ci())return;let i=so();if(i)return i.platform}function mr(){if(_e())return window.devicePixelRatio;if(ci()){let i=so();if(i)return i.devicePixelRatio}return 1}function ao(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(n[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function Ad(i){for(const e of i)e.target.handleResize(e)}function Od(i){for(const e of i)e.target.handleVisibilityChanged(e)}let zn=null;const gr=()=>(zn||(zn=new ResizeObserver(Ad)),zn);let Kn=null;const vr=()=>(Kn||(Kn=new IntersectionObserver(Od,{root:null,rootMargin:"0px"})),Kn);function Ld(){var i;const e=new Rt({sdk:Ei.JS,protocol:vd,version:gd});return ci()&&(e.os=(i=ro())!==null&&i!==void 0?i:""),e}function yr(){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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Mi;function Yn(){if(!Mi){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(),[Mi]=n.stream.getAudioTracks(),!Mi)throw Error("Could not get empty media stream audio track");Mi.enabled=!1}return Mi.clone()}class oo{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,s)=>g(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 Gt{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 Nd(i){return eo.includes(i)}function ri(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 Dd(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function br(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}var Gi;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Gi||(Gi={}));class Md{constructor(){this.pendingTasks=new Map,this.taskMutex=new Gt,this.nextTaskIndex=0}run(e){return g(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Gi.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Gi.RUNNING,yield e()}finally{t.status=Gi.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return g(this,void 0,void 0,function*(){return this.run(()=>g(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}const Ud=["syncState","trickle","offer","answer","simulate","leave"];function Fd(i){const e=Ud.indexOf(i.case)>=0;return p.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}class Ds{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.rtt=0,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.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Md,this.queuedRequests=[],this.closingLock=new Gt}join(e,t,n,s){return g(this,void 0,void 0,function*(){return this.isConnected=!1,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return g(this,void 0,void 0,function*(){if(!this.options){p.warn("attempted to reconnect without signal options being set, ignoring");return}return this.isReconnecting=!0,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=Dd(e),e=e.replace(/\/$/,""),e+="/rtc";const r=Ld(),a=Bd(t,r,n);return new Promise((o,c)=>g(this,void 0,void 0,function*(){const u=()=>g(this,void 0,void 0,function*(){this.close(),clearTimeout(d),c(new ie("room connection has been cancelled (signal)"))}),d=setTimeout(()=>{this.close(),c(new ie("room connection has timed out (signal)"))},n.websocketTimeout);s!=null&&s.aborted&&u(),s==null||s.addEventListener("abort",u),p.debug("connecting to ".concat(e+a)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(d)},this.ws.onerror=h=>g(this,void 0,void 0,function*(){if(!this.isConnected){clearTimeout(d);try{const f=yield fetch("http".concat(e.substring(2),"/validate").concat(a));if(f.status.toFixed(0).startsWith("4")){const m=yield f.text();c(new ie(m,0,f.status))}else c(new ie("Internal error",2,f.status))}catch{c(new ie("server was not reachable",1))}return}this.handleWSError(h)}),this.ws.onmessage=h=>g(this,void 0,void 0,function*(){var f,m,b,T;let w;if(typeof h.data=="string"){const I=JSON.parse(h.data);w=rt.fromJson(I)}else if(h.data instanceof ArrayBuffer)w=rt.fromBinary(new Uint8Array(h.data));else{p.error("could not decode websocket message: ".concat(typeof h.data));return}if(!this.isConnected){let I=!1;if(((f=w.message)===null||f===void 0?void 0:f.case)==="join"?(this.isConnected=!0,s==null||s.removeEventListener("abort",u),this.pingTimeoutDuration=w.message.value.pingTimeout,this.pingIntervalDuration=w.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(p.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),o(w.message.value)):n.reconnect?(this.isConnected=!0,s==null||s.removeEventListener("abort",u),this.startPingInterval(),((m=w.message)===null||m===void 0?void 0:m.case)==="reconnect"?o((b=w.message)===null||b===void 0?void 0:b.value):(o(),I=!0)):n.reconnect||c(new ie("did not receive join response, got ".concat((T=w.message)===null||T===void 0?void 0:T.case," instead"))),!I)return}this.signalLatency&&(yield si(this.signalLatency)),this.handleSignalResponse(w)}),this.ws.onclose=h=>{p.warn("websocket closed",{ev:h}),this.handleOnClose(h.reason)}}))}close(){return g(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const t=new Promise(n=>{this.ws?this.ws.onclose=()=>{n()}:n()});this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([t,si(250)])),this.ws=void 0}}finally{this.clearPingInterval(),e()}})}sendOffer(e){p.debug("sending offer",e),this.sendRequest({case:"offer",value:An(e)})}sendAnswer(e){return p.debug("sending answer"),this.sendRequest({case:"answer",value:An(e)})}sendIceCandidate(e,t){return p.trace("sending ice candidate",e),this.sendRequest({case:"trickle",value:new He({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new We({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new ct({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 ot({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new lt({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:V.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new pt({timestamp:V.parse(Date.now()),rtt:V.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new je({canReconnect:!1,reason:Wt.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return g(this,void 0,void 0,function*(){if(!t&&!Fd(e)&&this.isReconnecting){this.queuedRequests.push(()=>g(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield si(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){p.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case));return}const s=new It({message:e});try{this.useJSON?this.ws.send(s.toJsonString()):this.ws.send(s.toBinary())}catch(r){p.error("error sending signal message",{error:r})}})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){p.debug("received unsupported message");return}if(s.case==="answer"){const r=kr(s.value);this.onAnswer&&this.onAnswer(r)}else if(s.case==="offer"){const r=kr(s.value);this.onOffer&&this.onOffer(r)}else if(s.case==="trickle"){const r=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(r,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"?this.resetPingTimeout():s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout()):p.debug("unsupported message",s)}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return g(this,void 0,void 0,function*(){if(!this.isConnected)return;const t=this.onClose;yield this.close(),p.debug("websocket connection closed: ".concat(e)),t&&t(e)})}handleWSError(e){p.error("websocket error",e)}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){p.warn("ping timeout duration not set");return}this.pingTimeout=ve.setTimeout(()=>{p.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ve.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){p.warn("ping interval duration not set");return}p.debug("start ping interval"),this.pingInterval=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){p.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function kr(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 An(i){return new Se({sdp:i.sdp,type:i.type})}function Bd(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",ci()?"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.publishOnly!==void 0&&s.set("publish",t.publishOnly),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())}const Jd=10,hn="lk_e2ee",jd="LKFrameEncryptionKey",Vd={sharedKey:!1,ratchetSalt:jd,ratchetWindowSize:8,failureTolerance:Jd};var ii;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(ii||(ii={}));var Tr;(function(i){i.KeyRatcheted="keyRatcheted"})(Tr||(Tr={}));var ei;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(ei||(ei={}));var Sr;(function(i){i.Error="cryptorError"})(Sr||(Sr={}));function $d(){return qd()||Es()}function Es(){return typeof window.RTCRtpScriptTransform<"u"}function qd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Hd(i){const e=i.split("/")[1].toLowerCase();if(!eo.includes(e))throw Error("Video codec not supported: ".concat(e));return e}class Ul extends mt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{p.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Vd),e),this.on(ii.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(ii.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(ii.RatchetRequest,e,t)}}function Ms(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(s=t.callback)!=null&&s,c=t.maxWait,u=Date.now(),d=[];function h(){if(c!==void 0){var m=Date.now()-u;if(m+e>=c)return c-m}return e}var f=function(){var m=[].slice.call(arguments),b=this;return new Promise(function(T,w){var I=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,u=Date.now(),!a){var Q=i.apply(b,m);o&&o(Q),d.forEach(function(j){return(0,j.resolve)(Q)}),d=[]}},h()),I){var D=i.apply(b,m);return o&&o(D),T(D)}d.push({resolve:T,reject:w})})};return f.cancel=function(m){r!==void 0&&clearTimeout(r),d.forEach(function(b){return(0,b.reject)(m)}),d=[]},f}const Cr="default";class be{static getInstance(){return this.instance===void 0&&(this.instance=new be),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n;return g(this,void 0,void 0,function*(){if(((n=be.userMediaPromiseMap)===null||n===void 0?void 0:n.size)>0){p.debug("awaiting getUserMedia promise");try{e?yield be.userMediaPromiseMap.get(e):yield Promise.all(be.userMediaPromiseMap.values())}catch{p.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&!(Fn()&&this.hasDeviceInUse(e))&&(s.length===0||s.some(a=>{const o=a.label==="",c=e?a.kind===e:!0;return o&&c}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},o=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),o.getTracks().forEach(c=>{c.stop()})}return e&&(s=s.filter(r=>r.kind===e)),s})}normalizeDeviceId(e,t,n){return g(this,void 0,void 0,function*(){if(t!==Cr)return t;const r=(yield this.getDevices(e)).find(a=>a.groupId===n&&a.deviceId!==Cr);return r==null?void 0:r.deviceId})}hasDeviceInUse(e){return e?be.userMediaPromiseMap.has(e):be.userMediaPromiseMap.size>0}}be.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];be.userMediaPromiseMap=new Map;const Wd=1e3;class nn extends C{get constraints(){return this._constraints}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;super(e,t),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>p.debug("track mute bounce got cancelled by an unmute event")),this.debouncedTrackMuteHandler=Ms(()=>g(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>g(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 Gt,this.pauseUpstreamLock=new Gt,this.processorLock=new Gt,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 g(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Si(this._mediaStreamTrack,s)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop()),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&&this.processorElement){if(p.debug("restarting processor"),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");yi(e,this.processorElement),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(yield this.sender.replaceTrack(n??e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{yi(n??e,s)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Wd;return g(this,void 0,void 0,function*(){if(this.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t<e;){const n=this.dimensions;if(n)return n;yield si(50)}throw new Qe("unable to get track dimensions after timeout")})}getDeviceId(){return g(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 be.getInstance().normalizeDeviceId(n,e,t)})}mute(){return g(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return g(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 g(this,void 0,void 0,function*(){if(!this.sender)throw new Qe("unable to replace an unpublished track");return p.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this})}restart(e){return g(this,void 0,void 0,function*(){e||(e=this._constraints),p.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===C.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach(r=>{Si(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),p.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(R.Restarted,this),this})}setTrackMuted(e){p.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),!(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 g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),no()&&(p.debug("visibility changed, is in Background: ".concat(this.isInBackground)),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(p.debug("track needs to be reacquired, restarting ".concat(this.source)),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 g(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){p.warn("unable to pause upstream for an unpublished track");return}this._isUpstreamPaused=!0,this.emit(R.UpstreamPaused,this);const t=_i();if((t==null?void 0:t.name)==="Safari"&&ao(t.version,"12.0")<0)throw new Ls("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return g(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){p.warn("unable to resume upstream for an unpublished track");return}this._isUpstreamPaused=!1,this.emit(R.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return g(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 g(this,void 0,void 0,function*(){const r=yield this.processorLock.lock();try{if(p.debug("setting up processor"),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),this.processorElement.muted=!0,yi(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch(o=>p.error("failed to play processor element",{error:o}));const a={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(a),this.processor=e,this.processor.processedTrack){for(const o of this.attachedElements)o!==this.processorElement&&t&&(Si(this._mediaStreamTrack,o),yi(this.processor.processedTrack,o));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 g(this,void 0,void 0,function*(){this.processor&&(p.debug("stopping processor"),(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 Gd extends mt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:a}=t.data;switch(r){case"error":p.error(a.error.message),this.emit(ei.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(ei.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(ei.ParticipantEncryptionStatusChanged,a.enabled,o)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"ratchetKey":this.keyProvider.emit(ii.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{p.error("e2ee worker encountered an error:",{error:t.error}),this.emit(ei.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!$d())throw new Ls("tried to setup end-to-end encryption on an unsupported browser");if(p.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&&(p.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){p.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?p.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(O.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(P.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==ke.NONE,s.identity)),e.on(P.ConnectionStateChanged,n=>{n===Y.Connected&&e.participants.forEach(s=>{s.tracks.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==ke.NONE,s.identity)})})}).on(P.TrackUnsubscribed,(n,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).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(A.LocalTrackPublished,n=>g(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(ii.SetKey,n=>this.postKey(n)).on(ii.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 a={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(a)}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"?Hd(n.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof nn)||!t){t||p.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return g(this,void 0,void 0,function*(){if(this.worker){if(Es()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(hn in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(o,[a,r])}e[hn]=!0}})}handleSender(e,t,n){var s;if(!(hn 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(Es()){p.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{p.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[hn]=!0}}}var co={},uo={exports:{}},wr=uo.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(wr).forEach(function(i){var e=wr[i];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var lo=uo.exports;(function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,u,d){if(d&&!u)c[d]=e(o[1]);else for(var h=0;h<u.length;h+=1)o[h+1]!=null&&(c[u[h]]=e(o[h+1]))},n=function(o,c,u){var d=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:d&&!c[o.name]&&(c[o.name]={});var h=o.push?{}:d?c[o.name]:c;t(u.match(o.reg),h,o.names,o.name),o.push&&c[o.push].push(h)},s=lo,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},u=[],d=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var f=h[0],m=h.slice(2);f==="m"&&(u.push({rtp:[],fmtp:[]}),d=u[u.length-1]);for(var b=0;b<(s[f]||[]).length;b+=1){var T=s[f][b];if(T.reg.test(m))return n(T,d,m)}}),c.media=u,c};var a=function(o,c){var u=c.split(/=(.+)/,2);return u.length===2?o[u[0]]=e(u[1]):u.length===1&&c.length>1&&(o[u[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var c=[],u=o.split(" ").map(e),d=0;d<u.length;d+=3)c.push({component:u[d],ip:u[d+1],port:u[d+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(u){var d,h=!1;return u[0]!=="~"?d=e(u):(d=e(u.substring(1,u.length)),h=!0),{scid:d,paused:h}})})}})(co);var Xn=lo,zd=/%[sdv%]/g,Kd=function(i){var e=1,t=arguments,n=t.length;return i.replace(zd,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""}})},Ui=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 a=e.names[r];e.name?s.push(t[e.name][a]):s.push(t[e.names[r]])}else s.push(t[e.name]);return Kd.apply(null,s)},Yd=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Xd=["i","c","b","a"],Qd=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||Yd,n=e.innerOrder||Xd,s=[];return t.forEach(function(r){Xn[r].forEach(function(a){a.name in i&&i[a.name]!=null?s.push(Ui(r,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(o){s.push(Ui(r,a,o))})})}),i.media.forEach(function(r){s.push(Ui("m",Xn.m[0],r)),n.forEach(function(a){Xn[a].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Ui(a,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(c){s.push(Ui(a,o,c))})})})}),s.join(`\r
49
+ `);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 En(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(a=>t.apply(this,[a]))})}var ld=Object.freeze({__proto__:null,removeExtmapAllowMixed:ks,shimAddIceCandidateNullOrEmpty:wn,shimConnectionState:bs,shimMaxMessageSize:Sn,shimParameterlessSetLocalDescription:En,shimRTCIceCandidate:Tn,shimRTCIceCandidateRelayProtocol:ys,shimSendThrowTypeError:Cn});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=wa,n=od(i),s={browserDetails:n,commonShim:ld,extractVersion:kn,disableLog:rd,disableWarnings:ad,sdp:dd};switch(n.browser){case"chrome":if(!dr||!gs||!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=dr,wn(i,n),En(i),Pa(i,n),Ra(i),gs(i,n),_a(i),Na(i,n),Ia(i),Aa(i),Oa(i),xa(i,n),Tn(i),ys(i),bs(i),Sn(i,n),Cn(i),ks(i,n);break;case"firefox":if(!lr||!vs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=lr,wn(i,n),En(i),Da(i,n),vs(i,n),Ma(i),Ba(i),Ua(i),Fa(i),Ja(i),ja(i),Va(i),$a(i),qa(i),Tn(i),bs(i),Sn(i,n),Cn(i);break;case"safari":if(!hr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=hr,wn(i,n),En(i),Ya(i),Qa(i),Ga(i),Ha(i),Wa(i),Xa(i),za(i),Za(i),Tn(i),ys(i),Sn(i,n),Cn(i),ks(i,n);break;default:t("Unsupported browser!");break}return s}hd({window:typeof window>"u"?void 0:window});var Re;(function(i){i[i.PUBLISHER=0]="PUBLISHER",i[i.SUBSCRIBER=1]="SUBSCRIBER"})(Re||(Re={}));l.util.setEnumType(Re,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]);var oi;(function(i){i[i.ACTIVE=0]="ACTIVE",i[i.PAUSED=1]="PAUSED"})(oi||(oi={}));l.util.setEnumType(oi,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);var _n;(function(i){i[i.UDP=0]="UDP",i[i.TCP=1]="TCP",i[i.TLS=2]="TLS"})(_n||(_n={}));l.util.setEnumType(_n,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class _t extends I{constructor(e){super(),this.message={case:void 0},l.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 l.util.equals(_t,e,t)}}_t.runtime=l;_t.typeName="livekit.SignalRequest";_t.fields=l.util.newFieldList(()=>[{no:1,name:"offer",kind:"message",T:Se,oneof:"message"},{no:2,name:"answer",kind:"message",T:Se,oneof:"message"},{no:3,name:"trickle",kind:"message",T:He,oneof:"message"},{no:4,name:"add_track",kind:"message",T:qe,oneof:"message"},{no:5,name:"mute",kind:"message",T:We,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Je,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:at,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ot,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:lt,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ht,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:ct,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:pt,oneof:"message"}]);class rt extends I{constructor(e){super(),this.message={case:void 0},l.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 l.util.equals(rt,e,t)}}rt.runtime=l;rt.typeName="livekit.SignalResponse";rt.fields=l.util.newFieldList(()=>[{no:1,name:"join",kind:"message",T:It,oneof:"message"},{no:2,name:"answer",kind:"message",T:Se,oneof:"message"},{no:3,name:"offer",kind:"message",T:Se,oneof:"message"},{no:4,name:"trickle",kind:"message",T:He,oneof:"message"},{no:5,name:"update",kind:"message",T:Lt,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ge,oneof:"message"},{no:8,name:"leave",kind:"message",T:je,oneof:"message"},{no:9,name:"mute",kind:"message",T:We,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Nt,oneof:"message"},{no:11,name:"room_update",kind:"message",T:xt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Mt,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ft,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Jt,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:jt,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ot,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:At,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Vt,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qt,oneof:"message"}]);class Be extends I{constructor(e){super(),this.codec="",this.cid="",this.enableSimulcastLayers=!1,l.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 l.util.equals(Be,e,t)}}Be.runtime=l;Be.typeName="livekit.SimulcastCodec";Be.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:3,name:"enable_simulcast_layers",kind:"scalar",T:8}]);class qe extends I{constructor(e){super(),this.cid="",this.name="",this.type=ge.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=re.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=ke.NONE,this.stream="",l.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 l.util.equals(qe,e,t)}}qe.runtime=l;qe.typeName="livekit.AddTrackRequest";qe.fields=l.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:l.getEnumType(ge)},{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:l.getEnumType(re)},{no:9,name:"layers",kind:"message",T:Te,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Be,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:l.getEnumType(ke)},{no:15,name:"stream",kind:"scalar",T:9}]);class He extends I{constructor(e){super(),this.candidateInit="",this.target=Re.PUBLISHER,l.util.initPartial(e,this)}static fromBinary(e,t){return new He().fromBinary(e,t)}static fromJson(e,t){return new He().fromJson(e,t)}static fromJsonString(e,t){return new He().fromJsonString(e,t)}static equals(e,t){return l.util.equals(He,e,t)}}He.runtime=l;He.typeName="livekit.TrickleRequest";He.fields=l.util.newFieldList(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:l.getEnumType(Re)}]);class We extends I{constructor(e){super(),this.sid="",this.muted=!1,l.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 l.util.equals(We,e,t)}}We.runtime=l;We.typeName="livekit.MuteTrackRequest";We.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]);class It extends I{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),l.util.initPartial(e,this)}static fromBinary(e,t){return new It().fromBinary(e,t)}static fromJson(e,t){return new It().fromJson(e,t)}static fromJsonString(e,t){return new It().fromJsonString(e,t)}static equals(e,t){return l.util.equals(It,e,t)}}It.runtime=l;It.typeName="livekit.JoinResponse";It.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Ei},{no:2,name:"participant",kind:"message",T:Me},{no:3,name:"other_participants",kind:"message",T:Me,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ut,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:nt},{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:Et},{no:13,name:"sif_trailer",kind:"scalar",T:12}]);class At extends I{constructor(e){super(),this.iceServers=[],l.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 l.util.equals(At,e,t)}}At.runtime=l;At.typeName="livekit.ReconnectResponse";At.fields=l.util.newFieldList(()=>[{no:1,name:"ice_servers",kind:"message",T:ut,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:nt}]);class Ge extends I{constructor(e){super(),this.cid="",l.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 l.util.equals(Ge,e,t)}}Ge.runtime=l;Ge.typeName="livekit.TrackPublishedResponse";Ge.fields=l.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Pe}]);class Ot extends I{constructor(e){super(),this.trackSid="",l.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 l.util.equals(Ot,e,t)}}Ot.runtime=l;Ot.typeName="livekit.TrackUnpublishedResponse";Ot.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);class Se extends I{constructor(e){super(),this.type="",this.sdp="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Se().fromBinary(e,t)}static fromJson(e,t){return new Se().fromJson(e,t)}static fromJsonString(e,t){return new Se().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Se,e,t)}}Se.runtime=l;Se.typeName="livekit.SessionDescription";Se.fields=l.util.newFieldList(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]);class Lt extends I{constructor(e){super(),this.participants=[],l.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 l.util.equals(Lt,e,t)}}Lt.runtime=l;Lt.typeName="livekit.ParticipantUpdate";Lt.fields=l.util.newFieldList(()=>[{no:1,name:"participants",kind:"message",T:Me,repeated:!0}]);class Je extends I{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],l.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 l.util.equals(Je,e,t)}}Je.runtime=l;Je.typeName="livekit.UpdateSubscription";Je.fields=l.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:it,repeated:!0}]);class at extends I{constructor(e){super(),this.trackSids=[],this.disabled=!1,this.quality=ue.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,l.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 l.util.equals(at,e,t)}}at.runtime=l;at.typeName="livekit.UpdateTrackSettings";at.fields=l.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:l.getEnumType(ue)},{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 I{constructor(e){super(),this.canReconnect=!1,this.reason=Ht.UNKNOWN_REASON,l.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 l.util.equals(je,e,t)}}je.runtime=l;je.typeName="livekit.LeaveRequest";je.fields=l.util.newFieldList(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:l.getEnumType(Ht)}]);class ot extends I{constructor(e){super(),this.trackSid="",this.layers=[],l.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 l.util.equals(ot,e,t)}}ot.runtime=l;ot.typeName="livekit.UpdateVideoLayers";ot.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Te,repeated:!0}]);class ct extends I{constructor(e){super(),this.metadata="",this.name="",l.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 l.util.equals(ct,e,t)}}ct.runtime=l;ct.typeName="livekit.UpdateParticipantMetadata";ct.fields=l.util.newFieldList(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]);class ut extends I{constructor(e){super(),this.urls=[],this.username="",this.credential="",l.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 l.util.equals(ut,e,t)}}ut.runtime=l;ut.typeName="livekit.ICEServer";ut.fields=l.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 Nt extends I{constructor(e){super(),this.speakers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Nt().fromBinary(e,t)}static fromJson(e,t){return new Nt().fromJson(e,t)}static fromJsonString(e,t){return new Nt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Nt,e,t)}}Nt.runtime=l;Nt.typeName="livekit.SpeakersChanged";Nt.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:et,repeated:!0}]);class xt extends I{constructor(e){super(),l.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 l.util.equals(xt,e,t)}}xt.runtime=l;xt.typeName="livekit.RoomUpdate";xt.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Ei}]);class Dt extends I{constructor(e){super(),this.participantSid="",this.quality=ei.POOR,this.score=0,l.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 l.util.equals(Dt,e,t)}}Dt.runtime=l;Dt.typeName="livekit.ConnectionQualityInfo";Dt.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:l.getEnumType(ei)},{no:3,name:"score",kind:"scalar",T:2}]);class Mt extends I{constructor(e){super(),this.updates=[],l.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 l.util.equals(Mt,e,t)}}Mt.runtime=l;Mt.typeName="livekit.ConnectionQualityUpdate";Mt.fields=l.util.newFieldList(()=>[{no:1,name:"updates",kind:"message",T:Dt,repeated:!0}]);class Ut extends I{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=oi.ACTIVE,l.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 l.util.equals(Ut,e,t)}}Ut.runtime=l;Ut.typeName="livekit.StreamStateInfo";Ut.fields=l.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:l.getEnumType(oi)}]);class Ft extends I{constructor(e){super(),this.streamStates=[],l.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 l.util.equals(Ft,e,t)}}Ft.runtime=l;Ft.typeName="livekit.StreamStateUpdate";Ft.fields=l.util.newFieldList(()=>[{no:1,name:"stream_states",kind:"message",T:Ut,repeated:!0}]);class ze extends I{constructor(e){super(),this.quality=ue.LOW,this.enabled=!1,l.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 l.util.equals(ze,e,t)}}ze.runtime=l;ze.typeName="livekit.SubscribedQuality";ze.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(ue)},{no:2,name:"enabled",kind:"scalar",T:8}]);class Bt extends I{constructor(e){super(),this.codec="",this.qualities=[],l.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 l.util.equals(Bt,e,t)}}Bt.runtime=l;Bt.typeName="livekit.SubscribedCodec";Bt.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ze,repeated:!0}]);class Jt extends I{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],l.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 l.util.equals(Jt,e,t)}}Jt.runtime=l;Jt.typeName="livekit.SubscribedQualityUpdate";Jt.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ze,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Bt,repeated:!0}]);class dt extends I{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",l.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 l.util.equals(dt,e,t)}}dt.runtime=l;dt.typeName="livekit.TrackPermission";dt.fields=l.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 lt extends I{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],l.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 l.util.equals(lt,e,t)}}lt.runtime=l;lt.typeName="livekit.SubscriptionPermission";lt.fields=l.util.newFieldList(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:dt,repeated:!0}]);class jt extends I{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,l.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 l.util.equals(jt,e,t)}}jt.runtime=l;jt.typeName="livekit.SubscriptionPermissionUpdate";jt.fields=l.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 ht extends I{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],l.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 l.util.equals(ht,e,t)}}ht.runtime=l;ht.typeName="livekit.SyncState";ht.fields=l.util.newFieldList(()=>[{no:1,name:"answer",kind:"message",T:Se},{no:2,name:"subscription",kind:"message",T:Je},{no:3,name:"publish_tracks",kind:"message",T:Ge,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ft,repeated:!0},{no:5,name:"offer",kind:"message",T:Se}]);class ft extends I{constructor(e){super(),this.label="",this.id=0,this.target=Re.PUBLISHER,l.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 l.util.equals(ft,e,t)}}ft.runtime=l;ft.typeName="livekit.DataChannelInfo";ft.fields=l.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:l.getEnumType(Re)}]);class ye extends I{constructor(e){super(),this.scenario={case:void 0},l.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 l.util.equals(ye,e,t)}}ye.runtime=l;ye.typeName="livekit.SimulateScenario";ye.fields=l.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:l.getEnumType(_n),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"}]);class pt extends I{constructor(e){super(),this.timestamp=V.zero,this.rtt=V.zero,l.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 l.util.equals(pt,e,t)}}pt.runtime=l;pt.typeName="livekit.Ping";pt.fields=l.util.newFieldList(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]);class Vt extends I{constructor(e){super(),this.lastPingTimestamp=V.zero,this.timestamp=V.zero,l.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 l.util.equals(Vt,e,t)}}Vt.runtime=l;Vt.typeName="livekit.Pong";Vt.fields=l.util.newFieldList(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]);class Qt extends I{constructor(e){super(),this.regions=[],l.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 l.util.equals(Qt,e,t)}}Qt.runtime=l;Qt.typeName="livekit.RegionSettings";Qt.fields=l.util.newFieldList(()=>[{no:1,name:"regions",kind:"message",T:$t,repeated:!0}]);class $t extends I{constructor(e){super(),this.region="",this.url="",this.distance=V.zero,l.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 l.util.equals($t,e,t)}}$t.runtime=l;$t.typeName="livekit.RegionInfo";$t.fields=l.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 qt extends I{constructor(e){super(),this.trackSid="",this.err=Yi.SE_UNKNOWN,l.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 l.util.equals(qt,e,t)}}qt.runtime=l;qt.typeName="livekit.SubscriptionResponse";qt.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:l.getEnumType(Yi)}]);class Pi extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class ne extends Pi{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class xs extends Pi{constructor(e){super(21,e??"device is unsupported")}}class Qe extends Pi{constructor(e){super(20,e??"track is invalid")}}class fd extends Pi{constructor(e){super(10,e??"unsupported server")}}class pe extends Pi{constructor(e){super(12,e??"unexpected connection state")}}class Ts extends Pi{constructor(e){super(13,e??"unable to negotiate")}}var In;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(In||(In={}));(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})(In||(In={}));class ve{}ve.setTimeout=function(){return setTimeout(...arguments)};ve.setInterval=function(){return setInterval(...arguments)};ve.clearTimeout=function(){return clearTimeout(...arguments)};ve.clearInterval=function(){return clearInterval(...arguments)};const pd=/version\/(\d+(\.?_?\d+)+)/i;let Gn;function Ri(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(Gn===void 0||e){const n=md.find(s=>{let{test:r}=s;return r.test(t)});Gn=n==null?void 0:n.describe(t)}return Gn}const md=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:zn(/(?: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:zn(/(?: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:zn(pd,i),os:i.includes("mobile/")?"iOS":"macOS"}}}];function zn(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 gd="1.13.4";const vd=gd,yd=9;class ee{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 bd=["vp8","h264"],io=["vp8","h264","vp9","av1"];function kd(i){return!!bd.find(e=>e===i)}function fr(i,e){return(i==null?void 0:i.toLowerCase().replace(/audio\/|video\//y,""))===(e==null?void 0:e.toLowerCase().replace(/audio\/|video\//y,""))}var An;(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}})(An||(An={}));const Xi={h90:new ee(160,90,9e4,20),h180:new ee(320,180,16e4,20),h216:new ee(384,216,18e4,20),h360:new ee(640,360,45e4,20),h540:new ee(960,540,8e5,25),h720:new ee(1280,720,17e5,30),h1080:new ee(1920,1080,3e6,30),h1440:new ee(2560,1440,5e6,30),h2160:new ee(3840,2160,8e6,30)},Ss={h120:new ee(160,120,7e4,20),h180:new ee(240,180,125e3,20),h240:new ee(320,240,14e4,20),h360:new ee(480,360,33e4,20),h480:new ee(640,480,5e5,20),h540:new ee(720,540,6e5,25),h720:new ee(960,720,13e5,30),h1080:new ee(1440,1080,23e5,30),h1440:new ee(1920,1440,38e5,30)},Ds={h360fps3:new ee(640,360,2e5,3,"medium"),h720fps5:new ee(1280,720,4e5,5,"medium"),h720fps15:new ee(1280,720,15e5,15,"medium"),h720fps30:new ee(1280,720,2e6,30,"medium"),h1080fps15:new ee(1920,1080,25e5,15,"medium"),h1080fps30:new ee(1920,1080,4e6,30,"medium")};var P;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.StateChanged="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.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 L;(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.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded"})(L||(L={}));var N;(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"})(N||(N={}));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.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed"})(R||(R={}));const Td=5e3,Li=[];class C extends mt.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Td):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}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"&&(Li.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Li.splice(Li.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),vi(this.mediaStreamTrack,e);const n=e.srcObject.getTracks();return n.some(s=>s.kind==="audio")&&e.play().then(()=>{this.emit(R.AudioPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(R.AudioPlaybackFailed,s):m.warn("could not playback audio",s),e&&n.some(r=>r.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){Ti(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=>{Ti(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)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Li.forEach(n=>{n.parentElement||(t=!1)}),t&&Li.push(e)}}handleAppVisibilityChanged(){return g(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){_e()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_e()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function vi(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)),e.autoplay=!0,e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Fn()||Qi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ti(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 ge.AUDIO;case e.Video:return ge.VIDEO;default:return ge.DATA}}i.kindToProto=s;function r(u){switch(u){case ge.AUDIO:return e.Audio;case ge.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(u){switch(u){case t.Camera:return re.CAMERA;case t.Microphone:return re.MICROPHONE;case t.ScreenShare:return re.SCREEN_SHARE;case t.ScreenShareAudio:return re.SCREEN_SHARE_AUDIO;default:return re.UNKNOWN}}i.sourceToProto=a;function o(u){switch(u){case re.CAMERA:return t.Camera;case re.MICROPHONE:return t.Microphone;case re.SCREEN_SHARE:return t.ScreenShare;case re.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(u){switch(u){case oi.ACTIVE:return n.Active;case oi.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(C||(C={}));function no(i,e,t){const n=Object.assign({},i);return n.audio===!0&&(n.audio={}),n.video===!0&&(n.video={}),n.audio&&Cs(n.audio,e),n.video&&Cs(n.video,t),n}function Cs(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Un(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":Cs(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 Sd(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return g(this,void 0,void 0,function*(){const t=so();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 si(e),n.getByteTimeDomainData(r);const o=r.some(c=>c!==128&&c!==0);return t.close(),!o}return!1})}function so(){const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(i)return new i({latencyHint:"interactive"})}function Cd(i){return i===C.Source.Microphone?"audioinput":i===C.Source.Camera?"videoinput":void 0}function wd(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&(n=typeof n=="boolean"?{}:n,Fn()?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}}const Ed="|",pr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Pd(i){const e=i.split(Ed);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function si(i){return g(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,i))})}function mr(){return"addTransceiver"in RTCPeerConnection.prototype}function gr(){return"addTrack"in RTCPeerConnection.prototype}function Rd(){if(!("getCapabilities"in RTCRtpSender))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 _d(){if(!("getCapabilities"in RTCRtpSender))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 $i(i){return i==="av1"||i==="vp9"}function ws(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}const Id={Chrome:"100",Safari:"15",Firefox:"100"};function Ad(i){if(!_e()||!("setCodecPreferences"in i))return!1;const e=Ri();if(!(e!=null&&e.name)||!e.version)return!1;const t=Id[e.name];return t?co(e.version,t)>=0:!1}function Qi(){var i;return((i=Ri())===null||i===void 0?void 0:i.name)==="Firefox"}function Od(){var i;return((i=Ri())===null||i===void 0?void 0:i.name)==="Chrome"}function Fn(){var i;return((i=Ri())===null||i===void 0?void 0:i.name)==="Safari"}function ro(){return _e()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _e(){return typeof document<"u"}function ci(){return navigator.product=="ReactNative"}function Es(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function ao(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function oo(){if(!ci())return;let i=ao();if(i)return i.platform}function vr(){if(_e())return window.devicePixelRatio;if(ci()){let i=ao();if(i)return i.devicePixelRatio}return 1}function co(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(n[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function Ld(i){for(const e of i)e.target.handleResize(e)}function Nd(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Kn=null;const yr=()=>(Kn||(Kn=new ResizeObserver(Ld)),Kn);let Yn=null;const br=()=>(Yn||(Yn=new IntersectionObserver(Nd,{root:null,rootMargin:"0px"})),Yn);function xd(){var i;const e=new Pt({sdk:wi.JS,protocol:yd,version:vd});return ci()&&(e.os=(i=oo())!==null&&i!==void 0?i:""),e}function kr(){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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Ni;function Xn(){if(!Ni){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(),[Ni]=n.stream.getAudioTracks(),!Ni)throw Error("Could not get empty media stream audio track");Ni.enabled=!1}return Ni.clone()}class uo{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,s)=>g(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 Wt{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 Dd(i){return io.includes(i)}function ri(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 Md(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Tr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}var qi;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(qi||(qi={}));class Ud{constructor(){this.pendingTasks=new Map,this.taskMutex=new Wt,this.nextTaskIndex=0}run(e){return g(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:qi.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=qi.RUNNING,yield e()}finally{t.status=qi.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return g(this,void 0,void 0,function*(){return this.run(()=>g(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}const Fd=["syncState","trickle","offer","answer","simulate","leave"];function Bd(i){const e=Fd.indexOf(i.case)>=0;return m.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}class Ms{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.rtt=0,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.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Ud,this.queuedRequests=[],this.closingLock=new Wt}join(e,t,n,s){return g(this,void 0,void 0,function*(){return this.isConnected=!1,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return g(this,void 0,void 0,function*(){if(!this.options){m.warn("attempted to reconnect without signal options being set, ignoring");return}return this.isReconnecting=!0,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=Md(e),e=e.replace(/\/$/,""),e+="/rtc";const r=xd(),a=Jd(t,r,n);return new Promise((o,c)=>g(this,void 0,void 0,function*(){const u=()=>g(this,void 0,void 0,function*(){this.close(),clearTimeout(d),c(new ne("room connection has been cancelled (signal)"))}),d=setTimeout(()=>{this.close(),c(new ne("room connection has timed out (signal)"))},n.websocketTimeout);s!=null&&s.aborted&&u(),s==null||s.addEventListener("abort",u),m.debug("connecting to ".concat(e+a)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(d)},this.ws.onerror=h=>g(this,void 0,void 0,function*(){if(!this.isConnected){clearTimeout(d);try{const f=yield fetch("http".concat(e.substring(2),"/validate").concat(a));if(f.status.toFixed(0).startsWith("4")){const p=yield f.text();c(new ne(p,0,f.status))}else c(new ne("Internal error",2,f.status))}catch{c(new ne("server was not reachable",1))}return}this.handleWSError(h)}),this.ws.onmessage=h=>g(this,void 0,void 0,function*(){var f,p,b,T;let w;if(typeof h.data=="string"){const _=JSON.parse(h.data);w=rt.fromJson(_)}else if(h.data instanceof ArrayBuffer)w=rt.fromBinary(new Uint8Array(h.data));else{m.error("could not decode websocket message: ".concat(typeof h.data));return}if(!this.isConnected){let _=!1;if(((f=w.message)===null||f===void 0?void 0:f.case)==="join"?(this.isConnected=!0,s==null||s.removeEventListener("abort",u),this.pingTimeoutDuration=w.message.value.pingTimeout,this.pingIntervalDuration=w.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(m.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),o(w.message.value)):n.reconnect?(this.isConnected=!0,s==null||s.removeEventListener("abort",u),this.startPingInterval(),((p=w.message)===null||p===void 0?void 0:p.case)==="reconnect"?o((b=w.message)===null||b===void 0?void 0:b.value):(o(),_=!0)):n.reconnect||c(new ne("did not receive join response, got ".concat((T=w.message)===null||T===void 0?void 0:T.case," instead"))),!_)return}this.signalLatency&&(yield si(this.signalLatency)),this.handleSignalResponse(w)}),this.ws.onclose=h=>{m.warn("websocket closed",{ev:h}),this.handleOnClose(h.reason)}}))}close(){return g(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const t=new Promise(n=>{this.ws?this.ws.onclose=()=>{n()}:n()});this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([t,si(250)])),this.ws=void 0}}finally{this.clearPingInterval(),e()}})}sendOffer(e){m.debug("sending offer",e),this.sendRequest({case:"offer",value:On(e)})}sendAnswer(e){return m.debug("sending answer"),this.sendRequest({case:"answer",value:On(e)})}sendIceCandidate(e,t){return m.trace("sending ice candidate",e),this.sendRequest({case:"trickle",value:new He({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new We({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new ct({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 ot({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new lt({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:V.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new pt({timestamp:V.parse(Date.now()),rtt:V.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new je({canReconnect:!1,reason:Ht.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return g(this,void 0,void 0,function*(){if(!t&&!Bd(e)&&this.isReconnecting){this.queuedRequests.push(()=>g(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield si(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){m.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case));return}const s=new _t({message:e});try{this.useJSON?this.ws.send(s.toJsonString()):this.ws.send(s.toBinary())}catch(r){m.error("error sending signal message",{error:r})}})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){m.debug("received unsupported message");return}if(s.case==="answer"){const r=Sr(s.value);this.onAnswer&&this.onAnswer(r)}else if(s.case==="offer"){const r=Sr(s.value);this.onOffer&&this.onOffer(r)}else if(s.case==="trickle"){const r=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(r,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"?this.resetPingTimeout():s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout()):m.debug("unsupported message",s)}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return g(this,void 0,void 0,function*(){if(!this.isConnected)return;const t=this.onClose;yield this.close(),m.debug("websocket connection closed: ".concat(e)),t&&t(e)})}handleWSError(e){m.error("websocket error",e)}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){m.warn("ping timeout duration not set");return}this.pingTimeout=ve.setTimeout(()=>{m.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ve.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){m.warn("ping interval duration not set");return}m.debug("start ping interval"),this.pingInterval=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){m.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function Sr(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 On(i){return new Se({sdp:i.sdp,type:i.type})}function Jd(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",ci()?"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.publishOnly!==void 0&&s.set("publish",t.publishOnly),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())}const jd=10,hn="lk_e2ee",Vd="LKFrameEncryptionKey",$d={sharedKey:!1,ratchetSalt:Vd,ratchetWindowSize:8,failureTolerance:jd};var ti;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(ti||(ti={}));var Cr;(function(i){i.KeyRatcheted="keyRatcheted"})(Cr||(Cr={}));var Zt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Zt||(Zt={}));var wr;(function(i){i.Error="cryptorError"})(wr||(wr={}));function qd(){return Hd()||Ps()}function Ps(){return typeof window.RTCRtpScriptTransform<"u"}function Hd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Wd(i){const e=i.split("/")[1].toLowerCase();if(!io.includes(e))throw Error("Video codec not supported: ".concat(e));return e}class Fl extends mt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{m.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},$d),e),this.on(ti.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(ti.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(ti.RatchetRequest,e,t)}}function Us(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(s=t.callback)!=null&&s,c=t.maxWait,u=Date.now(),d=[];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),b=this;return new Promise(function(T,w){var _=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,u=Date.now(),!a){var Q=i.apply(b,p);o&&o(Q),d.forEach(function(j){return(0,j.resolve)(Q)}),d=[]}},h()),_){var M=i.apply(b,p);return o&&o(M),T(M)}d.push({resolve:T,reject:w})})};return f.cancel=function(p){r!==void 0&&clearTimeout(r),d.forEach(function(b){return(0,b.reject)(p)}),d=[]},f}const Er="default";class be{static getInstance(){return this.instance===void 0&&(this.instance=new be),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n;return g(this,void 0,void 0,function*(){if(((n=be.userMediaPromiseMap)===null||n===void 0?void 0:n.size)>0){m.debug("awaiting getUserMedia promise");try{e?yield be.userMediaPromiseMap.get(e):yield Promise.all(be.userMediaPromiseMap.values())}catch{m.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&!(Fn()&&this.hasDeviceInUse(e))&&(s.length===0||s.some(a=>{const o=a.label==="",c=e?a.kind===e:!0;return o&&c}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},o=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),o.getTracks().forEach(c=>{c.stop()})}return e&&(s=s.filter(r=>r.kind===e)),s})}normalizeDeviceId(e,t,n){return g(this,void 0,void 0,function*(){if(t!==Er)return t;const r=(yield this.getDevices(e)).find(a=>a.groupId===n&&a.deviceId!==Er);return r==null?void 0:r.deviceId})}hasDeviceInUse(e){return e?be.userMediaPromiseMap.has(e):be.userMediaPromiseMap.size>0}}be.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];be.userMediaPromiseMap=new Map;const Gd=1e3;class Zi extends C{get constraints(){return this._constraints}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;super(e,t),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>m.debug("track mute bounce got cancelled by an unmute event")),this.debouncedTrackMuteHandler=Us(()=>g(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>g(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 Wt,this.pauseUpstreamLock=new Wt,this.processorLock=new Wt,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 g(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Ti(this._mediaStreamTrack,s)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop()),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&&this.processorElement){if(m.debug("restarting processor"),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");vi(e,this.processorElement),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(yield this.sender.replaceTrack(n??e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{vi(n??e,s)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Gd;return g(this,void 0,void 0,function*(){if(this.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t<e;){const n=this.dimensions;if(n)return n;yield si(50)}throw new Qe("unable to get track dimensions after timeout")})}getDeviceId(){return g(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 be.getInstance().normalizeDeviceId(n,e,t)})}mute(){return g(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return g(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 g(this,void 0,void 0,function*(){if(!this.sender)throw new Qe("unable to replace an unpublished track");return m.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this})}restart(e){return g(this,void 0,void 0,function*(){e||(e=this._constraints),m.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===C.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach(r=>{Ti(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),m.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(R.Restarted,this),this})}setTrackMuted(e){m.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),!(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 g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ro()&&(m.debug("visibility changed, is in Background: ".concat(this.isInBackground)),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(m.debug("track needs to be reacquired, restarting ".concat(this.source)),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 g(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){m.warn("unable to pause upstream for an unpublished track");return}this._isUpstreamPaused=!0,this.emit(R.UpstreamPaused,this);const t=Ri();if((t==null?void 0:t.name)==="Safari"&&co(t.version,"12.0")<0)throw new xs("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return g(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){m.warn("unable to resume upstream for an unpublished track");return}this._isUpstreamPaused=!1,this.emit(R.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return g(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 g(this,void 0,void 0,function*(){const r=yield this.processorLock.lock();try{if(m.debug("setting up processor"),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),this.processorElement.muted=!0,vi(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch(o=>m.error("failed to play processor element",{error:o}));const a={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(a),this.processor=e,this.processor.processedTrack){for(const o of this.attachedElements)o!==this.processorElement&&t&&(Ti(this._mediaStreamTrack,o),vi(this.processor.processedTrack,o));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 g(this,void 0,void 0,function*(){this.processor&&(m.debug("stopping processor"),(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 zd extends mt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:a}=t.data;switch(r){case"error":m.error(a.error.message),this.emit(Zt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(Zt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Zt.ParticipantEncryptionStatusChanged,a.enabled,o)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"ratchetKey":this.keyProvider.emit(ti.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{m.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Zt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!qd())throw new xs("tried to setup end-to-end encryption on an unsupported browser");if(m.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&&(m.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){m.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?m.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(N.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(P.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==ke.NONE,s.identity)),e.on(P.ConnectionStateChanged,n=>{n===Y.Connected&&e.participants.forEach(s=>{s.tracks.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==ke.NONE,s.identity)})})}).on(P.TrackUnsubscribed,(n,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).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(L.LocalTrackPublished,n=>g(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(ti.SetKey,n=>this.postKey(n)).on(ti.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 a={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(a)}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"?Wd(n.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof Zi)||!t){t||m.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return g(this,void 0,void 0,function*(){if(this.worker){if(Ps()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(hn in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(o,[a,r])}e[hn]=!0}})}handleSender(e,t,n){var s;if(!(hn 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(Ps()){m.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{m.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[hn]=!0}}}var lo={},ho={exports:{}},Pr=ho.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(Pr).forEach(function(i){var e=Pr[i];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var fo=ho.exports;(function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,u,d){if(d&&!u)c[d]=e(o[1]);else for(var h=0;h<u.length;h+=1)o[h+1]!=null&&(c[u[h]]=e(o[h+1]))},n=function(o,c,u){var d=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:d&&!c[o.name]&&(c[o.name]={});var h=o.push?{}:d?c[o.name]:c;t(u.match(o.reg),h,o.names,o.name),o.push&&c[o.push].push(h)},s=fo,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},u=[],d=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var f=h[0],p=h.slice(2);f==="m"&&(u.push({rtp:[],fmtp:[]}),d=u[u.length-1]);for(var b=0;b<(s[f]||[]).length;b+=1){var T=s[f][b];if(T.reg.test(p))return n(T,d,p)}}),c.media=u,c};var a=function(o,c){var u=c.split(/=(.+)/,2);return u.length===2?o[u[0]]=e(u[1]):u.length===1&&c.length>1&&(o[u[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var c=[],u=o.split(" ").map(e),d=0;d<u.length;d+=3)c.push({component:u[d],ip:u[d+1],port:u[d+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(u){var d,h=!1;return u[0]!=="~"?d=e(u):(d=e(u.substring(1,u.length)),h=!0),{scid:d,paused:h}})})}})(lo);var Qn=fo,Kd=/%[sdv%]/g,Yd=function(i){var e=1,t=arguments,n=t.length;return i.replace(Kd,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""}})},xi=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 a=e.names[r];e.name?s.push(t[e.name][a]):s.push(t[e.names[r]])}else s.push(t[e.name]);return Yd.apply(null,s)},Xd=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Qd=["i","c","b","a"],Zd=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||Xd,n=e.innerOrder||Qd,s=[];return t.forEach(function(r){Qn[r].forEach(function(a){a.name in i&&i[a.name]!=null?s.push(xi(r,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(o){s.push(xi(r,a,o))})})}),i.media.forEach(function(r){s.push(xi("m",Qn.m[0],r)),n.forEach(function(a){Qn[a].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(xi(a,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(c){s.push(xi(a,o,c))})})})}),s.join(`\r
50
50
  `)+`\r
51
- `},Zd=co,el=Qd,Qn=el,Ji=Zd.parse;const Er=.7,Ci={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Pr extends mt.EventEmitter{get pc(){if(this._pc)return this._pc;throw new pe("Expected peer connection to be available")}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ms(n=>{this.emit(Ci.NegotiationStarted);try{this.createAndSendOffer()}catch(s){if(n)n(s);else throw s}},100),this._pc=xd()?new RTCPeerConnection(e,t):new RTCPeerConnection(e)}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return g(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 g(this,void 0,void 0,function*(){let n;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=il(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=Ji((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(o=u.payload,!0):!1),o===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===o){u.config=u.config.split(";").filter(d=>!d.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),n=Qn(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,this.createAndSendOffer()):e.type==="answer"&&(this.emit(Ci.NegotiationComplete),e.sdp&&Ji(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Ci.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){var t;return g(this,void 0,void 0,function*(){if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(p.debug("restarting ICE"),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"){p.warn("could not createOffer with closed peer connection");return}p.debug("starting to negotiate");const n=yield this.pc.createOffer(e),s=Ji((t=n.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"?Rr(r,[],[]):r.type==="video"&&(tl(r),this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(o=u.payload,!0):!1),o===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===o){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(a.maxbr*Er)),u.config.includes("x-google-max-bitrate")||(u.config+=";x-google-max-bitrate=".concat(a.maxbr)),c=!0;break}return c||r.fmtp.push({payload:o,config:"x-google-start-bitrate=".concat(a.maxbr*Er,";x-google-max-bitrate=").concat(a.maxbr)}),!0}))}),yield this.setMungedSDP(n,Qn(s)),this.onOffer(n)})}createAndSetAnswer(){var e;return g(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),n=Ji((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{s.type==="audio"&&Rr(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Qn(n)),t})}setTrackCodecBitrate(e){this.trackBitrates.push(e)}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)}setMungedSDP(e,t,n){return g(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{p.debug("setting munged ".concat(n?"remote":"local"," description")),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){p.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{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 a={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),p.error("unable to set ".concat(e.type),a),new ks(r)}})}}function Rr(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 tl(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(!Wi(r))return;let a=0;((n=i.ext)===null||n===void 0?void 0:n.some(c=>c.uri===hr?!0:(c.value>a&&(a=c.value),!1)))||(s=i.ext)===null||s===void 0||s.push({value:a+1,uri:hr})}function il(i){var e;const t=[],n=[],s=Ji((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&n.push(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}const nl={audioBitrate:xn.music.maxBitrate,audioPreset:xn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ns.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!1},ho={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},fo={resolution:en.h720.resolution},sl={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Xu,disconnectOnPageLeave:!0,expWebAudioMix:!1},po={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},_r="_lossy",Ir="_reliable",rl=2*1e3,xr="leave-reconnect";var Le;(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"})(Le||(Le={}));class al extends mt.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=po.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Le.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=t=>{let{channel:n}=t;return g(this,void 0,void 0,function*(){if(n){if(n.label===Ir)this.reliableDCSub=n;else if(n.label===_r)this.lossyDCSub=n;else return;p.debug("on data channel ".concat(n.id,", ").concat(n.label)),n.onmessage=this.handleDataMessage}})},this.handleDataMessage=t=>g(this,void 0,void 0,function*(){var n,s;const r=yield this.dataProcessLock.lock();try{let a;if(t.data instanceof ArrayBuffer)a=t.data;else if(t.data instanceof Blob)a=yield t.data.arrayBuffer();else{p.error("unsupported data type",t.data);return}const o=Ze.fromBinary(new Uint8Array(a));((n=o.value)===null||n===void 0?void 0:n.case)==="speaker"?this.emit(O.ActiveSpeakersUpdate,o.value.value.speakers):((s=o.value)===null||s===void 0?void 0:s.case)==="user"&&this.emit(O.DataPacketReceived,o.value.value,o.kind)}finally{r()}}),this.handleDataError=t=>{const s=t.currentTarget.maxRetransmits===0?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:r}=t.error;p.error("DataChannel error on ".concat(s,": ").concat(t.message),r)}else p.error("Unknown DataChannel error on ".concat(s),t)},this.handleBufferedAmountLow=t=>{const s=t.currentTarget.maxRetransmits===0?de.LOSSY:de.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;p.warn("".concat(t," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=o=>{p.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(o,"ms. giving up")),this.emit(O.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(a===null){s(r);return}t===xr&&(a=0),p.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ve.setTimeout(()=>this.attemptReconnect(n),a)},this.waitForRestarted=()=>new Promise((t,n)=>{this.pcState===Le.Connected&&t();const s=()=>{this.off(O.Disconnected,r),t()},r=()=>{this.off(O.Restarted,s),n()};this.once(O.Restarted,s),this.once(O.Disconnected,r)}),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);typeof n<"u"&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(O.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=t=>{const n=this.dataChannelForKind(t);if(n)return n.bufferedAmount<=n.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Fe.RR_SIGNAL_DISCONNECTED))},this.client=new Ds,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Gt,this.dataProcessLock=new Gt,this.dcBufferStatus=new Map([[de.LOSSY,!0],[de.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(O.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(O.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(O.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(O.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(O.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(O.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(O.StreamStateChanged,t)}join(e,t,n,s){return g(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.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof ie&&r.reason===1&&(p.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}close(){return g(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.emit(O.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return g(this,void 0,void 0,function*(){this.publisher&&this.publisher.pc.signalingState!=="closed"&&this.publisher.pc.getSenders().forEach(t=>{var n,s;try{!((n=this.publisher)===null||n===void 0)&&n.pc.removeTrack&&((s=this.publisher)===null||s===void 0||s.pc.removeTrack(t))}catch(r){p.warn("could not removeTrack",{error:r})}}),this.publisher&&(this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.hasPublished=!1,this.primaryPC=void 0;const e=t=>{t&&(t.close(),t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return g(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Qe("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 ie("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){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return(t=this.publisher)===null||t===void 0||t.pc.removeTrack(e),!0}catch(n){p.warn("failed to remove track",{error:n,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return g(this,void 0,void 0,function*(){if(this.primaryPC!==void 0)return ol(this.primaryPC)})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t,n;if(this.publisher||this.subscriber)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(p.debug("E2EE - setting up transports with insertable streams"),s.encodedInsertableStreams=!0);const r={optional:[{googDscp:!0}]};this.publisher=new Pr(s,r),this.subscriber=new Pr(s),this.emit(O.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=u=>{u.candidate&&(p.trace("adding ICE candidate for peer",u.candidate),this.client.sendIceCandidate(u.candidate,Re.PUBLISHER))},this.subscriber.pc.onicecandidate=u=>{u.candidate&&this.client.sendIceCandidate(u.candidate,Re.SUBSCRIBER)},this.publisher.onOffer=u=>{this.client.sendOffer(u)};let a=this.publisher.pc,o=this.subscriber.pc,c=e.subscriberPrimary;c&&(a=this.subscriber.pc,o=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=a,a.onconnectionstatechange=()=>g(this,void 0,void 0,function*(){if(p.debug("primary PC state changed ".concat(a.connectionState)),a.connectionState==="connected"){const u=this.pcState===Le.New;this.pcState=Le.Connected,u&&this.emit(O.Connected,e)}else a.connectionState==="failed"&&this.pcState===Le.Connected&&(this.pcState=Le.Disconnected,this.handleDisconnect("primary peerconnection",c?Fe.RR_SUBSCRIBER_FAILED:Fe.RR_PUBLISHER_FAILED))}),o.onconnectionstatechange=()=>g(this,void 0,void 0,function*(){p.debug("secondary PC state changed ".concat(o.connectionState)),o.connectionState==="failed"&&this.handleDisconnect("secondary peerconnection",c?Fe.RR_PUBLISHER_FAILED:Fe.RR_SUBSCRIBER_FAILED)}),this.subscriber.pc.ontrack=u=>{this.emit(O.MediaTrackAdded,u.track,u.streams[0],u.receiver)},this.createDataChannels()}setupSignalClientCallbacks(){this.client.onAnswer=e=>g(this,void 0,void 0,function*(){this.publisher&&(p.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState.toString()}),yield this.publisher.setRemoteDescription(e))}),this.client.onTrickle=(e,t)=>{!this.publisher||!this.subscriber||(p.trace("got ICE candidate from peer",{candidate:e,target:t}),t===Re.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>g(this,void 0,void 0,function*(){if(!this.subscriber)return;p.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState.toString()}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{if(p.debug("received trackPublishedResponse",e),!this.pendingTrackResolvers[e.cid]){p.error("missing track resolver for ".concat(e.cid));return}const{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Fe.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(xr)):(this.emit(O.Disconnected,e==null?void 0:e.reason),this.close()),p.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=Object.assign({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const n=[];e.iceServers.forEach(s=>{const r={urls:s.urls};s.username&&(r.username=s.username),s.credential&&(r.credential=s.credential),n.push(r)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ke.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(_r,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Ir,{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;p.debug("get capabilities",s);const r=[],a=[],o=[];s.codecs.forEach(c=>{const u=c.mimeType.toLowerCase();if(u==="audio/opus"){r.push(c);return}if(!(u==="video/".concat(n))){o.push(c);return}if(n==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(c):a.push(c);return}r.push(c)}),Id(e)&&e.setCodecPreferences(r.concat(a,o))}createSender(e,t,n){return g(this,void 0,void 0,function*(){if(fr())return yield this.createTransceiverRTCRtpSender(e,t,n);if(pr())return p.warn("using add-track fallback"),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new pe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return g(this,void 0,void 0,function*(){if(fr())return this.createSimulcastTransceiverSender(e,t,n,s);if(pr())return p.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new pe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream);const r={direction:"sendonly",streams:s};n&&(r.sendEncodings=n);const a=yield this.publisher.pc.addTransceiver(e.mediaStreamTrack,r);return e.kind===C.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(a,e.kind,t.videoCodec),e.codec=t.videoCodec),a.sender})}createSimulcastTransceiverSender(e,t,n,s){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.publisher.pc.addTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return this.setPreferredCodec(a,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");return this.publisher.pc.addTrack(e)})}attemptReconnect(e){var t,n,s;return g(this,void 0,void 0,function*(){if(!this._isClosed&&!this.attemptingReconnect){(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ke.DISABLED||((s=(n=this.primaryPC)===null||n===void 0?void 0:n.signalingState)!==null&&s!==void 0?s:"closed")==="closed")&&(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 a=!0;r instanceof pe?(p.debug("received unrecoverable error",{error:r}),a=!1):r instanceof fn||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Fe.RR_UNKNOWN):(p.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(O.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){p.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){var t,n,s;return g(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new pe("could not reconnect, url or token not saved");p.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(O.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw p.warn("attempted connection restart, without signal options present"),new fn;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof ie&&a.reason===0?new pe("could not reconnect, token might be expired"):new fn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(O.SignalRestarted,r),yield this.waitForPCReconnected(),(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(O.Restarted)}catch(r){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){var t;return g(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new pe("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new pe("publisher and subscriber connections unset");p.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(O.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.publisher.pc.setConfiguration(s),this.subscriber.pc.setConfiguration(s)}}catch(n){let s="";throw n instanceof Error&&(s=n.message),n instanceof ie&&n.reason===0?new pe("could not reconnect, token might be expired"):new fn(s)}if(this.emit(O.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(O.Resumed)})}waitForPCInitialConnection(e,t){return g(this,void 0,void 0,function*(){if(this.pcState!==Le.Connected){if(this.pcState!==Le.New)throw new pe("Expected peer connection to be new on initial connection");return new Promise((n,s)=>{const r=()=>{p.warn("closing engine"),ve.clearTimeout(o),s(new ie("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&r(),t==null||t.signal.addEventListener("abort",r);const a=()=>{ve.clearTimeout(o),t==null||t.signal.removeEventListener("abort",r),n()},o=ve.setTimeout(()=>{this.off(O.Connected,a),s(new ie("could not establish pc connection"))},e??this.peerConnectionTimeout);this.once(O.Connected,a)})}})}waitForPCReconnected(){var e,t;return g(this,void 0,void 0,function*(){const n=Date.now();let s=n;for(this.pcState=Le.Reconnecting,p.debug("waiting for peer connection to reconnect");s-n<this.peerConnectionTimeout&&this.primaryPC!==void 0;){if(s-n>rl&&((e=this.primaryPC)===null||e===void 0?void 0:e.connectionState)==="connected"&&(!this.hasPublished||((t=this.publisher)===null||t===void 0?void 0:t.pc.connectionState)==="connected")&&(this.pcState=Le.Connected),this.pcState===Le.Connected)return;yield si(100),s=Date.now()}throw new ie("could not establish PC connection")})}sendDataPacket(e,t){return g(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,s,r;return g(this,void 0,void 0,function*(){const a=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!a)throw new ie("".concat(o," connection not set"));!t&&!(!((n=this.publisher)===null||n===void 0)&&n.isICEConnected)&&((s=this.publisher)===null||s===void 0?void 0:s.pc.iceConnectionState)!=="checking"&&this.negotiate();const c=this.dataChannelForKind(e,t);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((r=this.dataChannelForKind(e,t))===null||r===void 0?void 0:r.readyState)==="open")return;yield si(50)}throw new ie("could not establish ".concat(o," connection, state: ").concat(a.pc.iceConnectionState))})}ensurePublisherConnected(e){return g(this,void 0,void 0,function*(){yield this.ensureDataTransportConnected(e,!1)})}verifyTransport(){return!(!this.primaryPC||this.primaryPC.connectionState==="closed"||this.primaryPC.connectionState==="failed"||this.hasPublished&&this.subscriberPrimary&&(!this.publisher||this.publisher.pc.connectionState==="closed"||this.publisher.pc.connectionState==="failed")||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise((e,t)=>{if(!this.publisher){t(new ks("publisher is not defined"));return}this.hasPublished=!0;const n=()=>{p.debug("engine disconnected while negotiation was ongoing"),r(),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(O.Closing,n);const s=setTimeout(()=>{t("negotiation timed out"),this.handleDisconnect("negotiation",Fe.RR_SIGNAL_DISCONNECTED)},this.peerConnectionTimeout),r=()=>{clearTimeout(s),this.off(O.Closing,n)};this.publisher.once(Ci.NegotiationStarted,()=>{var a;(a=this.publisher)===null||a===void 0||a.once(Ci.NegotiationComplete,()=>{r(),e()})}),this.publisher.once(Ci.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(c=>{const u=c.codec.toLowerCase();Nd(u)&&o.set(c.payload,u)}),this.emit(O.RTPVideoMapUpdate,o)}),this.publisher.negotiate(a=>{r(),t(a),a instanceof ks&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Fe.RR_UNKNOWN)})})}dataChannelForKind(e,t){if(t){if(e===de.LOSSY)return this.lossyDCSub;if(e===de.RELIABLE)return this.reliableDCSub}else{if(e===de.LOSSY)return this.lossyDC;if(e===de.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_e()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){_e()&&window.removeEventListener("online",this.handleBrowserOnLine)}}function ol(i){var e;return g(this,void 0,void 0,function*(){let t="";const n=new Map,s=new Map;if((yield i.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}class fn extends Error{}class Ar{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 ws(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return g(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),p.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return g(this,void 0,void 0,function*(){const t=yield fetch("".concat(cl(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 ie("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function cl(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}const Us=2e3;function Bn(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 we extends nn{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.Audio,t,n),this.stopOnMute=!1,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){p.error("could not get audio sender stats",{error:a});return}r&&this.prevStats&&(this._currentBitrate=Bn(r,this.prevStats)),this.prevStats=r}),this.audioContext=s,this.checkForSilence()}setDeviceId(e){return g(this,void 0,void 0,function*(){return this._constraints.deviceId===e?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ri(e)===this.mediaStreamTrack.getSettings().deviceId)})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(p.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==ri(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(p.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return g(this,void 0,void 0,function*(){let t;if(e){const n=Un({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 g(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){_e()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Us)))}setProcessor(e){var t;return g(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");if(this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};p.debug("setting up audio processor ".concat(e.name)),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 g(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 g(this,void 0,void 0,function*(){const e=yield Td(this);return e&&(this.isMuted||p.warn("silence detected on local audio track"),this.emit(R.AudioSilenceDetected)),e})}}function mo(i,e){switch(i.kind){case"audio":return new we(i,e,!1);case"video":return new Ne(i,e,!1);default:throw new Qe("unsupported track type: ".concat(i.kind))}}const ul=Object.values(en),dl=Object.values(Ts),ll=Object.values(Ns),hl=[en.h180,en.h360],fl=[Ts.h180,Ts.h360],pl=i=>[{scaleResolutionDownBy:2,fps:3}].map(t=>{var n;return new Z(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)/t.fps)))),t.fps,i.encoding.priority)}),Ps=["q","h","f"];function go(i,e,t,n){var s,r;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,u=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=ml(i,e,t,u),p.debug("using video encoding",a));const d=new Z(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Wi(u)){p.debug("using svc with scalabilityMode ".concat(c));const m=new vo(c),b=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let T=0;T<m.spatial;T+=1)b.push({rid:Ps[2-T],maxBitrate:a.maxBitrate/Math.pow(3,T),maxFramerate:d.encoding.maxFramerate});return b[0].scalabilityMode=c,p.debug("encodings",b),b}if(!o)return[a];let h=[];i?h=(s=Nr(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Lr(i,d):h=(r=Nr(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Lr(i,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const b=Math.max(e,t);if(b>=960&&f)return Zn(e,t,[m,f,d]);if(b>=480)return Zn(e,t,[m,d])}return Zn(e,t,[d])}function Or(i,e,t){var n,s,r,a;if(!t.backupCodec||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&p.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),c=(n=o.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,u=(r=o.height)!==null&&r!==void 0?r:(a=i.dimensions)===null||a===void 0?void 0:a.height;return go(i.source===C.Source.ScreenShare,c,u,t)}function ml(i,e,t,n){const s=gl(i,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)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 gl(i,e,t){if(i)return ll;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?ul:dl}function Lr(i,e){if(i)return pl(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)?hl:fl}function Zn(i,e,t){const n=[];if(t.forEach((s,r)=>{if(r>=Ps.length)return;const a=Math.min(i,e),c={rid:Ps[r],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate};s.encoding.maxFramerate&&(c.maxFramerate=s.encoding.maxFramerate);const u=tn()||r===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),n.push(c)}),ci()&&ro()==="ios"){let s;n.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let r=!0;n.forEach(a=>{var o;a.maxFramerate!=s&&(r&&(r=!1,p.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),p.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(s)),a.maxFramerate=s)})}return n}function Nr(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 vo{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 vl=5e3;class Ne extends nn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;super(e,C.Kind.Video,t,n),this.simulcastCodecs=new Map,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){p.error("could not get audio sender stats",{error:a});return}const r=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;r.forEach((o,c)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);a+=Bn(o,d)}),this._currentBitrate=a}this.prevStats=r}),this.senderLock=new Gt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!_e())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()},Us))}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,a;return g(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0)r=u.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(d){n={error:d}}finally{try{!o&&!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,a;return g(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0){r=u.value,o=!1;const d=r;yield(a=d.sender)===null||a===void 0?void 0:a.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!o&&!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 g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Camera&&!this.isUserProvided&&(p.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Camera&&!this.isUserProvided&&(p.debug("reacquiring camera track"),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 g(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 a={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},o=n.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t})}setPublishingQuality(e){const t=[];for(let n=oe.LOW;n<=oe.HIGH;n+=1)t.push(new ze({quality:n,enabled:n<=e}));p.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}setDeviceId(e){return g(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ri(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ri(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,n,s,r;return g(this,void 0,void 0,function*(){let a;if(e){const d=Un({video:e});typeof d.video!="boolean"&&(a=d.video)}yield this.restart(a);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0){r=u.value,o=!1;const d=r;d.sender&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){n={error:d}}finally{try{!o&&!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,a,o,c,u;return g(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 d=!0,h=gi(this.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)o=f.value,d=!1,yield(u=o.sender)===null||u===void 0?void 0:u.replaceTrack(this.processor.processedTrack)}catch(m){r={error:m}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(r)throw r.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));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)},vl))}setPublishingCodecs(e){var t,n,s,r,a,o,c;return g(this,void 0,void 0,function*(){if(p.debug("setting publishing codecs",{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=gi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(d.qualities);else{const h=this.simulcastCodecs.get(d.codec);if(p.debug("try setPublishingCodec for ".concat(d.codec),h),!h||!h.sender){for(const f of d.qualities)if(f.enabled){u.push(d.codec);break}}else h.encodings&&(p.debug("try setPublishingLayersForSender ".concat(d.codec)),yield Dr(h.sender,h.encodings,d.qualities,this.senderLock))}}}catch(d){a={error:d}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return u})}setPublishingLayers(e){return g(this,void 0,void 0,function*(){p.debug("setting publishing layers",e),!(!this.sender||!this.encodings)&&(yield Dr(this.sender,this.encodings,e,this.senderLock))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),no()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Dr(i,e,t,n){return g(this,void 0,void 0,function*(){const s=yield n.lock();p.debug("setPublishingLayersForSender",{sender:i,qualities:t,senderEncodings:e});try{const r=i.getParameters(),{encodings:a}=r;if(!a)return;if(a.length!==e.length){p.warn("cannot set publishing layers, encodings mismatch");return}let o=!1;!1&&a[0].scalabilityMode||a.forEach((u,d)=>{var h;let f=(h=u.rid)!==null&&h!==void 0?h:"";f===""&&(f="q");const m=yo(f),b=t.find(T=>T.quality===m);b&&u.active!==b.enabled&&(o=!0,u.active=b.enabled,p.debug("setting layer ".concat(b.quality," to ").concat(u.active?"enabled":"disabled")),tn()&&(b.enabled?(u.scaleResolutionDownBy=e[d].scaleResolutionDownBy,u.maxBitrate=e[d].maxBitrate,u.maxFrameRate=e[d].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))}),o&&(r.encodings=a,p.debug("setting encodings",r.encodings),yield i.setParameters(r))}finally{s()}})}function yo(i){switch(i){case"f":return oe.HIGH;case"h":return oe.MEDIUM;case"q":return oe.LOW;default:return oe.HIGH}}function Mr(i,e,t,n){if(!t)return[new Te({quality:oe.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new vo(s),a=[];for(let o=0;o<r.spatial;o+=1)a.push(new Te({quality:oe.HIGH-o,width:Math.ceil(i/Math.pow(2,o)),height:Math.ceil(e/Math.pow(2,o)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(3,o)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let u=yo((a=s.rid)!==null&&a!==void 0?a:"");return new Te({quality:u,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}class bo extends C{constructor(e,t,n,s){super(e,n),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,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return g(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(),Us))}}class zi extends bo{constructor(e,t,n,s,r){super(e,t,C.Kind.Audio,n),this.monitorReceiver=()=>g(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=Bn(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;ci()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ci())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return g(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Cs(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&Cs(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(p.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),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 g(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 Ki extends bo{constructor(e,t,n,s){super(e,t,C.Kind.Video,n),this.elementInfos=[],this.monitorReceiver=()=>g(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const r=yield this.getReceiverStats();r&&this.prevStats&&this.receiver&&(this._currentBitrate=Bn(r,this.prevStats)),this.prevStats=r}),this.debouncedHandleResize=Ms(()=>{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?Si(this._mediaStreamTrack,t):yi(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 yl(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()):p.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream){p.warn("stopObservingElementInfo ignored");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 g(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:"video",framesDecoded:n.framesDecoded,framesDropped:n.framesDropped,framesReceived:n.framesReceived,packetsReceived:n.packetsReceived,packetsLost:n.packetsLost,frameWidth:n.frameWidth,frameHeight:n.frameHeight,pliCount:n.pliCount,firCount:n.firCount,nackCount:n.nackCount,jitter:n.jitter,timestamp:n.timestamp,bytesReceived:n.bytesReceived,decoderImplementation:n.decoderImplementation})}),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 g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,c)=>Math.max(o,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(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-n<es){ve.setTimeout(()=>{this.updateVisibility()},es);return}this.lastVisible=a,this.emit(R.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>n+s&&(n=o,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"?mr():t||(mr()>2?2:1)}}class yl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:a}=n;r===this.element&&(this.isIntersecting=a,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??Ur(e),this.isPiP=_e()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Ur(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,vr().observe(this.element),gr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=vr())===null||e===void 0||e.unobserve(this.element),(t=gr())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Ur(i){let e=i.offsetTop,t=i.offsetLeft;const n=i.offsetWidth,s=i.offsetHeight,{hidden:r}=i,{opacity:a,display:o}=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&&(a!==""?parseFloat(a)>0:!0)&&o!=="none"}class kt extends mt.EventEmitter{constructor(e,t,n){super(),this.metadataMuted=!1,this.encryption=ke.NONE,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},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 isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==ke.NONE}get audioTrack(){if(this.track instanceof we||this.track instanceof zi)return this.track}get videoTrack(){if(this.track instanceof Ne||this.track instanceof Ki)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,p.debug("update publication info",{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={}))})(kt||(kt={}));class On extends kt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n){super(e,t.sid,t.name),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 g(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return g(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return g(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return g(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var ni;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Unknown="unknown"})(ni||(ni={}));function bl(i){switch(i){case ti.EXCELLENT:return ni.Excellent;case ti.GOOD:return ni.Good;case ti.POOR:return ni.Poor;default:return ni.Unknown}}class ko extends mt.EventEmitter{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every(e=>e.isEncrypted)}constructor(e,t,n,s){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ni.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(C.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(C.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrack(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,p.trace("update participant info",{info:e}),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(A.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(A.ParticipantNameChanged,e)}setPermissions(e){var t,n,s,r,a;const o=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!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])});return this.permissions=e,c&&this.emit(A.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(A.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=bl(e),t!==this._connectionQuality&&this.emit(A.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach(t=>(t.track instanceof zi||t.track instanceof we)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(A.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(A.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case C.Kind.Video:this.videoTracks.set(e.trackSid,e);break}}}function kl(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 dt({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 kt{constructor(e,t,n){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=oe.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(R.Ended,s)},this.handleVisibilityChange=s=>{p.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),{trackSid:this.trackSid}),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{p.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),{trackSid:this.trackSid}),this.videoDimensions=s,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 it({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?kt.SubscriptionStatus.Unsubscribed:super.isSubscribed?kt.SubscriptionStatus.Subscribed:kt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?kt.PermissionStatus.Allowed:kt.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 Ki&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Ki&&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?(p.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):this.isDesired?!0:(p.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof Ki&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new at({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=oe.HIGH,this.emit(R.UpdateSettings,e)}}class sn extends ko{static fromParticipantInfo(e,t){return new sn(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,n,s,r){super(t,n||"",s,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(R.UpdateSettings,t=>{p.debug("send update settings",t),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(A.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(A.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(A.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(A.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(A.TrackSubscriptionFailed,e.trackSid,t)})}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(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.getTrack(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.getTrack(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,a){let o=this.getTrackPublication(t);if(o||t.startsWith("TR")||this.tracks.forEach(d=>{!o&&e.kind===d.kind.toString()&&(o=d)}),!o){if(a===0){p.error("could not find published track",{participant:this.sid,trackSid:t}),this.emit(A.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,a-1)},150);return}if(e.readyState==="ended"){p.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),this.emit(A.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let u;return c?u=new Ki(e,t,s,r):u=new zi(e,t,s,this.audioContext,this.audioOutput),u.source=o.source,u.isMuted=o.isMuted,u.setMediaStream(n),u.start(),o.setTrack(u),this.volumeMap.has(o.source)&&u instanceof zi&&u.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r;let a=this.getTrackPublication(s.sid);if(a)a.updateInfo(s);else{const o=C.kindFromProto(s.type);if(!o)return;a=new To(o,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe),a.updateInfo(s),n.set(s.sid,a);const c=Array.from(this.tracks.values()).find(u=>u.source===(a==null?void 0:a.source));c&&a.source!==C.Source.Unknown&&p.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),{oldTrack:c,newTrack:a,participant:this,participantInfo:e}),this.addTrackPublication(a)}t.set(s.sid,a)}),this.tracks.forEach(s=>{t.has(s.trackSid)||(p.trace("detected removed track on remote participant, unpublishing",{publication:s,participantSid:this.sid}),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(A.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.tracks.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.tracks.delete(e),n.kind){case C.Kind.Audio:this.audioTracks.delete(e);break;case C.Kind.Video:this.videoTracks.delete(e);break}t&&this.emit(A.TrackUnpublished,n)}setAudioOutput(e){return g(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach(n=>{var s;n.track instanceof zi&&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 p.trace("participant event",{participant:this.sid,event:e,args:n}),super.emit(e,...n)}}class Fr extends ko{constructor(e,t,n,s){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ke.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new oo)},this.handleReconnected=()=>{var r,a;(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.resolve)===null||a===void 0||a.call(r),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>p.warn(o)),(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{p.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(r=>kl(r)))},this.onTrackUnmuted=r=>{this.onTrackMuted(r,r.isUpstreamPaused)},this.onTrackMuted=(r,a)=>{if(a===void 0&&(a=!0),!r.sid){p.error("could not update mute status for unpublished track",r);return}this.engine.updateMuteStatus(r.sid,a)},this.onTrackUpstreamPaused=r=>{p.debug("upstream paused"),this.onTrackMuted(r,!0)},this.onTrackUpstreamResumed=r=>{p.debug("upstream resumed"),this.onTrackMuted(r,r.isMuted)},this.handleSubscribedQualityUpdate=r=>g(this,void 0,void 0,function*(){var a,o,c,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTracks.get(r.trackSid);if(!f){p.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:r.trackSid});return}if(r.subscribedCodecs.length>0){if(!f.videoTrack)return;const w=yield f.videoTrack.setPublishingCodecs(r.subscribedCodecs);try{for(var m=!0,b=gi(w),T;T=yield b.next(),a=T.done,!a;m=!0){u=T.value,m=!1;const I=u;bd(I)&&(p.debug("publish ".concat(I," for ").concat(f.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(f.videoTrack,I,f.options))}}catch(I){o={error:I}}finally{try{!m&&!a&&(c=b.return)&&(yield c.call(b))}finally{if(o)throw o.error}}}else r.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(r.subscribedQualities))}),this.handleLocalTrackUnpublished=r=>{const a=this.tracks.get(r.trackSid);if(!a){p.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:r.trackSid});return}this.unpublishTrack(a.track)},this.handleTrackEnded=r=>g(this,void 0,void 0,function*(){if(r.source===C.Source.ScreenShare||r.source===C.Source.ScreenShareAudio)p.debug("unpublishing local track due to TrackEnded",{track:r.sid}),this.unpublishTrack(r);else if(r.isUserProvided)yield r.mute();else if(r instanceof we||r instanceof Ne)try{if(_e())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:r.source===C.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw p.warn("user has revoked access to ".concat(r.source)),a.onchange=()=>{a.state!=="denied"&&(r.isMuted||r.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}r.isMuted||(p.debug("track ended, attempting to use a different device"),yield r.restartTrack())}catch{p.warn("could not restart track, muting instead"),yield r.mute()}}),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=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!==ke.NONE}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.client.onRemoteMuteChanged=(t,n)=>{const s=this.tracks.get(t);!s||!s.track||(n?s.mute():s.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(O.Connected,this.handleReconnected).on(O.SignalRestarted,this.handleReconnected).on(O.SignalResumed,this.handleReconnected).on(O.Restarting,this.handleReconnecting).on(O.Resuming,this.handleReconnecting).on(O.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(A.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return g(this,void 0,void 0,function*(){this.encryptionType=e?ke.GCM:ke.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){var r,a;return g(this,void 0,void 0,function*(){p.debug("setTrackEnabled",{source:e,enabled:t});let o=this.getTrack(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){p.info("skipping duplicate published source",{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:(a=n)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Qe(e)}const u=[];for(const h of c)p.info("publishing track",{localTrack:h}),u.push(this.publishTrack(h,s));[o]=yield Promise.all(u)}catch(u){throw c==null||c.forEach(d=>{d.stop()}),u instanceof Error&&!(u instanceof Qe)&&this.emit(A.MediaDevicesError,u),u}finally{this.pendingPublishing.delete(e)}}else if(o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrack(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return g(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 g(this,void 0,void 0,function*(){const s=to(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),r=Un(s);let a;try{a=yield navigator.mediaDevices.getUserMedia(r)}catch(o){throw o instanceof Error&&(r.audio&&(this.microphoneError=o),r.video&&(this.cameraError=o)),o}return r.audio&&(this.microphoneError=void 0),r.video&&(this.cameraError=void 0),a.getTracks().map(o=>{const c=o.kind==="audio";c?e.audio:e.video;let u;const d=c?r.audio:r.video;typeof d!="boolean"&&(u=d);const h=mo(o,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=a,h})})}createScreenTracks(e){return g(this,void 0,void 0,function*(){if(e===void 0&&(e={}),e.resolution===void 0&&(e.resolution=Ns.h1080fps15.resolution),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ls("getDisplayMedia not supported");const t=Cd(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new Qe("no video track found");const r=new Ne(s[0],void 0,!1);r.source=C.Source.ScreenShare;const a=[r];if(n.getAudioTracks().length>0){const o=new we(n.getAudioTracks()[0],void 0,!1,this.audioContext);o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){var n,s,r,a;return g(this,void 0,void 0,function*(){yield(n=this.reconnectFuture)===null||n===void 0?void 0:n.promise,e instanceof nn&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let o;if(e instanceof MediaStreamTrack)o=e.getConstraints();else{o=e.constraints;let m;switch(e.source){case C.Source.Microphone:m="audioinput";break;case C.Source.Camera:m="videoinput"}m&&this.activeDeviceMap.has(m)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(m)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new we(e,o,!0,this.audioContext);break;case"video":e=new Ne(e,o,!0);break;default:throw new Qe("unsupported MediaStreamTrack kind ".concat(e.kind))}e instanceof we&&e.setAudioContext(this.audioContext);let c;if(this.tracks.forEach(m=>{m.track&&m.track===e&&(c=m)}),c)return p.warn("track has already been published, skipping"),c;const u="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,d=(s=t==null?void 0:t.forceStereo)!==null&&s!==void 0?s:u;d&&(t||(t={}),t.dtx===void 0&&p.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),t.red===void 0&&p.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),(a=t.red)!==null&&a!==void 0||(t.red=!1));const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Fn()&&this.roomOptions.e2ee&&(p.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),h.simulcast=!1),h.source&&(e.source=h.source);const f=this.publish(e,h,d);this.pendingPublishPromises.set(e,f);try{return yield f}catch(m){throw m}finally{this.pendingPublishPromises.delete(e)}})}publish(e,t,n){var s,r,a,o,c,u,d,h,f,m,b,T,w,I;return g(this,void 0,void 0,function*(){const D=Array.from(this.tracks.values()).find(F=>e instanceof nn&&F.source===e.source);if(D&&e.source!==C.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(F){F instanceof Error&&p.warn(F.message,{oldTrack:D,newTrack:e,trace:F.stack})}t.stopMicTrackOnMute&&e instanceof we&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&tn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Pd()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Rd()&&(t.videoCodec=void 0),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 Q=new qe({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)});let j,ce;if(e.kind===C.Kind.Video){let F={width:0,height:0};try{F=yield e.waitForDimensions()}catch{const Ue=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:en.h720.resolution;F={width:Ue.width,height:Ue.height},p.error("could not determine track dimensions, using defaults",F)}if(Q.width=F.width,Q.height=F.height,e instanceof Ne)if(Wi(t.videoCodec)&&(t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),t.videoCodec&&t.backupCodec&&t.videoCodec!==t.backupCodec.codec){this.roomOptions.dynacast||(this.roomOptions.dynacast=!0);const le=Object.assign({},t);le.simulcast=!0,ce=Or(e,t.backupCodec.codec,le),Q.simulcastCodecs=[new Be({codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0}),new Be({codec:t.backupCodec.codec,cid:"",enableSimulcastLayers:!0})]}else t.videoCodec&&(Q.simulcastCodecs=[new Be({codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:(u=t.simulcast)!==null&&u!==void 0?u:!1})]);j=go(e.source===C.Source.ScreenShare,F.width,F.height,t),Q.layers=Mr(Q.width,Q.height,j,Wi(t.videoCodec))}else e.kind===C.Kind.Audio&&(j=[{maxBitrate:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate)!==null&&h!==void 0?h:t.audioBitrate,priority:(m=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&m!==void 0?m:"high",networkPriority:(T=(b=t.audioPreset)===null||b===void 0?void 0:b.priority)!==null&&T!==void 0?T:"high"}]);if(!this.engine||this.engine.isClosed)throw new pe("cannot publish track when not connected");const ae=yield this.engine.addTrack(Q);let q=!1,K=!1;if(ae.codecs.forEach(F=>{lr(F.mimeType,t.videoCodec)?q=!0:t.backupCodec&&lr(F.mimeType,t.backupCodec.codec)&&(K=!0)}),Q.simulcastCodecs.length>0){if(!q&&!K)throw Error("cannot publish track, codec not supported by server");if(!q&&t.backupCodec){const F=t.backupCodec;t=Object.assign({},t),p.debug("primary codec ".concat(t.videoCodec," not supported, fallback to ").concat(F.codec)),t.videoCodec=F.codec,t.videoEncoding=F.encoding,j=ce}}const x=new On(e.kind,ae,e);if(x.options=t,e.sid=ae.sid,!this.engine.publisher)throw new pe("publisher is closed");if(p.debug("publishing ".concat(e.kind," with encodings"),{encodings:j,trackInfo:ae}),e.sender=yield this.engine.createSender(e,t,j),j)if(tn()&&e.kind===C.Kind.Audio){let F;for(const le of this.engine.publisher.pc.getTransceivers())if(le.sender===e.sender){F=le;break}F&&this.engine.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((w=j[0])===null||w===void 0)&&w.maxBitrate?j[0].maxBitrate/1e3:0})}else e.codec&&Wi(e.codec)&&(!((I=j[0])===null||I===void 0)&&I.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:Q.cid,codec:e.codec,maxbr:j[0].maxBitrate/1e3});return yield this.engine.negotiate(),e instanceof Ne?e.startMonitor(this.engine.client):e instanceof we&&e.startMonitor(),this.addTrackPublication(x),this.emit(A.LocalTrackPublished,x),x})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var s;return g(this,void 0,void 0,function*(){let r;if(this.tracks.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new Qe("track is not published");if(!(e instanceof Ne))throw new Qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),o=Or(e,t,a);if(!o){p.info("backup codec has been disabled, ignoring request to add additional codec for track");return}const c=e.addSimulcastTrack(t,o),u=new qe({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id,enableSimulcastLayers:a.simulcast}]});if(u.layers=Mr(u.width,u.height,o),!this.engine||this.engine.isClosed)throw new pe("cannot publish track when not connected");const d=yield this.engine.addTrack(u);yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate(),p.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:d})})}unpublishTrack(e,t){var n,s;return g(this,void 0,void 0,function*(){const r=this.getPublicationForTrack(e);if(p.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!r||!r.track){p.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});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 o=e.sender;if(e.sender=void 0,this.engine.publisher&&this.engine.publisher.pc.connectionState!=="closed"&&o)try{for(const c of this.engine.publisher.pc.getTransceivers())c.sender===o&&(c.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),e instanceof Ne){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(a=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){p.warn("failed to unpublish track",{error:c,method:"unpublishTrack"})}switch(this.tracks.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTracks.delete(r.trackSid);break;case C.Kind.Video:this.videoTracks.delete(r.trackSid);break}return this.emit(A.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return g(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>n instanceof On)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return g(this,void 0,void 0,function*(){const n=[];this.tracks.forEach(s=>{s.track&&(e&&(s.options=Object.assign(Object.assign({},s.options),e)),n.push(s))}),yield Promise.all(n.map(s=>g(this,void 0,void 0,function*(){const r=s.track;yield this.unpublishTrack(r,!1),t&&!r.isMuted&&(r instanceof we||r instanceof Ne)&&!r.isUserProvided&&(p.debug("restarting existing track",{track:s.trackSid}),yield r.restartTrack()),yield this.publishTrack(r,s.options)})))})}publishData(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return g(this,void 0,void 0,function*(){const s=Array.isArray(n)?n:n==null?void 0:n.destination,r=[],a=Array.isArray(n)?void 0:n.topic;s!==void 0&&s.forEach(c=>{c instanceof sn?r.push(c.sid):r.push(c)});const o=new Ze({kind:t,value:{case:"user",value:new tt({participantSid:this.sid,payload:e,destinationSids:r,topic:a})}});yield this.engine.sendDataPacket(o,t)})}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,s;const r=this.tracks.get(t.sid);if(r){const a=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(p.debug("updating server mute state after reconcile",{sid:t.sid,muted:a}),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.tracks.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(s instanceof we||s instanceof Ne)&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}publishedTracksInfo(){const e=[];return this.tracks.forEach(t=>{t.track!==void 0&&e.push(new Ge({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new ft({label:n.label,id:n.id,target:s}))};return t(this.engine.dataChannelForKind(de.LOSSY),Re.PUBLISHER),t(this.engine.dataChannelForKind(de.RELIABLE),Re.PUBLISHER),t(this.engine.dataChannelForKind(de.LOSSY,!0),Re.SUBSCRIBER),t(this.engine.dataChannelForKind(de.RELIABLE,!0),Re.SUBSCRIBER),e}}var Y;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting"})(Y||(Y={}));const Tl=2*1e3;class So extends mt.EventEmitter{constructor(e){var t,n;super(),t=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.connect=(s,r,a)=>g(this,void 0,void 0,function*(){var o;const c=yield this.disconnectLock.lock();if(this.state===Y.Connected)return p.info("already connected to room ".concat(this.name)),c(),Promise.resolve();if(this.connectFuture)return c(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),((o=this.regionUrlProvider)===null||o===void 0?void 0:o.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ws(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ar(s,r):this.regionUrlProvider.updateToken(r),this.regionUrlProvider.fetchRegionSettings().catch(h=>{p.warn("could not fetch region settings",{error:h})}));const u=(h,f,m)=>g(this,void 0,void 0,function*(){var b;this.abortController&&this.abortController.abort();const T=new AbortController;this.abortController=T,c==null||c();try{yield this.attemptConnection(m??s,r,a,T),this.abortController=void 0,h()}catch(w){if(this.regionUrlProvider&&w instanceof ie&&w.reason!==3&&w.reason!==0){let I=null;try{I=yield this.regionUrlProvider.getNextBestRegionUrl((b=this.abortController)===null||b===void 0?void 0:b.signal)}catch(D){if(D instanceof ie&&(D.status===401||D.reason===3)){f(D);return}}I?(p.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(I)),yield u(h,f,I)):f(w)}else f(w)}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new oo((h,f)=>{u(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,r,a,o,c,u)=>g(this,void 0,void 0,function*(){const d=yield a.join(s,r,{autoSubscribe:o.autoSubscribe,publishOnly:o.publishOnly,adaptiveStream:typeof c.adaptiveStream=="object"?!0:c.adaptiveStream,maxRetries:o.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:o.websocketTimeout},u.signal);let h=d.serverInfo;if(h||(h={version:d.serverVersion,region:d.serverRegion}),p.debug("connected to Livekit Server ".concat(Object.entries(h).map(f=>{let[m,b]=f;return"".concat(m,": ").concat(b)}).join(", "))),!d.serverVersion)throw new hd("unknown server version");return d.serverVersion==="0.15.1"&&this.options.dynacast&&(p.debug("disabling dynacast due to server version"),c.dynacast=!1),d}),this.applyJoinResponse=s=>{const r=s.participant;this.localParticipant.sid=r.sid,this.localParticipant.identity=r.identity,this.handleParticipantUpdates([r,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(s.sifTrailer)},this.attemptConnection=(s,r,a,o)=>g(this,void 0,void 0,function*(){var c,u;this.state===Y.Reconnecting?(p.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),!((c=this.regionUrlProvider)===null||c===void 0)&&c.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},po),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,r,this.engine,this.connOptions,this.options,o);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected)}catch(d){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const h=new ie("could not establish signal connection");throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof ie&&(h.reason=d.reason,h.status=d.status),p.debug("error trying to establish signal connection",{error:d}),h}if(o.signal.aborted)throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),new ie("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,o)}catch(d){throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),d}_e()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_e()&&(document.addEventListener("freeze",this.onPageLeave),(u=navigator.mediaDevices)===null||u===void 0||u.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(Y.Connected),this.emit(P.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return g(t,void 0,void 0,function*(){var r,a,o,c;const u=yield this.disconnectLock.lock();try{if(this.state===Y.Disconnected){p.debug("already disconnected");return}p.info("disconnect from room",{identity:this.localParticipant.identity}),(this.state===Y.Connecting||this.state===Y.Reconnecting)&&(p.warn("abort connection attempt"),(r=this.abortController)===null||r===void 0||r.abort(),(o=(a=this.connectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,new ie("Client initiated disconnect")),this.connectFuture=void 0),!((c=this.engine)===null||c===void 0)&&c.client.isConnected&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(s,Wt.CLIENT_INITIATED),this.engine=void 0}finally{u()}})},this.onPageLeave=()=>g(this,void 0,void 0,function*(){yield this.disconnect()}),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const s of this.participants.values())this.handleParticipantDisconnected(s.sid,s);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(P.Reconnecting)},this.handleSignalRestarted=s=>g(this,void 0,void 0,function*(){p.debug("signal reconnected to server",{region:s.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(s);try{const r=[];this.localParticipant.tracks.forEach(a=>{a.track&&r.push(a)}),yield Promise.all(r.map(a=>g(this,void 0,void 0,function*(){const o=a.track;this.localParticipant.unpublishTrack(o,!1),o.isMuted||((o instanceof we||o instanceof Ne)&&o.source!==C.Source.ScreenShare&&o.source!==C.Source.ScreenShareAudio&&!o.isUserProvided&&(p.debug("restarting existing track",{track:a.trackSid}),yield o.restartTrack()),p.debug("publishing new track",{track:a.trackSid}),yield this.localParticipant.publishTrack(o,a.options))})))}catch(r){p.error("error trying to re-publish tracks after reconnection",{error:r})}try{yield this.engine.waitForRestarted(),p.debug("fully reconnected to server",{region:s.serverRegion})}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.participants.forEach(r=>{this.emit(P.ParticipantConnected,r)})}),this.handleParticipantUpdates=s=>{s.forEach(r=>{if(r.identity===this.localParticipant.identity){this.localParticipant.updateInfo(r);return}const a=this.identityToSid.get(r.identity);a&&a!==r.sid&&this.handleParticipantDisconnected(a,this.participants.get(a));let o=this.participants.get(r.sid);const c=!o;r.state===ai.DISCONNECTED?this.handleParticipantDisconnected(r.sid,o):(o=this.getOrCreateParticipant(r.sid,r),c||o.updateInfo(r))})},this.handleActiveSpeakersUpdate=s=>{const r=[],a={};s.forEach(o=>{if(a[o.sid]=!0,o.sid===this.localParticipant.sid)this.localParticipant.audioLevel=o.level,this.localParticipant.setIsSpeaking(!0),r.push(this.localParticipant);else{const c=this.participants.get(o.sid);c&&(c.audioLevel=o.level,c.setIsSpeaking(!0),r.push(c))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach(o=>{a[o.sid]||(o.audioLevel=0,o.setIsSpeaking(!1))}),this.activeSpeakers=r,this.emitWhenConnected(P.ActiveSpeakersChanged,r)},this.handleSpeakersChanged=s=>{const r=new Map;this.activeSpeakers.forEach(o=>{r.set(o.sid,o)}),s.forEach(o=>{let c=this.participants.get(o.sid);o.sid===this.localParticipant.sid&&(c=this.localParticipant),c&&(c.audioLevel=o.level,c.setIsSpeaking(o.active),o.active?r.set(o.sid,c):r.delete(o.sid))});const a=Array.from(r.values());a.sort((o,c)=>c.audioLevel-o.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(P.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(r=>{const a=this.participants.get(r.participantSid);if(!a)return;const o=a.getTrackPublication(r.trackSid);!o||!o.track||(o.track.streamState=C.streamStateFromProto(r.state),a.emit(A.TrackStreamStateChanged,o,o.track.streamState),this.emitWhenConnected(P.TrackStreamStateChanged,o,o.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const r=this.participants.get(s.participantSid);if(!r)return;const a=r.getTrackPublication(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const r=Array.from(this.participants.values()).find(o=>o.tracks.has(s.trackSid));if(!r)return;const a=r.getTrackPublication(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=(s,r)=>{const a=this.participants.get(s.participantSid);this.emit(P.DataReceived,s.payload,a,r,s.topic),a==null||a.emit(A.DataReceived,s.payload,r)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(P.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{p.warn("could not playback audio",s),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(P.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>g(this,void 0,void 0,function*(){this.emit(P.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const r=this.roomInfo;this.roomInfo=s,r&&r.metadata!==s.metadata&&this.emitWhenConnected(P.RoomMetadataChanged,s.metadata),(r==null?void 0:r.activeRecording)!==s.activeRecording&&this.emitWhenConnected(P.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(r=>{if(r.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(r.quality);return}const a=this.participants.get(r.participantSid);a&&a.setConnectionQuality(r.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(P.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(P.ParticipantNameChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(P.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(P.TrackUnmuted,s,this.localParticipant)},this.onLocalTrackPublished=s=>g(this,void 0,void 0,function*(){var r;this.emit(P.LocalTrackPublished,s,this.localParticipant),s.track instanceof we&&(yield s.track.checkForSilence())&&this.emit(P.LocalAudioSilenceDetected,s);const a=yield(r=s.track)===null||r===void 0?void 0:r.getDeviceId(),o=Sd(s.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(P.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=s=>{this.emit(P.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalConnectionQualityChanged=s=>{this.emit(P.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(P.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(P.ParticipantPermissionsChanged,s,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},sl),e),this.options.audioCaptureDefaults=Object.assign(Object.assign({},ho),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},fo),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},nl),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Gt,this.localParticipant=new Fr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ri(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ri(this.options.audioCaptureDefaults.deviceId)),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&this.switchActiveDevice("audiooutput",ri(this.options.audioOutput.deviceId)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return g(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 Gd(this.options.e2ee),this.e2eeManager.on(ei.ParticipantEncryptionStatusChanged,(t,n)=>{n instanceof Fr&&(this.isE2EEEnabled=t),this.emit(P.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(ei.EncryptionError,t=>this.emit(P.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}get sid(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.sid)!==null&&t!==void 0?t:""}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 al(this.options),this.engine.on(O.ParticipantUpdate,this.handleParticipantUpdates).on(O.RoomUpdate,this.handleRoomUpdate).on(O.SpeakersChanged,this.handleSpeakersChanged).on(O.StreamStateChanged,this.handleStreamStateUpdate).on(O.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(O.SubscriptionError,this.handleSubscriptionError).on(O.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(O.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(O.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(O.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(O.DataPacketReceived,this.handleDataPacket).on(O.Resuming,()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(P.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())}).on(O.Resumed,()=>{this.setAndEmitConnectionState(Y.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions(),Array.from(this.participants.values()).filter(t=>!this.cachedParticipantSids.includes(t.sid)).forEach(t=>this.emit(P.ParticipantConnected,t)),this.cachedParticipantSids=[]}).on(O.SignalResumed,()=>{this.state===Y.Reconnecting&&this.sendSyncState()}).on(O.Restarting,this.handleRestarting).on(O.SignalRestarted,this.handleSignalRestarted).on(O.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 be.getInstance().getDevices(e,t)}prepareConnection(e,t){return g(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){p.debug("prepareConnection to ".concat(e));try{if(ws(new URL(e))&&t){this.regionUrlProvider=new Ar(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(br(n),{method:"HEAD"}),p.debug("prepared connection to ".concat(n)))}else yield fetch(br(e),{method:"HEAD"})}catch(n){p.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);if(t)return this.participants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return g(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"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=()=>g(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new je({reason:Wt.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&&(this.engine.client.sendSimulateScenario(s),n())})}startAudio(){return g(this,void 0,void 0,function*(){const e=[],t=_i();if(t&&t.os==="iOS"){const n="livekit-dummy-audio-el";let s=document.getElementById(n);if(!s){s=document.createElement("audio"),s.id=n,s.autoplay=!0,s.hidden=!0;const r=Yn();r.enabled=!0;const a=new MediaStream([r]);s.srcObject=a,document.addEventListener("visibilitychange",()=>{s&&(s.srcObject=document.hidden?null:a)}),document.body.append(s),this.once(P.Disconnected,()=>{s==null||s.remove()})}e.push(s)}this.participants.forEach(n=>{n.audioTracks.forEach(s=>{s.track&&s.track.attachedElements.forEach(r=>{e.push(r)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(n=>(n.muted=!1,n.play()))]),this.handleAudioPlaybackStarted()}catch(n){throw this.handleAudioPlaybackFailed(n),n}})}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return(t=(e=this.options.audioOutput)===null||e===void 0?void 0:e.deviceId)!==null&&t!==void 0?t:""}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,a;return g(this,void 0,void 0,function*(){let o=!1,c=!0;const u=n?{exact:t}:t;if(e==="audioinput"){const d=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=u,o=d!==u;const h=Array.from(this.localParticipant.audioTracks.values()).filter(f=>f.source===C.Source.Microphone);try{c=(yield Promise.all(h.map(f=>{var m;return(m=f.audioTrack)===null||m===void 0?void 0:m.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.audioCaptureDefaults.deviceId=d,f}}else if(e==="videoinput"){const d=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=u,o=d!==u;const h=Array.from(this.localParticipant.videoTracks.values()).filter(f=>f.source===C.Source.Camera);try{c=(yield Promise.all(h.map(f=>{var m;return(m=f.videoTrack)===null||m===void 0?void 0:m.setDeviceId(u)}))).every(f=>f===!0)}catch(f){throw this.options.videoCaptureDefaults.deviceId=d,f}}else if(e==="audiooutput"){if(!Cs()&&!this.options.expWebAudioMix||this.options.expWebAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");(s=(a=this.options).audioOutput)!==null&&s!==void 0||(a.audioOutput={});const d=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,o=d!==u;try{this.options.expWebAudioMix?(r=this.audioContext)===null||r===void 0||r.setSinkId(t):yield Promise.all(Array.from(this.participants.values()).map(h=>h.setAudioOutput({deviceId:t})))}catch(h){throw this.options.audioOutput.deviceId=d,h}}return o&&c&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(P.ActiveDeviceChanged,e,t)),c})}setupLocalParticipantEvents(){this.localParticipant.on(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(A.TrackMuted,this.onLocalTrackMuted).on(A.TrackUnmuted,this.onLocalTrackUnmuted).on(A.LocalTrackPublished,this.onLocalTrackPublished).on(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(A.MediaDevicesError,this.onMediaDevicesError).on(A.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),d()},d=()=>{this.off(P.Reconnected,u),this.off(P.Connected,u),this.off(P.Disconnected,d)};this.once(P.Reconnected,u),this.once(P.Connected,u),this.once(P.Disconnected,d);return}if(this.state===Y.Disconnected){p.warn("skipping incoming track after Room disconnected");return}const s=Ed(t.id),r=s[0];let a=s[1];if((!a||a==="")&&(a=e.id),r===this.localParticipant.sid){p.warn("tried to create RemoteParticipant for local participant");return}const o=this.participants.get(r);if(!o){p.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r));return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),o.addSubscribedMediaTrack(e,a,t,n,c)}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.state!==Y.Disconnected){this.regionUrl=void 0;try{this.participants.forEach(s=>{s.tracks.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.tracks.forEach(s=>{var r,a;s.track&&this.localParticipant.unpublishTrack(s.track,e),e&&((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop())}),this.localParticipant.off(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(A.TrackMuted,this.onLocalTrackMuted).off(A.TrackUnmuted,this.onLocalTrackUnmuted).off(A.LocalTrackPublished,this.onLocalTrackPublished).off(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(A.MediaDevicesError,this.onMediaDevicesError).off(A.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.expWebAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),_e()&&(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(P.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(P.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return g(this,void 0,void 0,function*(){if(typeof this.options.expWebAudioMix!="boolean"&&this.options.expWebAudioMix.audioContext?this.audioContext=this.options.expWebAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=io())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(s){p.warn(s)}this.options.expWebAudioMix&&this.participants.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){let n;return t?n=sn.fromParticipantInfo(this.engine.client,t):n=new sn(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&n.setAudioContext(this.audioContext),n}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const n=this.createParticipant(e,t);return this.participants.set(e,n),this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(P.ParticipantConnected,n),n.on(A.TrackPublished,s=>{this.emitWhenConnected(P.TrackPublished,s,n)}).on(A.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio&&(s.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(P.TrackSubscribed,s,r,n)}).on(A.TrackUnpublished,s=>{this.emit(P.TrackUnpublished,s,n)}).on(A.TrackUnsubscribed,(s,r)=>{this.emit(P.TrackUnsubscribed,s,r,n)}).on(A.TrackSubscriptionFailed,s=>{this.emit(P.TrackSubscriptionFailed,s,n)}).on(A.TrackMuted,s=>{this.emitWhenConnected(P.TrackMuted,s,n)}).on(A.TrackUnmuted,s=>{this.emitWhenConnected(P.TrackUnmuted,s,n)}).on(A.ParticipantMetadataChanged,s=>{this.emitWhenConnected(P.ParticipantMetadataChanged,s,n)}).on(A.ParticipantNameChanged,s=>{this.emitWhenConnected(P.ParticipantNameChanged,s,n)}).on(A.ConnectionQualityChanged,s=>{this.emitWhenConnected(P.ConnectionQualityChanged,s,n)}).on(A.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(P.ParticipantPermissionsChanged,s,n)}).on(A.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionStatusChanged,s,r,n)}).on(A.TrackSubscriptionFailed,(s,r)=>{this.emit(P.TrackSubscriptionFailed,s,n,r)}).on(A.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionPermissionChanged,s,r,n)}),t&&n.updateInfo(t),n}sendSyncState(){var e,t;if(this.engine.subscriber===void 0||this.engine.subscriber.pc.localDescription===null)return;const n=this.engine.subscriber.pc.localDescription,s=this.engine.subscriber.pc.remoteDescription,r=(t=(e=this.connOptions)===null||e===void 0?void 0:e.autoSubscribe)!==null&&t!==void 0?t:!0,a=new Array;this.participants.forEach(o=>{o.tracks.forEach(c=>{c.isDesired!==r&&a.push(c.trackSid)})}),this.engine.client.sendSyncState(new ht({answer:An({sdp:n.sdp,type:n.type}),offer:s?An({sdp:s.sdp,type:s.type}):void 0,subscription:new Je({trackSids:a,subscribe:!r,participantTracks:[]}),publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()}))}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof To&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ve.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,p.warn("detected connection state mismatch",{numFailures:e}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Wt.STATE_MISMATCH))):e=0},Tl)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(P.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===Y.Connected){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.emit(e,...n)}return!1}simulateParticipants(e){var t,n;return g(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 Pi({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:V.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(Y.Connected),s.video){const a=new On(C.Kind.Video,new Pe({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO,name:"video-dummy"}),new Ne(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:yr((t=160*r.aspectRatios[0])!==null&&t!==void 0?t:1,160,!0,!0)));this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}if(s.audio){const a=new On(C.Kind.Audio,new Pe({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO}),new we(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Yn()));this.localParticipant.addTrackPublication(a),this.localParticipant.emit(A.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new De({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:ai.ACTIVE,tracks:[],joinedAt:V.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const u=yr((n=160*r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1,160,!1,!0),d=new Pe({source:se.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO});c.addSubscribedMediaTrack(u,d.sid,new MediaStream([u])),o.tracks=[...o.tracks,d]}if(r.audio){const u=Yn(),d=new Pe({source:se.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO});c.addSubscribedMediaTrack(u,d.sid,new MediaStream([u])),o.tracks=[...o.tracks,d]}c.updateInfo(o)}})}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 e!==P.ActiveSpeakersChanged&&p.debug("room event ".concat(e),{event:e,args:n}),super.emit(e,...n)}}var Ve;(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"})(Ve||(Ve={}));class Ii extends mt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ve.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new So(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return g(this,void 0,void 0,function*(){if(this.status!==Ve.IDLE)throw Error("check is running already");this.setStatus(Ve.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!==Ve.SKIPPED&&this.setStatus(this.isSuccess()?Ve.SUCCESS:Ve.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return g(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 g(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(Ve.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 Co(i){var e,t;return g(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=to(i,ho,fo),s=Un(n),r=navigator.mediaDevices.getUserMedia(s);i.audio&&(be.userMediaPromiseMap.set("audioinput",r),r.catch(()=>be.userMediaPromiseMap.delete("audioinput"))),i.video&&(be.userMediaPromiseMap.set("videoinput",r),r.catch(()=>be.userMediaPromiseMap.delete("videoinput")));const a=yield r;return a.getTracks().map(o=>{const c=o.kind==="audio";c?i.audio:i.video;let u;const d=c?s.audio:s.video;typeof d!="boolean"&&(u=d),u?u.deviceId=o.getSettings().deviceId:u={deviceId:o.getSettings().deviceId};const h=mo(o,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=a,h})})}function Sl(i){return g(this,void 0,void 0,function*(){return(yield Co({audio:!1,video:i}))[0]})}function Cl(i){return g(this,void 0,void 0,function*(){return(yield Co({audio:i,video:!1}))[0]})}class wl extends Ii{get description(){return"Can publish audio"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Cl();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&a.mediaType==="audio"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))})}}class El extends Ii{get description(){return"Can publish video"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Sl();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&a.mediaType==="video"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}}class Pl extends Ii{get description(){return"Resuming connection after interruption"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect();let n=!1,s=!1,r;const a=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 o=t.engine.client.onClose;if(o&&o(""),yield a,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 Rl extends Ii{get description(){return"Can connect via TURN"}perform(){var e,t;return g(this,void 0,void 0,function*(){const n=new Ds,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let u of c.urls)u.startsWith("turn:")?(a=!0,o=!0):u.startsWith("turns:")&&(a=!0,o=!0,r=!0),u.startsWith("stun:")&&(o=!0);o?a&&!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||a?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 _l extends Ii{get description(){return"Establishing WebRTC connection"}perform(){return g(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 a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(Il(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(s,r)},this.room.engine.subscriber&&(this.room.engine.subscriber.pc.onicecandidateerror=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),p.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 Il(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 xl extends Ii{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return g(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 Ds;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)===wi.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 Fl extends mt.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:Ve.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!==Ve.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return g(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),s=a=>{this.updateCheck(t,a)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(xl)})}checkWebRTC(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(_l)})}checkTURN(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Rl)})}checkReconnect(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Pl)})}checkPublishAudio(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(wl)})}checkPublishVideo(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(El)})}}function Al(){const i=document.createElement("style");return i.textContent=`
51
+ `},el=lo,tl=Zd,Zn=tl,Ui=el.parse;const Rr=.7,Si={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _r extends mt.EventEmitter{get pc(){if(this._pc)return this._pc;throw new pe("Expected peer connection to be available")}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Us(n=>{this.emit(Si.NegotiationStarted);try{this.createAndSendOffer()}catch(s){if(n)n(s);else throw s}},100),this._pc=Od()?new RTCPeerConnection(e,t):new RTCPeerConnection(e)}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return g(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 g(this,void 0,void 0,function*(){let n;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=nl(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=Ui((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(o=u.payload,!0):!1),o===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===o){u.config=u.config.split(";").filter(d=>!d.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),n=Zn(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,this.createAndSendOffer()):e.type==="answer"&&(this.emit(Si.NegotiationComplete),e.sdp&&Ui(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Si.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){var t;return g(this,void 0,void 0,function*(){if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(m.debug("restarting ICE"),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"){m.warn("could not createOffer with closed peer connection");return}m.debug("starting to negotiate");const n=yield this.pc.createOffer(e),s=Ui((t=n.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"?Ir(r,[],[]):r.type==="video"&&(il(r),this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(o=u.payload,!0):!1),o===0)return!0;let c=!1;for(const u of r.fmtp)if(u.payload===o){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(a.maxbr*Rr)),u.config.includes("x-google-max-bitrate")||(u.config+=";x-google-max-bitrate=".concat(a.maxbr)),c=!0;break}return c||r.fmtp.push({payload:o,config:"x-google-start-bitrate=".concat(a.maxbr*Rr,";x-google-max-bitrate=").concat(a.maxbr)}),!0}))}),yield this.setMungedSDP(n,Zn(s)),this.onOffer(n)})}createAndSetAnswer(){var e;return g(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),n=Ui((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{s.type==="audio"&&Ir(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Zn(n)),t})}setTrackCodecBitrate(e){this.trackBitrates.push(e)}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)}setMungedSDP(e,t,n){return g(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{m.debug("setting munged ".concat(n?"remote":"local"," description")),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){m.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{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 a={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),m.error("unable to set ".concat(e.type),a),new Ts(r)}})}}function Ir(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 il(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(!$i(r))return;let a=0;((n=i.ext)===null||n===void 0?void 0:n.some(c=>c.uri===pr?!0:(c.value>a&&(a=c.value),!1)))||(s=i.ext)===null||s===void 0||s.push({value:a+1,uri:pr})}function nl(i){var e;const t=[],n=[],s=Ui((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&n.push(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}const sl={audioBitrate:An.music.maxBitrate,audioPreset:An.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ds.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!1},po={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},mo={resolution:Xi.h720.resolution},rl={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qu,disconnectOnPageLeave:!0,expWebAudioMix:!1},go={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},Ar="_lossy",Or="_reliable",al=2*1e3,Lr="leave-reconnect";var xe;(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"})(xe||(xe={}));class ol extends mt.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=go.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=xe.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=t=>{let{channel:n}=t;return g(this,void 0,void 0,function*(){if(n){if(n.label===Or)this.reliableDCSub=n;else if(n.label===Ar)this.lossyDCSub=n;else return;m.debug("on data channel ".concat(n.id,", ").concat(n.label)),n.onmessage=this.handleDataMessage}})},this.handleDataMessage=t=>g(this,void 0,void 0,function*(){var n,s;const r=yield this.dataProcessLock.lock();try{let a;if(t.data instanceof ArrayBuffer)a=t.data;else if(t.data instanceof Blob)a=yield t.data.arrayBuffer();else{m.error("unsupported data type",t.data);return}const o=Ze.fromBinary(new Uint8Array(a));((n=o.value)===null||n===void 0?void 0:n.case)==="speaker"?this.emit(N.ActiveSpeakersUpdate,o.value.value.speakers):((s=o.value)===null||s===void 0?void 0:s.case)==="user"&&this.emit(N.DataPacketReceived,o.value.value,o.kind)}finally{r()}}),this.handleDataError=t=>{const s=t.currentTarget.maxRetransmits===0?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:r}=t.error;m.error("DataChannel error on ".concat(s,": ").concat(t.message),r)}else m.error("Unknown DataChannel error on ".concat(s),t)},this.handleBufferedAmountLow=t=>{const s=t.currentTarget.maxRetransmits===0?le.LOSSY:le.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;m.warn("".concat(t," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=o=>{m.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(o,"ms. giving up")),this.emit(N.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(a===null){s(r);return}t===Lr&&(a=0),m.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ve.setTimeout(()=>this.attemptReconnect(n),a)},this.waitForRestarted=()=>new Promise((t,n)=>{this.pcState===xe.Connected&&t();const s=()=>{this.off(N.Disconnected,r),t()},r=()=>{this.off(N.Restarted,s),n()};this.once(N.Restarted,s),this.once(N.Disconnected,r)}),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);typeof n<"u"&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(N.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=t=>{const n=this.dataChannelForKind(t);if(n)return n.bufferedAmount<=n.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Fe.RR_SIGNAL_DISCONNECTED))},this.client=new Ms,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Wt,this.dataProcessLock=new Wt,this.dcBufferStatus=new Map([[le.LOSSY,!0],[le.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(N.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(N.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(N.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(N.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(N.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(N.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(N.StreamStateChanged,t)}join(e,t,n,s){return g(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.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof ne&&r.reason===1&&(m.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}close(){return g(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.emit(N.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return g(this,void 0,void 0,function*(){this.publisher&&this.publisher.pc.signalingState!=="closed"&&this.publisher.pc.getSenders().forEach(t=>{var n,s;try{!((n=this.publisher)===null||n===void 0)&&n.pc.removeTrack&&((s=this.publisher)===null||s===void 0||s.pc.removeTrack(t))}catch(r){m.warn("could not removeTrack",{error:r})}}),this.publisher&&(this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.hasPublished=!1,this.primaryPC=void 0;const e=t=>{t&&(t.close(),t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return g(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Qe("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 ne("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){var t;if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return(t=this.publisher)===null||t===void 0||t.pc.removeTrack(e),!0}catch(n){m.warn("failed to remove track",{error:n,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return g(this,void 0,void 0,function*(){if(this.primaryPC!==void 0)return cl(this.primaryPC)})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t,n;if(this.publisher||this.subscriber)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(m.debug("E2EE - setting up transports with insertable streams"),s.encodedInsertableStreams=!0);const r={optional:[{googDscp:!0}]};this.publisher=new _r(s,r),this.subscriber=new _r(s),this.emit(N.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=u=>{u.candidate&&(m.trace("adding ICE candidate for peer",u.candidate),this.client.sendIceCandidate(u.candidate,Re.PUBLISHER))},this.subscriber.pc.onicecandidate=u=>{u.candidate&&this.client.sendIceCandidate(u.candidate,Re.SUBSCRIBER)},this.publisher.onOffer=u=>{this.client.sendOffer(u)};let a=this.publisher.pc,o=this.subscriber.pc,c=e.subscriberPrimary;c&&(a=this.subscriber.pc,o=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=a,a.onconnectionstatechange=()=>g(this,void 0,void 0,function*(){if(m.debug("primary PC state changed ".concat(a.connectionState)),a.connectionState==="connected"){const u=this.pcState===xe.New;this.pcState=xe.Connected,u&&this.emit(N.Connected,e)}else a.connectionState==="failed"&&this.pcState===xe.Connected&&(this.pcState=xe.Disconnected,this.handleDisconnect("primary peerconnection",c?Fe.RR_SUBSCRIBER_FAILED:Fe.RR_PUBLISHER_FAILED))}),o.onconnectionstatechange=()=>g(this,void 0,void 0,function*(){m.debug("secondary PC state changed ".concat(o.connectionState)),o.connectionState==="failed"&&this.handleDisconnect("secondary peerconnection",c?Fe.RR_PUBLISHER_FAILED:Fe.RR_SUBSCRIBER_FAILED)}),this.subscriber.pc.ontrack=u=>{this.emit(N.MediaTrackAdded,u.track,u.streams[0],u.receiver)},this.createDataChannels()}setupSignalClientCallbacks(){this.client.onAnswer=e=>g(this,void 0,void 0,function*(){this.publisher&&(m.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState.toString()}),yield this.publisher.setRemoteDescription(e))}),this.client.onTrickle=(e,t)=>{!this.publisher||!this.subscriber||(m.trace("got ICE candidate from peer",{candidate:e,target:t}),t===Re.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>g(this,void 0,void 0,function*(){if(!this.subscriber)return;m.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState.toString()}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{if(m.debug("received trackPublishedResponse",e),!this.pendingTrackResolvers[e.cid]){m.error("missing track resolver for ".concat(e.cid));return}const{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Fe.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(Lr)):(this.emit(N.Disconnected,e==null?void 0:e.reason),this.close()),m.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=Object.assign({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const n=[];e.iceServers.forEach(s=>{const r={urls:s.urls};s.username&&(r.username=s.username),s.credential&&(r.credential=s.credential),n.push(r)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ke.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(Ar,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Or,{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;m.debug("get capabilities",s);const r=[],a=[],o=[];s.codecs.forEach(c=>{const u=c.mimeType.toLowerCase();if(u==="audio/opus"){r.push(c);return}if(!(u==="video/".concat(n))){o.push(c);return}if(n==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(c):a.push(c);return}r.push(c)}),Ad(e)&&e.setCodecPreferences(r.concat(a,o))}createSender(e,t,n){return g(this,void 0,void 0,function*(){if(mr())return yield this.createTransceiverRTCRtpSender(e,t,n);if(gr())return m.warn("using add-track fallback"),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new pe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return g(this,void 0,void 0,function*(){if(mr())return this.createSimulcastTransceiverSender(e,t,n,s);if(gr())return m.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new pe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream);const r={direction:"sendonly",streams:s};n&&(r.sendEncodings=n);const a=yield this.publisher.pc.addTransceiver(e.mediaStreamTrack,r);return e.kind===C.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(a,e.kind,t.videoCodec),e.codec=t.videoCodec),a.sender})}createSimulcastTransceiverSender(e,t,n,s){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.publisher.pc.addTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return this.setPreferredCodec(a,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return g(this,void 0,void 0,function*(){if(!this.publisher)throw new pe("publisher is closed");return this.publisher.pc.addTrack(e)})}attemptReconnect(e){var t,n,s;return g(this,void 0,void 0,function*(){if(!this._isClosed&&!this.attemptingReconnect){(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ke.DISABLED||((s=(n=this.primaryPC)===null||n===void 0?void 0:n.signalingState)!==null&&s!==void 0?s:"closed")==="closed")&&(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 a=!0;r instanceof pe?(m.debug("received unrecoverable error",{error:r}),a=!1):r instanceof fn||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Fe.RR_UNKNOWN):(m.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(N.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){m.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){var t,n,s;return g(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new pe("could not reconnect, url or token not saved");m.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(N.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw m.warn("attempted connection restart, without signal options present"),new fn;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof ne&&a.reason===0?new pe("could not reconnect, token might be expired"):new fn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(N.SignalRestarted,r),yield this.waitForPCReconnected(),(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(N.Restarted)}catch(r){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){var t;return g(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new pe("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new pe("publisher and subscriber connections unset");m.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(N.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.publisher.pc.setConfiguration(s),this.subscriber.pc.setConfiguration(s)}}catch(n){let s="";throw n instanceof Error&&(s=n.message),n instanceof ne&&n.reason===0?new pe("could not reconnect, token might be expired"):new fn(s)}if(this.emit(N.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(N.Resumed)})}waitForPCInitialConnection(e,t){return g(this,void 0,void 0,function*(){if(this.pcState!==xe.Connected){if(this.pcState!==xe.New)throw new pe("Expected peer connection to be new on initial connection");return new Promise((n,s)=>{const r=()=>{m.warn("closing engine"),ve.clearTimeout(o),s(new ne("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&r(),t==null||t.signal.addEventListener("abort",r);const a=()=>{ve.clearTimeout(o),t==null||t.signal.removeEventListener("abort",r),n()},o=ve.setTimeout(()=>{this.off(N.Connected,a),s(new ne("could not establish pc connection"))},e??this.peerConnectionTimeout);this.once(N.Connected,a)})}})}waitForPCReconnected(){var e,t;return g(this,void 0,void 0,function*(){const n=Date.now();let s=n;for(this.pcState=xe.Reconnecting,m.debug("waiting for peer connection to reconnect");s-n<this.peerConnectionTimeout&&this.primaryPC!==void 0;){if(s-n>al&&((e=this.primaryPC)===null||e===void 0?void 0:e.connectionState)==="connected"&&(!this.hasPublished||((t=this.publisher)===null||t===void 0?void 0:t.pc.connectionState)==="connected")&&(this.pcState=xe.Connected),this.pcState===xe.Connected)return;yield si(100),s=Date.now()}throw new ne("could not establish PC connection")})}sendDataPacket(e,t){return g(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,s,r;return g(this,void 0,void 0,function*(){const a=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!a)throw new ne("".concat(o," connection not set"));!t&&!(!((n=this.publisher)===null||n===void 0)&&n.isICEConnected)&&((s=this.publisher)===null||s===void 0?void 0:s.pc.iceConnectionState)!=="checking"&&this.negotiate();const c=this.dataChannelForKind(e,t);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((r=this.dataChannelForKind(e,t))===null||r===void 0?void 0:r.readyState)==="open")return;yield si(50)}throw new ne("could not establish ".concat(o," connection, state: ").concat(a.pc.iceConnectionState))})}ensurePublisherConnected(e){return g(this,void 0,void 0,function*(){yield this.ensureDataTransportConnected(e,!1)})}verifyTransport(){return!(!this.primaryPC||this.primaryPC.connectionState==="closed"||this.primaryPC.connectionState==="failed"||this.hasPublished&&this.subscriberPrimary&&(!this.publisher||this.publisher.pc.connectionState==="closed"||this.publisher.pc.connectionState==="failed")||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise((e,t)=>{if(!this.publisher){t(new Ts("publisher is not defined"));return}this.hasPublished=!0;const n=()=>{m.debug("engine disconnected while negotiation was ongoing"),r(),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(N.Closing,n);const s=setTimeout(()=>{t("negotiation timed out"),this.handleDisconnect("negotiation",Fe.RR_SIGNAL_DISCONNECTED)},this.peerConnectionTimeout),r=()=>{clearTimeout(s),this.off(N.Closing,n)};this.publisher.once(Si.NegotiationStarted,()=>{var a;(a=this.publisher)===null||a===void 0||a.once(Si.NegotiationComplete,()=>{r(),e()})}),this.publisher.once(Si.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(c=>{const u=c.codec.toLowerCase();Dd(u)&&o.set(c.payload,u)}),this.emit(N.RTPVideoMapUpdate,o)}),this.publisher.negotiate(a=>{r(),t(a),a instanceof Ts&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Fe.RR_UNKNOWN)})})}dataChannelForKind(e,t){if(t){if(e===le.LOSSY)return this.lossyDCSub;if(e===le.RELIABLE)return this.reliableDCSub}else{if(e===le.LOSSY)return this.lossyDC;if(e===le.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_e()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){_e()&&window.removeEventListener("online",this.handleBrowserOnLine)}}function cl(i){var e;return g(this,void 0,void 0,function*(){let t="";const n=new Map,s=new Map;if((yield i.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}class fn extends Error{}class Nr{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 Es(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return g(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),m.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return g(this,void 0,void 0,function*(){const t=yield fetch("".concat(ul(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 ne("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function ul(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}const Fs=2e3;function Bn(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 we extends Zi{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.Audio,t,n),this.stopOnMute=!1,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){m.error("could not get audio sender stats",{error:a});return}r&&this.prevStats&&(this._currentBitrate=Bn(r,this.prevStats)),this.prevStats=r}),this.audioContext=s,this.checkForSilence()}setDeviceId(e){return g(this,void 0,void 0,function*(){return this._constraints.deviceId===e?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ri(e)===this.mediaStreamTrack.getSettings().deviceId)})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(m.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==ri(this._constraints.deviceId);return this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(m.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return g(this,void 0,void 0,function*(){let t;if(e){const n=Un({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 g(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){_e()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Fs)))}setProcessor(e){var t;return g(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");if(this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};m.debug("setting up audio processor ".concat(e.name)),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 g(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 g(this,void 0,void 0,function*(){const e=yield Sd(this);return e&&(this.isMuted||m.warn("silence detected on local audio track"),this.emit(R.AudioSilenceDetected)),e})}}function vo(i,e){switch(i.kind){case"audio":return new we(i,e,!1);case"video":return new De(i,e,!1);default:throw new Qe("unsupported track type: ".concat(i.kind))}}const dl=Object.values(Xi),ll=Object.values(Ss),hl=Object.values(Ds),fl=[Xi.h180,Xi.h360],pl=[Ss.h180,Ss.h360],ml=i=>[{scaleResolutionDownBy:2,fps:3}].map(t=>{var n;return new ee(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)/t.fps)))),t.fps,i.encoding.priority)}),Rs=["q","h","f"];function yo(i,e,t,n){var s,r;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,u=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=gl(i,e,t,u),m.debug("using video encoding",a));const d=new ee(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&$i(u)){m.debug("using svc with scalabilityMode ".concat(c));const p=new bo(c),b=[];if(p.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let T=0;T<p.spatial;T+=1)b.push({rid:Rs[2-T],maxBitrate:a.maxBitrate/Math.pow(3,T),maxFramerate:d.encoding.maxFramerate});return b[0].scalabilityMode=c,m.debug("encodings",b),b}if(!o)return[a];let h=[];i?h=(s=Mr(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Dr(i,d):h=(r=Mr(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Dr(i,d);let f;if(h.length>0){const p=h[0];h.length>1&&([,f]=h);const b=Math.max(e,t);if(b>=960&&f)return es(e,t,[p,f,d]);if(b>=480)return es(e,t,[p,d])}return es(e,t,[d])}function xr(i,e,t){var n,s,r,a;if(!t.backupCodec||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&m.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),c=(n=o.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,u=(r=o.height)!==null&&r!==void 0?r:(a=i.dimensions)===null||a===void 0?void 0:a.height;return yo(i.source===C.Source.ScreenShare,c,u,t)}function gl(i,e,t,n){const s=vl(i,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)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 vl(i,e,t){if(i)return hl;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?dl:ll}function Dr(i,e){if(i)return ml(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)?fl:pl}function es(i,e,t){const n=[];if(t.forEach((s,r)=>{if(r>=Rs.length)return;const a=Math.min(i,e),c={rid:Rs[r],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate};s.encoding.maxFramerate&&(c.maxFramerate=s.encoding.maxFramerate);const u=Qi()||r===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),n.push(c)}),ci()&&oo()==="ios"){let s;n.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let r=!0;n.forEach(a=>{var o;a.maxFramerate!=s&&(r&&(r=!1,m.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),m.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(s)),a.maxFramerate=s)})}return n}function Mr(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 bo{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 yl=5e3;class De extends Zi{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;super(e,C.Kind.Video,t,n),this.simulcastCodecs=new Map,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){m.error("could not get audio sender stats",{error:a});return}const r=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;r.forEach((o,c)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);a+=Bn(o,d)}),this._currentBitrate=a}this.prevStats=r}),this.senderLock=new Wt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!_e())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()},Fs))}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,a;return g(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0)r=u.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(d){n={error:d}}finally{try{!o&&!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,a;return g(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0){r=u.value,o=!1;const d=r;yield(a=d.sender)===null||a===void 0?void 0:a.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!o&&!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 g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Camera&&!this.isUserProvided&&(m.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===C.Source.Camera&&!this.isUserProvided&&(m.debug("reacquiring camera track"),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 g(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 a={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},o=n.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t})}setPublishingQuality(e){const t=[];for(let n=ue.LOW;n<=ue.HIGH;n+=1)t.push(new ze({quality:n,enabled:n<=e}));m.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}setDeviceId(e){return g(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ri(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ri(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,n,s,r;return g(this,void 0,void 0,function*(){let a;if(e){const d=Un({video:e});typeof d.video!="boolean"&&(a=d.video)}yield this.restart(a);try{for(var o=!0,c=gi(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;o=!0){r=u.value,o=!1;const d=r;d.sender&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){n={error:d}}finally{try{!o&&!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,a,o,c,u;return g(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 d=!0,h=gi(this.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)o=f.value,d=!1,yield(u=o.sender)===null||u===void 0?void 0:u.replaceTrack(this.processor.processedTrack)}catch(p){r={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(r)throw r.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));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)},yl))}setPublishingCodecs(e){var t,n,s,r,a,o,c;return g(this,void 0,void 0,function*(){if(m.debug("setting publishing codecs",{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=gi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(d.qualities);else{const h=this.simulcastCodecs.get(d.codec);if(m.debug("try setPublishingCodec for ".concat(d.codec),h),!h||!h.sender){for(const f of d.qualities)if(f.enabled){u.push(d.codec);break}}else h.encodings&&(m.debug("try setPublishingLayersForSender ".concat(d.codec)),yield Ur(h.sender,h.encodings,d.qualities,this.senderLock))}}}catch(d){a={error:d}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return u})}setPublishingLayers(e){return g(this,void 0,void 0,function*(){m.debug("setting publishing layers",e),!(!this.sender||!this.encodings)&&(yield Ur(this.sender,this.encodings,e,this.senderLock))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ro()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Ur(i,e,t,n){return g(this,void 0,void 0,function*(){const s=yield n.lock();m.debug("setPublishingLayersForSender",{sender:i,qualities:t,senderEncodings:e});try{const r=i.getParameters(),{encodings:a}=r;if(!a)return;if(a.length!==e.length){m.warn("cannot set publishing layers, encodings mismatch");return}let o=!1;!1&&a[0].scalabilityMode||a.forEach((u,d)=>{var h;let f=(h=u.rid)!==null&&h!==void 0?h:"";f===""&&(f="q");const p=ko(f),b=t.find(T=>T.quality===p);b&&u.active!==b.enabled&&(o=!0,u.active=b.enabled,m.debug("setting layer ".concat(b.quality," to ").concat(u.active?"enabled":"disabled")),Qi()&&(b.enabled?(u.scaleResolutionDownBy=e[d].scaleResolutionDownBy,u.maxBitrate=e[d].maxBitrate,u.maxFrameRate=e[d].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))}),o&&(r.encodings=a,m.debug("setting encodings",r.encodings),yield i.setParameters(r))}finally{s()}})}function ko(i){switch(i){case"f":return ue.HIGH;case"h":return ue.MEDIUM;case"q":return ue.LOW;default:return ue.HIGH}}function Fr(i,e,t,n){if(!t)return[new Te({quality:ue.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new bo(s),a=[];for(let o=0;o<r.spatial;o+=1)a.push(new Te({quality:ue.HIGH-o,width:Math.ceil(i/Math.pow(2,o)),height:Math.ceil(e/Math.pow(2,o)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(3,o)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let u=ko((a=s.rid)!==null&&a!==void 0?a:"");return new Te({quality:u,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}class To extends C{constructor(e,t,n,s){super(e,n),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,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return g(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(),Fs))}}class Hi extends To{constructor(e,t,n,s,r){super(e,t,C.Kind.Audio,n),this.monitorReceiver=()=>g(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=Bn(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;ci()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ci())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return g(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ws(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&ws(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(m.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),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 g(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 ts=100;class Wi extends To{constructor(e,t,n,s){super(e,t,C.Kind.Video,n),this.elementInfos=[],this.monitorReceiver=()=>g(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const r=yield this.getReceiverStats();r&&this.prevStats&&this.receiver&&(this._currentBitrate=Bn(r,this.prevStats)),this.prevStats=r}),this.debouncedHandleResize=Us(()=>{this.updateDimensions()},ts),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?Ti(this._mediaStreamTrack,t):vi(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 bl(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()):m.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream){m.warn("stopObservingElementInfo ignored");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 g(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:"video",framesDecoded:n.framesDecoded,framesDropped:n.framesDropped,framesReceived:n.framesReceived,packetsReceived:n.packetsReceived,packetsLost:n.packetsLost,frameWidth:n.frameWidth,frameHeight:n.frameHeight,pliCount:n.pliCount,firCount:n.firCount,nackCount:n.nackCount,jitter:n.jitter,timestamp:n.timestamp,bytesReceived:n.bytesReceived,decoderImplementation:n.decoderImplementation})}),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 g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,c)=>Math.max(o,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(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-n<ts){ve.setTimeout(()=>{this.updateVisibility()},ts);return}this.lastVisible=a,this.emit(R.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>n+s&&(n=o,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"?vr():t||(vr()>2?2:1)}}class bl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:a}=n;r===this.element&&(this.isIntersecting=a,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??Br(e),this.isPiP=_e()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Br(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,br().observe(this.element),yr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=br())===null||e===void 0||e.unobserve(this.element),(t=yr())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Br(i){let e=i.offsetTop,t=i.offsetLeft;const n=i.offsetWidth,s=i.offsetHeight,{hidden:r}=i,{opacity:a,display:o}=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&&(a!==""?parseFloat(a)>0:!0)&&o!=="none"}class bt extends mt.EventEmitter{constructor(e,t,n){super(),this.metadataMuted=!1,this.encryption=ke.NONE,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},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 isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==ke.NONE}get audioTrack(){if(this.track instanceof we||this.track instanceof Hi)return this.track}get videoTrack(){if(this.track instanceof De||this.track instanceof Wi)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,m.debug("update publication info",{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={}))})(bt||(bt={}));class Ln extends bt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n){super(e,t.sid,t.name),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 g(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return g(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return g(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return g(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var ni;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Unknown="unknown"})(ni||(ni={}));function kl(i){switch(i){case ei.EXCELLENT:return ni.Excellent;case ei.GOOD:return ni.Good;case ei.POOR:return ni.Poor;default:return ni.Unknown}}class So extends mt.EventEmitter{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every(e=>e.isEncrypted)}constructor(e,t,n,s){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ni.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(C.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(C.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrack(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,m.trace("update participant info",{info:e}),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(L.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(L.ParticipantNameChanged,e)}setPermissions(e){var t,n,s,r,a;const o=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!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])});return this.permissions=e,c&&this.emit(L.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=kl(e),t!==this._connectionQuality&&this.emit(L.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach(t=>(t.track instanceof Hi||t.track instanceof we)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case C.Kind.Video:this.videoTracks.set(e.trackSid,e);break}}}function Tl(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 dt({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 Co extends bt{constructor(e,t,n){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ue.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(R.Ended,s)},this.handleVisibilityChange=s=>{m.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),{trackSid:this.trackSid}),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{m.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),{trackSid:this.trackSid}),this.videoDimensions=s,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 it({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bt.SubscriptionStatus.Unsubscribed:super.isSubscribed?bt.SubscriptionStatus.Subscribed:bt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bt.PermissionStatus.Allowed:bt.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 Wi&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof Wi&&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?(m.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):this.isDesired?!0:(m.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof Wi&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new at({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=ue.HIGH,this.emit(R.UpdateSettings,e)}}class en extends So{static fromParticipantInfo(e,t){return new en(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,n,s,r){super(t,n||"",s,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(R.UpdateSettings,t=>{m.debug("send update settings",t),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(L.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(L.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(L.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(L.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(L.TrackSubscriptionFailed,e.trackSid,t)})}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(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.getTrack(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.getTrack(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,a){let o=this.getTrackPublication(t);if(o||t.startsWith("TR")||this.tracks.forEach(d=>{!o&&e.kind===d.kind.toString()&&(o=d)}),!o){if(a===0){m.error("could not find published track",{participant:this.sid,trackSid:t}),this.emit(L.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,a-1)},150);return}if(e.readyState==="ended"){m.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),this.emit(L.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let u;return c?u=new Wi(e,t,s,r):u=new Hi(e,t,s,this.audioContext,this.audioOutput),u.source=o.source,u.isMuted=o.isMuted,u.setMediaStream(n),u.start(),o.setTrack(u),this.volumeMap.has(o.source)&&u instanceof Hi&&u.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r;let a=this.getTrackPublication(s.sid);if(a)a.updateInfo(s);else{const o=C.kindFromProto(s.type);if(!o)return;a=new Co(o,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe),a.updateInfo(s),n.set(s.sid,a);const c=Array.from(this.tracks.values()).find(u=>u.source===(a==null?void 0:a.source));c&&a.source!==C.Source.Unknown&&m.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),{oldTrack:c,newTrack:a,participant:this,participantInfo:e}),this.addTrackPublication(a)}t.set(s.sid,a)}),this.tracks.forEach(s=>{t.has(s.trackSid)||(m.trace("detected removed track on remote participant, unpublishing",{publication:s,participantSid:this.sid}),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(L.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.tracks.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.tracks.delete(e),n.kind){case C.Kind.Audio:this.audioTracks.delete(e);break;case C.Kind.Video:this.videoTracks.delete(e);break}t&&this.emit(L.TrackUnpublished,n)}setAudioOutput(e){return g(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach(n=>{var s;n.track instanceof Hi&&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 m.trace("participant event",{participant:this.sid,event:e,args:n}),super.emit(e,...n)}}class Jr extends So{constructor(e,t,n,s){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ke.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new uo)},this.handleReconnected=()=>{var r,a;(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.resolve)===null||a===void 0||a.call(r),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>m.warn(o)),(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{m.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(r=>Tl(r)))},this.onTrackUnmuted=r=>{this.onTrackMuted(r,r.isUpstreamPaused)},this.onTrackMuted=(r,a)=>{if(a===void 0&&(a=!0),!r.sid){m.error("could not update mute status for unpublished track",r);return}this.engine.updateMuteStatus(r.sid,a)},this.onTrackUpstreamPaused=r=>{m.debug("upstream paused"),this.onTrackMuted(r,!0)},this.onTrackUpstreamResumed=r=>{m.debug("upstream resumed"),this.onTrackMuted(r,r.isMuted)},this.handleSubscribedQualityUpdate=r=>g(this,void 0,void 0,function*(){var a,o,c,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTracks.get(r.trackSid);if(!f){m.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid: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,b=gi(w),T;T=yield b.next(),a=T.done,!a;p=!0){u=T.value,p=!1;const _=u;kd(_)&&(m.debug("publish ".concat(_," for ").concat(f.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(f.videoTrack,_,f.options))}}catch(_){o={error:_}}finally{try{!p&&!a&&(c=b.return)&&(yield c.call(b))}finally{if(o)throw o.error}}}else r.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(r.subscribedQualities))}),this.handleLocalTrackUnpublished=r=>{const a=this.tracks.get(r.trackSid);if(!a){m.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:r.trackSid});return}this.unpublishTrack(a.track)},this.handleTrackEnded=r=>g(this,void 0,void 0,function*(){if(r.source===C.Source.ScreenShare||r.source===C.Source.ScreenShareAudio)m.debug("unpublishing local track due to TrackEnded",{track:r.sid}),this.unpublishTrack(r);else if(r.isUserProvided)yield r.mute();else if(r instanceof we||r instanceof De)try{if(_e())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:r.source===C.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw m.warn("user has revoked access to ".concat(r.source)),a.onchange=()=>{a.state!=="denied"&&(r.isMuted||r.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}r.isMuted||(m.debug("track ended, attempting to use a different device"),yield r.restartTrack())}catch{m.warn("could not restart track, muting instead"),yield r.mute()}}),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=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!==ke.NONE}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.client.onRemoteMuteChanged=(t,n)=>{const s=this.tracks.get(t);!s||!s.track||(n?s.mute():s.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(N.Connected,this.handleReconnected).on(N.SignalRestarted,this.handleReconnected).on(N.SignalResumed,this.handleReconnected).on(N.Restarting,this.handleReconnecting).on(N.Resuming,this.handleReconnecting).on(N.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(L.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return g(this,void 0,void 0,function*(){this.encryptionType=e?ke.GCM:ke.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){var r,a;return g(this,void 0,void 0,function*(){m.debug("setTrackEnabled",{source:e,enabled:t});let o=this.getTrack(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){m.info("skipping duplicate published source",{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:(a=n)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Qe(e)}const u=[];for(const h of c)m.info("publishing track",{localTrack:h}),u.push(this.publishTrack(h,s));[o]=yield Promise.all(u)}catch(u){throw c==null||c.forEach(d=>{d.stop()}),u instanceof Error&&!(u instanceof Qe)&&this.emit(L.MediaDevicesError,u),u}finally{this.pendingPublishing.delete(e)}}else if(o&&o.track)if(e===C.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrack(C.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return g(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 g(this,void 0,void 0,function*(){const s=no(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),r=Un(s);let a;try{a=yield navigator.mediaDevices.getUserMedia(r)}catch(o){throw o instanceof Error&&(r.audio&&(this.microphoneError=o),r.video&&(this.cameraError=o)),o}return r.audio&&(this.microphoneError=void 0),r.video&&(this.cameraError=void 0),a.getTracks().map(o=>{const c=o.kind==="audio";c?e.audio:e.video;let u;const d=c?r.audio:r.video;typeof d!="boolean"&&(u=d);const h=vo(o,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=a,h})})}createScreenTracks(e){return g(this,void 0,void 0,function*(){if(e===void 0&&(e={}),e.resolution===void 0&&(e.resolution=Ds.h1080fps15.resolution),navigator.mediaDevices.getDisplayMedia===void 0)throw new xs("getDisplayMedia not supported");const t=wd(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new Qe("no video track found");const r=new De(s[0],void 0,!1);r.source=C.Source.ScreenShare;const a=[r];if(n.getAudioTracks().length>0){const o=new we(n.getAudioTracks()[0],void 0,!1,this.audioContext);o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){var n,s,r,a;return g(this,void 0,void 0,function*(){yield(n=this.reconnectFuture)===null||n===void 0?void 0:n.promise,e instanceof Zi&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let o;if(e instanceof MediaStreamTrack)o=e.getConstraints();else{o=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)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(p)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new we(e,o,!0,this.audioContext);break;case"video":e=new De(e,o,!0);break;default:throw new Qe("unsupported MediaStreamTrack kind ".concat(e.kind))}e instanceof we&&e.setAudioContext(this.audioContext);let c;if(this.tracks.forEach(p=>{p.track&&p.track===e&&(c=p)}),c)return m.warn("track has already been published, skipping"),c;const u="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,d=(s=t==null?void 0:t.forceStereo)!==null&&s!==void 0?s:u;d&&(t||(t={}),t.dtx===void 0&&m.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),t.red===void 0&&m.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),(a=t.red)!==null&&a!==void 0||(t.red=!1));const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Fn()&&this.roomOptions.e2ee&&(m.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),h.simulcast=!1),h.source&&(e.source=h.source);const f=this.publish(e,h,d);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,a,o,c,u,d,h,f,p,b,T,w,_;return g(this,void 0,void 0,function*(){const M=Array.from(this.tracks.values()).find(F=>e instanceof Zi&&F.source===e.source);if(M&&e.source!==C.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(F){F instanceof Error&&m.warn(F.message,{oldTrack:M,newTrack:e,trace:F.stack})}t.stopMicTrackOnMute&&e instanceof we&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&Qi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Rd()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!_d()&&(t.videoCodec=void 0),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 Q=new qe({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)});let j,he;if(e.kind===C.Kind.Video){let F={width:0,height:0};try{F=yield e.waitForDimensions()}catch{const Ie=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Xi.h720.resolution;F={width:Ie.width,height:Ie.height},m.error("could not determine track dimensions, using defaults",F)}if(Q.width=F.width,Q.height=F.height,e instanceof De)if($i(t.videoCodec)&&(t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),t.videoCodec&&t.backupCodec&&t.videoCodec!==t.backupCodec.codec){this.roomOptions.dynacast||(this.roomOptions.dynacast=!0);const fe=Object.assign({},t);fe.simulcast=!0,he=xr(e,t.backupCodec.codec,fe),Q.simulcastCodecs=[new Be({codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0}),new Be({codec:t.backupCodec.codec,cid:"",enableSimulcastLayers:!0})]}else t.videoCodec&&(Q.simulcastCodecs=[new Be({codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:(u=t.simulcast)!==null&&u!==void 0?u:!1})]);j=yo(e.source===C.Source.ScreenShare,F.width,F.height,t),Q.layers=Fr(Q.width,Q.height,j,$i(t.videoCodec))}else e.kind===C.Kind.Audio&&(j=[{maxBitrate:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate)!==null&&h!==void 0?h:t.audioBitrate,priority:(p=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high",networkPriority:(T=(b=t.audioPreset)===null||b===void 0?void 0:b.priority)!==null&&T!==void 0?T:"high"}]);if(!this.engine||this.engine.isClosed)throw new pe("cannot publish track when not connected");const ae=yield this.engine.addTrack(Q);let q=!1,K=!1;if(ae.codecs.forEach(F=>{fr(F.mimeType,t.videoCodec)?q=!0:t.backupCodec&&fr(F.mimeType,t.backupCodec.codec)&&(K=!0)}),Q.simulcastCodecs.length>0){if(!q&&!K)throw Error("cannot publish track, codec not supported by server");if(!q&&t.backupCodec){const F=t.backupCodec;t=Object.assign({},t),m.debug("primary codec ".concat(t.videoCodec," not supported, fallback to ").concat(F.codec)),t.videoCodec=F.codec,t.videoEncoding=F.encoding,j=he}}const A=new Ln(e.kind,ae,e);if(A.options=t,e.sid=ae.sid,!this.engine.publisher)throw new pe("publisher is closed");if(m.debug("publishing ".concat(e.kind," with encodings"),{encodings:j,trackInfo:ae}),e.sender=yield this.engine.createSender(e,t,j),j)if(Qi()&&e.kind===C.Kind.Audio){let F;for(const fe of this.engine.publisher.pc.getTransceivers())if(fe.sender===e.sender){F=fe;break}F&&this.engine.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((w=j[0])===null||w===void 0)&&w.maxBitrate?j[0].maxBitrate/1e3:0})}else e.codec&&$i(e.codec)&&(!((_=j[0])===null||_===void 0)&&_.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:Q.cid,codec:e.codec,maxbr:j[0].maxBitrate/1e3});return yield this.engine.negotiate(),e instanceof De?e.startMonitor(this.engine.client):e instanceof we&&e.startMonitor(),this.addTrackPublication(A),this.emit(L.LocalTrackPublished,A),A})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var s;return g(this,void 0,void 0,function*(){let r;if(this.tracks.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new Qe("track is not published");if(!(e instanceof De))throw new Qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),o=xr(e,t,a);if(!o){m.info("backup codec has been disabled, ignoring request to add additional codec for track");return}const c=e.addSimulcastTrack(t,o),u=new qe({cid:c.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id,enableSimulcastLayers:a.simulcast}]});if(u.layers=Fr(u.width,u.height,o),!this.engine||this.engine.isClosed)throw new pe("cannot publish track when not connected");const d=yield this.engine.addTrack(u);yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate(),m.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:d})})}unpublishTrack(e,t){var n,s;return g(this,void 0,void 0,function*(){const r=this.getPublicationForTrack(e);if(m.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!r||!r.track){m.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});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 o=e.sender;if(e.sender=void 0,this.engine.publisher&&this.engine.publisher.pc.connectionState!=="closed"&&o)try{for(const c of this.engine.publisher.pc.getTransceivers())c.sender===o&&(c.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),e instanceof De){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(a=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){m.warn("failed to unpublish track",{error:c,method:"unpublishTrack"})}switch(this.tracks.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTracks.delete(r.trackSid);break;case C.Kind.Video:this.videoTracks.delete(r.trackSid);break}return this.emit(L.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return g(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>n instanceof Ln)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return g(this,void 0,void 0,function*(){const n=[];this.tracks.forEach(s=>{s.track&&(e&&(s.options=Object.assign(Object.assign({},s.options),e)),n.push(s))}),yield Promise.all(n.map(s=>g(this,void 0,void 0,function*(){const r=s.track;yield this.unpublishTrack(r,!1),t&&!r.isMuted&&(r instanceof we||r instanceof De)&&!r.isUserProvided&&(m.debug("restarting existing track",{track:s.trackSid}),yield r.restartTrack()),yield this.publishTrack(r,s.options)})))})}publishData(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return g(this,void 0,void 0,function*(){const s=Array.isArray(n)?n:n==null?void 0:n.destination,r=[],a=Array.isArray(n)?void 0:n.topic;s!==void 0&&s.forEach(c=>{c instanceof en?r.push(c.sid):r.push(c)});const o=new Ze({kind:t,value:{case:"user",value:new tt({participantSid:this.sid,payload:e,destinationSids:r,topic:a})}});yield this.engine.sendDataPacket(o,t)})}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,s;const r=this.tracks.get(t.sid);if(r){const a=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(m.debug("updating server mute state after reconcile",{sid:t.sid,muted:a}),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.tracks.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(s instanceof we||s instanceof De)&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}publishedTracksInfo(){const e=[];return this.tracks.forEach(t=>{t.track!==void 0&&e.push(new Ge({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new ft({label:n.label,id:n.id,target:s}))};return t(this.engine.dataChannelForKind(le.LOSSY),Re.PUBLISHER),t(this.engine.dataChannelForKind(le.RELIABLE),Re.PUBLISHER),t(this.engine.dataChannelForKind(le.LOSSY,!0),Re.SUBSCRIBER),t(this.engine.dataChannelForKind(le.RELIABLE,!0),Re.SUBSCRIBER),e}}var Y;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting"})(Y||(Y={}));const Sl=2*1e3;class wo extends mt.EventEmitter{constructor(e){var t,n;super(),t=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.connect=(s,r,a)=>g(this,void 0,void 0,function*(){var o;const c=yield this.disconnectLock.lock();if(this.state===Y.Connected)return m.info("already connected to room ".concat(this.name)),c(),Promise.resolve();if(this.connectFuture)return c(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),((o=this.regionUrlProvider)===null||o===void 0?void 0:o.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Es(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Nr(s,r):this.regionUrlProvider.updateToken(r),this.regionUrlProvider.fetchRegionSettings().catch(h=>{m.warn("could not fetch region settings",{error:h})}));const u=(h,f,p)=>g(this,void 0,void 0,function*(){var b;this.abortController&&this.abortController.abort();const T=new AbortController;this.abortController=T,c==null||c();try{yield this.attemptConnection(p??s,r,a,T),this.abortController=void 0,h()}catch(w){if(this.regionUrlProvider&&w instanceof ne&&w.reason!==3&&w.reason!==0){let _=null;try{_=yield this.regionUrlProvider.getNextBestRegionUrl((b=this.abortController)===null||b===void 0?void 0:b.signal)}catch(M){if(M instanceof ne&&(M.status===401||M.reason===3)){f(M);return}}_?(m.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(_)),yield u(h,f,_)):f(w)}else f(w)}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new uo((h,f)=>{u(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,r,a,o,c,u)=>g(this,void 0,void 0,function*(){const d=yield a.join(s,r,{autoSubscribe:o.autoSubscribe,publishOnly:o.publishOnly,adaptiveStream:typeof c.adaptiveStream=="object"?!0:c.adaptiveStream,maxRetries:o.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:o.websocketTimeout},u.signal);let h=d.serverInfo;if(h||(h={version:d.serverVersion,region:d.serverRegion}),m.debug("connected to Livekit Server ".concat(Object.entries(h).map(f=>{let[p,b]=f;return"".concat(p,": ").concat(b)}).join(", "))),!d.serverVersion)throw new fd("unknown server version");return d.serverVersion==="0.15.1"&&this.options.dynacast&&(m.debug("disabling dynacast due to server version"),c.dynacast=!1),d}),this.applyJoinResponse=s=>{const r=s.participant;this.localParticipant.sid=r.sid,this.localParticipant.identity=r.identity,this.handleParticipantUpdates([r,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(s.sifTrailer)},this.attemptConnection=(s,r,a,o)=>g(this,void 0,void 0,function*(){var c,u;this.state===Y.Reconnecting?(m.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),!((c=this.regionUrlProvider)===null||c===void 0)&&c.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},go),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,r,this.engine,this.connOptions,this.options,o);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected)}catch(d){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const h=new ne("could not establish signal connection");throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof ne&&(h.reason=d.reason,h.status=d.status),m.debug("error trying to establish signal connection",{error:d}),h}if(o.signal.aborted)throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),new ne("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,o)}catch(d){throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),d}_e()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_e()&&(document.addEventListener("freeze",this.onPageLeave),(u=navigator.mediaDevices)===null||u===void 0||u.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(Y.Connected),this.emit(P.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return g(t,void 0,void 0,function*(){var r,a,o,c;const u=yield this.disconnectLock.lock();try{if(this.state===Y.Disconnected){m.debug("already disconnected");return}m.info("disconnect from room",{identity:this.localParticipant.identity}),(this.state===Y.Connecting||this.state===Y.Reconnecting)&&(m.warn("abort connection attempt"),(r=this.abortController)===null||r===void 0||r.abort(),(o=(a=this.connectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,new ne("Client initiated disconnect")),this.connectFuture=void 0),!((c=this.engine)===null||c===void 0)&&c.client.isConnected&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(s,Ht.CLIENT_INITIATED),this.engine=void 0}finally{u()}})},this.onPageLeave=()=>g(this,void 0,void 0,function*(){yield this.disconnect()}),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const s of this.participants.values())this.handleParticipantDisconnected(s.sid,s);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(P.Reconnecting)},this.handleSignalRestarted=s=>g(this,void 0,void 0,function*(){m.debug("signal reconnected to server",{region:s.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(s);try{const r=[];this.localParticipant.tracks.forEach(a=>{a.track&&r.push(a)}),yield Promise.all(r.map(a=>g(this,void 0,void 0,function*(){const o=a.track;this.localParticipant.unpublishTrack(o,!1),o.isMuted||((o instanceof we||o instanceof De)&&o.source!==C.Source.ScreenShare&&o.source!==C.Source.ScreenShareAudio&&!o.isUserProvided&&(m.debug("restarting existing track",{track:a.trackSid}),yield o.restartTrack()),m.debug("publishing new track",{track:a.trackSid}),yield this.localParticipant.publishTrack(o,a.options))})))}catch(r){m.error("error trying to re-publish tracks after reconnection",{error:r})}try{yield this.engine.waitForRestarted(),m.debug("fully reconnected to server",{region:s.serverRegion})}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.participants.forEach(r=>{this.emit(P.ParticipantConnected,r)})}),this.handleParticipantUpdates=s=>{s.forEach(r=>{if(r.identity===this.localParticipant.identity){this.localParticipant.updateInfo(r);return}const a=this.identityToSid.get(r.identity);a&&a!==r.sid&&this.handleParticipantDisconnected(a,this.participants.get(a));let o=this.participants.get(r.sid);const c=!o;r.state===ai.DISCONNECTED?this.handleParticipantDisconnected(r.sid,o):(o=this.getOrCreateParticipant(r.sid,r),c||o.updateInfo(r))})},this.handleActiveSpeakersUpdate=s=>{const r=[],a={};s.forEach(o=>{if(a[o.sid]=!0,o.sid===this.localParticipant.sid)this.localParticipant.audioLevel=o.level,this.localParticipant.setIsSpeaking(!0),r.push(this.localParticipant);else{const c=this.participants.get(o.sid);c&&(c.audioLevel=o.level,c.setIsSpeaking(!0),r.push(c))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach(o=>{a[o.sid]||(o.audioLevel=0,o.setIsSpeaking(!1))}),this.activeSpeakers=r,this.emitWhenConnected(P.ActiveSpeakersChanged,r)},this.handleSpeakersChanged=s=>{const r=new Map;this.activeSpeakers.forEach(o=>{r.set(o.sid,o)}),s.forEach(o=>{let c=this.participants.get(o.sid);o.sid===this.localParticipant.sid&&(c=this.localParticipant),c&&(c.audioLevel=o.level,c.setIsSpeaking(o.active),o.active?r.set(o.sid,c):r.delete(o.sid))});const a=Array.from(r.values());a.sort((o,c)=>c.audioLevel-o.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(P.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(r=>{const a=this.participants.get(r.participantSid);if(!a)return;const o=a.getTrackPublication(r.trackSid);!o||!o.track||(o.track.streamState=C.streamStateFromProto(r.state),a.emit(L.TrackStreamStateChanged,o,o.track.streamState),this.emitWhenConnected(P.TrackStreamStateChanged,o,o.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const r=this.participants.get(s.participantSid);if(!r)return;const a=r.getTrackPublication(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const r=Array.from(this.participants.values()).find(o=>o.tracks.has(s.trackSid));if(!r)return;const a=r.getTrackPublication(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=(s,r)=>{const a=this.participants.get(s.participantSid);this.emit(P.DataReceived,s.payload,a,r,s.topic),a==null||a.emit(L.DataReceived,s.payload,r)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(P.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{m.warn("could not playback audio",s),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(P.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>g(this,void 0,void 0,function*(){this.emit(P.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const r=this.roomInfo;this.roomInfo=s,r&&r.metadata!==s.metadata&&this.emitWhenConnected(P.RoomMetadataChanged,s.metadata),(r==null?void 0:r.activeRecording)!==s.activeRecording&&this.emitWhenConnected(P.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(r=>{if(r.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(r.quality);return}const a=this.participants.get(r.participantSid);a&&a.setConnectionQuality(r.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(P.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(P.ParticipantNameChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(P.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(P.TrackUnmuted,s,this.localParticipant)},this.onLocalTrackPublished=s=>g(this,void 0,void 0,function*(){var r;this.emit(P.LocalTrackPublished,s,this.localParticipant),s.track instanceof we&&(yield s.track.checkForSilence())&&this.emit(P.LocalAudioSilenceDetected,s);const a=yield(r=s.track)===null||r===void 0?void 0:r.getDeviceId(),o=Cd(s.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(P.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=s=>{this.emit(P.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalConnectionQualityChanged=s=>{this.emit(P.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(P.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(P.ParticipantPermissionsChanged,s,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},rl),e),this.options.audioCaptureDefaults=Object.assign(Object.assign({},po),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},mo),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sl),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Wt,this.localParticipant=new Jr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ri(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ri(this.options.audioCaptureDefaults.deviceId)),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&this.switchActiveDevice("audiooutput",ri(this.options.audioOutput.deviceId)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return g(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 zd(this.options.e2ee),this.e2eeManager.on(Zt.ParticipantEncryptionStatusChanged,(t,n)=>{n instanceof Jr&&(this.isE2EEEnabled=t),this.emit(P.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Zt.EncryptionError,t=>this.emit(P.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}get sid(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.sid)!==null&&t!==void 0?t:""}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 ol(this.options),this.engine.on(N.ParticipantUpdate,this.handleParticipantUpdates).on(N.RoomUpdate,this.handleRoomUpdate).on(N.SpeakersChanged,this.handleSpeakersChanged).on(N.StreamStateChanged,this.handleStreamStateUpdate).on(N.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(N.SubscriptionError,this.handleSubscriptionError).on(N.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(N.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(N.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(N.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(N.DataPacketReceived,this.handleDataPacket).on(N.Resuming,()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(P.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())}).on(N.Resumed,()=>{this.setAndEmitConnectionState(Y.Connected),this.emit(P.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions(),Array.from(this.participants.values()).filter(t=>!this.cachedParticipantSids.includes(t.sid)).forEach(t=>this.emit(P.ParticipantConnected,t)),this.cachedParticipantSids=[]}).on(N.SignalResumed,()=>{this.state===Y.Reconnecting&&this.sendSyncState()}).on(N.Restarting,this.handleRestarting).on(N.SignalRestarted,this.handleSignalRestarted).on(N.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 be.getInstance().getDevices(e,t)}prepareConnection(e,t){return g(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){m.debug("prepareConnection to ".concat(e));try{if(Es(new URL(e))&&t){this.regionUrlProvider=new Nr(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(Tr(n),{method:"HEAD"}),m.debug("prepared connection to ".concat(n)))}else yield fetch(Tr(e),{method:"HEAD"})}catch(n){m.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);if(t)return this.participants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return g(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"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=()=>g(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new je({reason:Ht.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&&(this.engine.client.sendSimulateScenario(s),n())})}startAudio(){return g(this,void 0,void 0,function*(){const e=[],t=Ri();if(t&&t.os==="iOS"){const n="livekit-dummy-audio-el";let s=document.getElementById(n);if(!s){s=document.createElement("audio"),s.id=n,s.autoplay=!0,s.hidden=!0;const r=Xn();r.enabled=!0;const a=new MediaStream([r]);s.srcObject=a,document.addEventListener("visibilitychange",()=>{s&&(s.srcObject=document.hidden?null:a)}),document.body.append(s),this.once(P.Disconnected,()=>{s==null||s.remove()})}e.push(s)}this.participants.forEach(n=>{n.audioTracks.forEach(s=>{s.track&&s.track.attachedElements.forEach(r=>{e.push(r)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(n=>(n.muted=!1,n.play()))]),this.handleAudioPlaybackStarted()}catch(n){throw this.handleAudioPlaybackFailed(n),n}})}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return(t=(e=this.options.audioOutput)===null||e===void 0?void 0:e.deviceId)!==null&&t!==void 0?t:""}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,a;return g(this,void 0,void 0,function*(){let o=!1,c=!0;const u=n?{exact:t}:t;if(e==="audioinput"){const d=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=u,o=d!==u;const h=Array.from(this.localParticipant.audioTracks.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=d,f}}else if(e==="videoinput"){const d=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=u,o=d!==u;const h=Array.from(this.localParticipant.videoTracks.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=d,f}}else if(e==="audiooutput"){if(!ws()&&!this.options.expWebAudioMix||this.options.expWebAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");(s=(a=this.options).audioOutput)!==null&&s!==void 0||(a.audioOutput={});const d=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,o=d!==u;try{this.options.expWebAudioMix?(r=this.audioContext)===null||r===void 0||r.setSinkId(t):yield Promise.all(Array.from(this.participants.values()).map(h=>h.setAudioOutput({deviceId:t})))}catch(h){throw this.options.audioOutput.deviceId=d,h}}return o&&c&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(P.ActiveDeviceChanged,e,t)),c})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),d()},d=()=>{this.off(P.Reconnected,u),this.off(P.Connected,u),this.off(P.Disconnected,d)};this.once(P.Reconnected,u),this.once(P.Connected,u),this.once(P.Disconnected,d);return}if(this.state===Y.Disconnected){m.warn("skipping incoming track after Room disconnected");return}const s=Pd(t.id),r=s[0];let a=s[1];if((!a||a==="")&&(a=e.id),r===this.localParticipant.sid){m.warn("tried to create RemoteParticipant for local participant");return}const o=this.participants.get(r);if(!o){m.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r));return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),o.addSubscribedMediaTrack(e,a,t,n,c)}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.state!==Y.Disconnected){this.regionUrl=void 0;try{this.participants.forEach(s=>{s.tracks.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.tracks.forEach(s=>{var r,a;s.track&&this.localParticipant.unpublishTrack(s.track,e),e&&((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop())}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.expWebAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),_e()&&(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(P.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(P.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return g(this,void 0,void 0,function*(){if(typeof this.options.expWebAudioMix!="boolean"&&this.options.expWebAudioMix.audioContext?this.audioContext=this.options.expWebAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=so())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(s){m.warn(s)}this.options.expWebAudioMix&&this.participants.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){let n;return t?n=en.fromParticipantInfo(this.engine.client,t):n=new en(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&n.setAudioContext(this.audioContext),n}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const n=this.createParticipant(e,t);return this.participants.set(e,n),this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(P.ParticipantConnected,n),n.on(L.TrackPublished,s=>{this.emitWhenConnected(P.TrackPublished,s,n)}).on(L.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio&&(s.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(P.TrackSubscribed,s,r,n)}).on(L.TrackUnpublished,s=>{this.emit(P.TrackUnpublished,s,n)}).on(L.TrackUnsubscribed,(s,r)=>{this.emit(P.TrackUnsubscribed,s,r,n)}).on(L.TrackSubscriptionFailed,s=>{this.emit(P.TrackSubscriptionFailed,s,n)}).on(L.TrackMuted,s=>{this.emitWhenConnected(P.TrackMuted,s,n)}).on(L.TrackUnmuted,s=>{this.emitWhenConnected(P.TrackUnmuted,s,n)}).on(L.ParticipantMetadataChanged,s=>{this.emitWhenConnected(P.ParticipantMetadataChanged,s,n)}).on(L.ParticipantNameChanged,s=>{this.emitWhenConnected(P.ParticipantNameChanged,s,n)}).on(L.ConnectionQualityChanged,s=>{this.emitWhenConnected(P.ConnectionQualityChanged,s,n)}).on(L.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(P.ParticipantPermissionsChanged,s,n)}).on(L.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionStatusChanged,s,r,n)}).on(L.TrackSubscriptionFailed,(s,r)=>{this.emit(P.TrackSubscriptionFailed,s,n,r)}).on(L.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(P.TrackSubscriptionPermissionChanged,s,r,n)}),t&&n.updateInfo(t),n}sendSyncState(){var e,t;if(this.engine.subscriber===void 0||this.engine.subscriber.pc.localDescription===null)return;const n=this.engine.subscriber.pc.localDescription,s=this.engine.subscriber.pc.remoteDescription,r=(t=(e=this.connOptions)===null||e===void 0?void 0:e.autoSubscribe)!==null&&t!==void 0?t:!0,a=new Array;this.participants.forEach(o=>{o.tracks.forEach(c=>{c.isDesired!==r&&a.push(c.trackSid)})}),this.engine.client.sendSyncState(new ht({answer:On({sdp:n.sdp,type:n.type}),offer:s?On({sdp:s.sdp,type:s.type}):void 0,subscription:new Je({trackSids:a,subscribe:!r,participantTracks:[]}),publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()}))}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof Co&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ve.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,m.warn("detected connection state mismatch",{numFailures:e}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ht.STATE_MISMATCH))):e=0},Sl)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(P.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===Y.Connected){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.emit(e,...n)}return!1}simulateParticipants(e){var t,n;return g(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 Ei({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:V.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Me({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(P.SignalConnected),this.emit(P.Connected),this.setAndEmitConnectionState(Y.Connected),s.video){const a=new Ln(C.Kind.Video,new Pe({source:re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO,name:"video-dummy"}),new De(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:kr((t=160*r.aspectRatios[0])!==null&&t!==void 0?t:1,160,!0,!0)));this.localParticipant.addTrackPublication(a),this.localParticipant.emit(L.LocalTrackPublished,a)}if(s.audio){const a=new Ln(C.Kind.Audio,new Pe({source:re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO}),new we(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Xn()));this.localParticipant.addTrackPublication(a),this.localParticipant.emit(L.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new Me({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:ai.ACTIVE,tracks:[],joinedAt:V.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const u=kr((n=160*r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1,160,!1,!0),d=new Pe({source:re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO});c.addSubscribedMediaTrack(u,d.sid,new MediaStream([u])),o.tracks=[...o.tracks,d]}if(r.audio){const u=Xn(),d=new Pe({source:re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ge.AUDIO});c.addSubscribedMediaTrack(u,d.sid,new MediaStream([u])),o.tracks=[...o.tracks,d]}c.updateInfo(o)}})}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 e!==P.ActiveSpeakersChanged&&m.debug("room event ".concat(e),{event:e,args:n}),super.emit(e,...n)}}var Ve;(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"})(Ve||(Ve={}));class _i extends mt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ve.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new wo(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return g(this,void 0,void 0,function*(){if(this.status!==Ve.IDLE)throw Error("check is running already");this.setStatus(Ve.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!==Ve.SKIPPED&&this.setStatus(this.isSuccess()?Ve.SUCCESS:Ve.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return g(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 g(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(Ve.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 Eo(i){var e,t;return g(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=no(i,po,mo),s=Un(n),r=navigator.mediaDevices.getUserMedia(s);i.audio&&(be.userMediaPromiseMap.set("audioinput",r),r.catch(()=>be.userMediaPromiseMap.delete("audioinput"))),i.video&&(be.userMediaPromiseMap.set("videoinput",r),r.catch(()=>be.userMediaPromiseMap.delete("videoinput")));const a=yield r;return a.getTracks().map(o=>{const c=o.kind==="audio";c?i.audio:i.video;let u;const d=c?s.audio:s.video;typeof d!="boolean"&&(u=d),u?u.deviceId=o.getSettings().deviceId:u={deviceId:o.getSettings().deviceId};const h=vo(o,u);return h.kind===C.Kind.Video?h.source=C.Source.Camera:h.kind===C.Kind.Audio&&(h.source=C.Source.Microphone),h.mediaStream=a,h})})}function Cl(i){return g(this,void 0,void 0,function*(){return(yield Eo({audio:!1,video:i}))[0]})}function wl(i){return g(this,void 0,void 0,function*(){return(yield Eo({audio:i,video:!1}))[0]})}class El extends _i{get description(){return"Can publish audio"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield wl();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&a.mediaType==="audio"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))})}}class Pl extends _i{get description(){return"Can publish video"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield Cl();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,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(a=>{a.type==="outbound-rtp"&&a.mediaType==="video"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}}class Rl extends _i{get description(){return"Resuming connection after interruption"}perform(){var e;return g(this,void 0,void 0,function*(){const t=yield this.connect();let n=!1,s=!1,r;const a=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 o=t.engine.client.onClose;if(o&&o(""),yield a,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 _l extends _i{get description(){return"Can connect via TURN"}perform(){var e,t;return g(this,void 0,void 0,function*(){const n=new Ms,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let u of c.urls)u.startsWith("turn:")?(a=!0,o=!0):u.startsWith("turns:")&&(a=!0,o=!0,r=!0),u.startsWith("stun:")&&(o=!0);o?a&&!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||a?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 Il extends _i{get description(){return"Establishing WebRTC connection"}perform(){return g(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 a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(Al(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(s,r)},this.room.engine.subscriber&&(this.room.engine.subscriber.pc.onicecandidateerror=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),m.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 Al(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 Ol extends _i{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return g(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 Ms;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)===Ci.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 Bl extends mt.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:Ve.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!==Ve.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return g(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),s=a=>{this.updateCheck(t,a)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Ol)})}checkWebRTC(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Il)})}checkTURN(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(_l)})}checkReconnect(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Rl)})}checkPublishAudio(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(El)})}checkPublishVideo(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Pl)})}}function Ll(){const i=document.createElement("style");return i.textContent=`
52
52
  * {
53
53
  cursor: crosshair !important;
54
54
  }
55
- `,i}function Ol(){const i=document.createElement("style");return i.textContent=`
55
+ `,i}function Nl(){const i=document.createElement("style");return i.textContent=`
56
56
  * {
57
57
  pointer-events: none !important;
58
58
  user-select: none !important;
59
59
  }
60
- `,i}function Ll(i){jo(i,"svelte-xrxt5b",'#liveroom-client-element.svelte-xrxt5b.svelte-xrxt5b{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-xrxt5b.svelte-xrxt5b{z-index:99999;position:fixed;inset:0;overflow:hidden;pointer-events:none}.user.svelte-xrxt5b.svelte-xrxt5b{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.svelte-xrxt5b .cursor.svelte-xrxt5b{position:absolute;top:0;left:0;color:var(--color);transform-origin:top left;transform:rotate(6deg)}.user[data-isself="true"].svelte-xrxt5b .cursor.svelte-xrxt5b{display:none}.user-label.svelte-xrxt5b.svelte-xrxt5b{font-weight:600;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)}.user.svelte-xrxt5b .user-label.svelte-xrxt5b{display:flex;flex-direction:column;justify-content:center;align-items:center}.user.svelte-xrxt5b .user-label[data-hidevideo="true"].svelte-xrxt5b{position:absolute;top:20px;left:16px}.user.svelte-xrxt5b .user-label[data-hidevideo="false"].svelte-xrxt5b{position:relative;margin:0.5rem 0 0 0.5rem}.user[data-isself="true"].svelte-xrxt5b .user-label.svelte-xrxt5b{display:none}.user-label.svelte-xrxt5b .user-name.svelte-xrxt5b{display:flex;justify-content:center;align-items:center;background-color:var(--color);font-size:0.7rem}.user.svelte-xrxt5b .user-label[data-hidevideo="true"] .user-name.svelte-xrxt5b{padding:0.15rem 0.5rem}.user.svelte-xrxt5b .user-label[data-hidevideo="false"] .user-name.svelte-xrxt5b{position:absolute;inset-inline:0;bottom:-2px;padding:0.15rem 0.5rem 0.35rem 0.5rem}.user.svelte-xrxt5b .user-label #video-container.svelte-xrxt5b{height:7rem;width:7rem;overflow:hidden;display:flex;justify-content:center;align-items:center}.user.svelte-xrxt5b .user-label[data-hidevideo="true"] #video-container.svelte-xrxt5b{display:none}.user.svelte-xrxt5b .user-label #video-container video.svelte-xrxt5b{height:100%;aspect-ratio:16 / 9;transform:scaleX(-1)}.user.svelte-xrxt5b .halo.svelte-xrxt5b{transform:scale(0);z-index:-1;position:absolute;top:-60px;left:-60px;width:120px;height:120px;border-radius:9999px;background-color:var(--color);opacity:0.25;transition:transform 100ms ease-out;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user.svelte-xrxt5b .halo[data-show="true"].svelte-xrxt5b{transform:scale(1)}')}function Br(i,e,t){const n=i.slice();return n[28]=e[t],n[29]=e,n[30]=t,n}function Jr(i){let e,t=[],n=new Map,s=Hs(Object.values(i[1]));const r=a=>a[28].id;for(let a=0;a<s.length;a+=1){let o=Br(i,s,a),c=r(o);n.set(c,t[a]=jr(c,o))}return{c(){e=Ye("div");for(let a=0;a<t.length;a+=1)t[a].c();z(e,"id","users-container"),z(e,"class","svelte-xrxt5b")},m(a,o){Ln(a,e,o);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(a,o){o&15&&(s=Hs(Object.values(a[1])),t=tc(t,o,r,1,a,s,n,e,ec,jr,null,Br))},d(a){a&&an(e);for(let o=0;o<t.length;o+=1)t[o].d()}}}function jr(i,e){let t,n,s,r,a,o,c,u,d=e[28],h,f,m=e[28].name+"",b,T,w,I,D,Q,j,ce;const ae=()=>e[12](c,d),q=()=>e[12](null,d);return{key:i,first:null,c(){t=Ye("div"),n=$s("svg"),s=$s("path"),r=cn(),a=Ye("div"),o=Ye("div"),c=Ye("video"),h=cn(),f=Ye("div"),b=qr(m),w=cn(),I=Ye("div"),Q=cn(),z(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"),z(n,"width","23"),z(n,"viewBox","0 0 27 24"),z(n,"fill","currentColor"),z(n,"aria-hidden","true"),z(n,"xmlns","http://www.w3.org/2000/svg"),z(n,"class","cursor svelte-xrxt5b"),z(c,"id",u=`user-video-${e[28].id}`),z(c,"class","svelte-xrxt5b"),z(o,"id","video-container"),z(o,"class","svelte-xrxt5b"),z(f,"class","user-name svelte-xrxt5b"),z(a,"class","user-label svelte-xrxt5b"),z(a,"data-hidevideo",T=!e[28].camera_enabled),z(I,"class","halo svelte-xrxt5b"),z(I,"data-show",D=(e[28].id==e[0].id&&e[28].is_shift_key_down||e[28].id!=e[0].id&&(e[28].is_shift_key_down||e[28].is_mouse_down))&&e[3]>1),z(t,"id",j="user-"+e[28].id),z(t,"class","user svelte-xrxt5b"),z(t,"data-isself",ce=e[28].id==e[0].id),hi(t,"--color",e[28].color),hi(t,"--x",parseFloat(e[28].x)+"vw"),hi(t,"--y",parseFloat(e[28].y)+"vh"),this.first=t},m(K,x){Ln(K,t,x),Oe(t,n),Oe(n,s),Oe(t,r),Oe(t,a),Oe(a,o),Oe(o,c),ae(),Oe(a,h),Oe(a,f),Oe(f,b),Oe(t,w),Oe(t,I),Oe(t,Q)},p(K,x){e=K,x&2&&u!==(u=`user-video-${e[28].id}`)&&z(c,"id",u),d!==e[28]&&(q(),d=e[28],ae()),x&2&&m!==(m=e[28].name+"")&&Ho(b,m),x&2&&T!==(T=!e[28].camera_enabled)&&z(a,"data-hidevideo",T),x&11&&D!==(D=(e[28].id==e[0].id&&e[28].is_shift_key_down||e[28].id!=e[0].id&&(e[28].is_shift_key_down||e[28].is_mouse_down))&&e[3]>1)&&z(I,"data-show",D),x&2&&j!==(j="user-"+e[28].id)&&z(t,"id",j),x&3&&ce!==(ce=e[28].id==e[0].id)&&z(t,"data-isself",ce),x&2&&hi(t,"--color",e[28].color),x&2&&hi(t,"--x",parseFloat(e[28].x)+"vw"),x&2&&hi(t,"--y",parseFloat(e[28].y)+"vh")},d(K){K&&an(t),q()}}}function Nl(i){let e,t=i[0]&&i[1]&&Jr(i);return{c(){e=Ye("div"),t&&t.c(),z(e,"id","liveroom-client-element"),z(e,"class","svelte-xrxt5b")},m(n,s){Ln(n,e,s),t&&t.m(e,null)},p(n,[s]){n[0]&&n[1]?t?t.p(n,s):(t=Jr(n),t.c(),t.m(e,null)):t&&(t.d(1),t=null)},i:Yi,o:Yi,d(n){n&&an(e),t&&t.d()}}}function Rs(i,e){if(i.tagName==="BODY")return window;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?Rs(i.parentElement,e):window}function Dl(i,e,t){let{version:n}=e,{url:s}=e,{room_id:r}=e,{user_name:a=void 0}=e,o,c,u=!1,d=Al(),h=Ol(),f,m,b,T,w={},I;Go(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${a}')... (v${n})`),Q()}),zo(()=>{j(),xi()});async function D(){if(console.log("[LiveKit] Beginning setup..."),t(8,c=new So({dynacast:!0}).on(P.TrackSubscribed,async(U,he,fe)=>{switch(console.log("[LiveKit] Track Subscribed",U,he,fe),console.table({identity:fe.identity,source:he.source}),he.source){case C.Source.Camera:{const Ie=w[fe.identity];Ie&&(console.log(`[LiveKit] Attaching user camera (identity ${fe.identity})`),U.attach(Ie));break}}})),console.log("[LiveKit] Created room",c.name),!b)throw new Error("LiveKit websocket URL not set");if(!T)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${b}'...`),await c.connect(b,T,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",c.name),await Promise.all([c.localParticipant.enableCameraAndMicrophone().then(()=>console.log("[LiveKit] Local camera & mic enabled")).then(async()=>{var Ie,xe,gt;const U=(xe=(Ie=c==null?void 0:c.localParticipant)==null?void 0:Ie.videoTracks)==null?void 0:xe.values(),he=U&&((gt=Array.from(U)[0])==null?void 0:gt.track),fe=f&&w[f.id];fe&&he&&(console.log("[LiveKit] Attaching local user camera"),he.attach(fe))})])}function Q(){o=new cu({url:s,topic:`liveroom-livestate:${r}`,params:{room_id:r,user_name:a,referrer:document.referrer,current_url:window.location.href,inner_width:window.innerWidth,inner_height:window.innerHeight,language:window.navigator.language,user_agent:window.navigator.userAgent},socketOptions:{logger:null}}),o.addEventListener("wheel-from-another-user",({detail:{delta_x:U,delta_y:he,x:fe,y:Ie}})=>{const xe=parseInt(U),gt=parseInt(he),te=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(fe)/100,clientY:window.innerHeight*parseFloat(Ie)/100,deltaX:xe,deltaY:gt,deltaMode:0}),vt=document.head.contains(h);vt&&document.head.removeChild(h);const di=document.elementFromPoint(te.clientX,te.clientY);vt&&document.head.appendChild(h),(di instanceof HTMLElement||di instanceof SVGElement)&&(Math.abs(gt)>=Math.abs(xe)?Rs(di,"vertical").scrollBy({top:gt,left:0,behavior:"instant"}):Rs(di,"horizontal").scrollBy({top:0,left:xe,behavior:"instant"}))}),o.addEventListener("click-from-another-user",({detail:{x:U,y:he}})=>{const fe=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(U)/100,clientY:window.innerHeight*parseFloat(he)/100}),Ie=document.head.contains(h);Ie&&document.head.removeChild(h);const xe=document.elementFromPoint(fe.clientX,fe.clientY);Ie&&document.head.appendChild(h),(xe instanceof HTMLElement||xe instanceof SVGElement)&&xe.dispatchEvent(fe)}),o.addEventListener("livestate-change",({detail:{state:U}})=>{t(4,r=U.room_id),t(0,f=U.me),t(1,m=U.users),t(10,b=U.livekit_ws_url),t(11,T=U.livekit_token)}),o.connect(),window.addEventListener("mousemove",ce),window.addEventListener("mousedown",ae),window.addEventListener("mouseup",q),window.addEventListener("keydown",x),window.addEventListener("keyup",F),window.addEventListener("resize",le)}function j(){window.removeEventListener("resize",le),window.removeEventListener("keyup",F),window.removeEventListener("keydown",x),window.removeEventListener("mouseup",q),window.removeEventListener("mousedown",ae),window.removeEventListener("mousemove",ce),o==null||o.disconnect(),o=void 0,c==null||c.disconnect(),t(8,c=void 0)}function ce(U){o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:f.id,x:Number(U.clientX/window.innerWidth*100).toFixed(2),y:Number(U.clientY/window.innerHeight*100).toFixed(2)}}))}function ae(){o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:f.id}}))}function q(){o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:f.id}}))}const K=["Shift"];function x(U){!U.repeat&&K.includes(U.key)&&o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("key_down",{detail:{key:U.key,user_id:f.id}}))}function F(U){K.includes(U.key)&&o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("key_up",{detail:{key:U.key,user_id:f.id}}))}function le(){o&&(f!=null&&f.id)&&o.dispatchEvent(new CustomEvent("window_resize",{detail:{inner_width:window.innerWidth,inner_height:window.innerHeight,user_id:f.id}}))}function Ue(){document.head.appendChild(d),document.head.appendChild(h),t(9,u=!0)}function xi(){document.head.removeChild(d),document.head.removeChild(h),t(9,u=!1)}function Ai(U,he){ts[U?"unshift":"push"](()=>{w[he.id]=U,t(2,w)})}return i.$$set=U=>{"version"in U&&t(5,n=U.version),"url"in U&&t(6,s=U.url),"room_id"in U&&t(4,r=U.room_id),"user_name"in U&&t(7,a=U.user_name)},i.$$.update=()=>{i.$$.dirty&3331&&!c&&f&&m&&b&&T&&D(),i.$$.dirty&2&&t(3,I=Object.keys(m||{}).length),i.$$.dirty&514&&!u&&m&&Object.values(m).some(U=>U.type=="admin"&&U.is_space_key_down)&&Ue(),i.$$.dirty&514&&u&&m&&Object.values(m).filter(U=>U.type=="admin").every(U=>!U.is_space_key_down)&&xi()},[f,m,w,I,r,n,s,a,c,u,b,T,Ai]}class wo extends oc{constructor(e){super(),rc(this,e,Dl,Nl,Bo,{version:5,url:6,room_id:4,user_name:7},Ll)}get version(){return this.$$.ctx[5]}set version(e){this.$$set({version:e}),vi()}get url(){return this.$$.ctx[6]}set url(e){this.$$set({url:e}),vi()}get room_id(){return this.$$.ctx[4]}set room_id(e){this.$$set({room_id:e}),vi()}get user_name(){return this.$$.ctx[7]}set user_name(e){this.$$set({user_name:e}),vi()}}customElements.define("liveroom-client-element",ac(wo,{version:{},url:{},room_id:{},user_name:{}},[],[],!0));module.exports=wo;
60
+ `,i}function xl(i){Vo(i,"svelte-uiimm6",'#liveroom-client-element.svelte-uiimm6.svelte-uiimm6{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-uiimm6.svelte-uiimm6{z-index:99999;position:fixed;inset:0;overflow:hidden;pointer-events:none}.user.svelte-uiimm6.svelte-uiimm6{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.svelte-uiimm6 .cursor.svelte-uiimm6{position:absolute;top:0;left:0;color:var(--color);transform-origin:top left;transform:rotate(6deg)}.user[data-isself="true"].svelte-uiimm6 .cursor.svelte-uiimm6{display:none}.user-label.svelte-uiimm6.svelte-uiimm6{font-weight:600;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)}.user.svelte-uiimm6 .user-label.svelte-uiimm6{display:flex;flex-direction:column;justify-content:center;align-items:center}.user.svelte-uiimm6 .user-label[data-hidevideo="true"].svelte-uiimm6{position:absolute;top:20px;left:16px}.user.svelte-uiimm6 .user-label[data-hidevideo="false"].svelte-uiimm6{position:relative;margin:12px 6px}.user[data-isself="true"].svelte-uiimm6 .user-label.svelte-uiimm6{display:none}.user-label.svelte-uiimm6 .user-name.svelte-uiimm6{display:flex;justify-content:center;align-items:center;background-color:var(--color);font-size:0.7rem}.user.svelte-uiimm6 .user-label[data-hidevideo="true"] .user-name.svelte-uiimm6{padding:0.15rem 0.5rem}.user.svelte-uiimm6 .user-label[data-hidevideo="false"] .user-name.svelte-uiimm6{position:absolute;inset-inline:0;bottom:-2px;padding:0.15rem 0.5rem 0.35rem 0.5rem}.user.svelte-uiimm6 .user-label #video-container.svelte-uiimm6{height:7rem;width:7rem;overflow:hidden;display:flex;justify-content:center;align-items:center}.user.svelte-uiimm6 .user-label[data-hidevideo="true"] #video-container.svelte-uiimm6{display:none}.user.svelte-uiimm6 .user-label #video-container video.svelte-uiimm6{height:100%;aspect-ratio:16 / 9;transform:scaleX(-1)}.user.svelte-uiimm6 .halo.svelte-uiimm6{transform:scale(0);z-index:-1;position:absolute;top:-60px;left:-60px;width:120px;height:120px;border-radius:9999px;background-color:var(--color);opacity:0.25;transition:transform 100ms ease-out;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user.svelte-uiimm6 .halo[data-show="true"].svelte-uiimm6{transform:scale(1)}')}function jr(i,e,t){const n=i.slice();return n[29]=e[t],n[30]=e,n[31]=t,n}function Vr(i){let e,t=[],n=new Map,s=Gs(Object.values(i[1]));const r=a=>a[29].id;for(let a=0;a<s.length;a+=1){let o=jr(i,s,a),c=r(o);n.set(c,t[a]=$r(c,o))}return{c(){e=Ye("div");for(let a=0;a<t.length;a+=1)t[a].c();z(e,"id","users-container"),z(e,"class","svelte-uiimm6")},m(a,o){Nn(a,e,o);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(a,o){o[0]&15&&(s=Gs(Object.values(a[1])),t=ic(t,o,r,1,a,s,n,e,tc,$r,null,jr))},d(a){a&&nn(e);for(let o=0;o<t.length;o+=1)t[o].d()}}}function $r(i,e){let t,n,s,r,a,o,c,u,d=e[29],h,f,p=e[29].name+"",b,T,w,_,M,Q,j,he;const ae=()=>e[13](c,d),q=()=>e[13](null,d);return{key:i,first:null,c(){t=Ye("div"),n=Hs("svg"),s=Hs("path"),r=cn(),a=Ye("div"),o=Ye("div"),c=Ye("video"),h=cn(),f=Ye("div"),b=Wr(p),w=cn(),_=Ye("div"),Q=cn(),z(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"),z(n,"width","23"),z(n,"viewBox","0 0 27 24"),z(n,"fill","currentColor"),z(n,"aria-hidden","true"),z(n,"xmlns","http://www.w3.org/2000/svg"),z(n,"class","cursor svelte-uiimm6"),z(c,"id",u=`user-video-${e[29].id}`),z(c,"class","svelte-uiimm6"),z(o,"id","video-container"),z(o,"class","svelte-uiimm6"),z(f,"class","user-name svelte-uiimm6"),z(a,"class","user-label svelte-uiimm6"),z(a,"data-hidevideo",T=!e[29].camera_enabled),z(_,"class","halo svelte-uiimm6"),z(_,"data-show",M=(e[29].id==e[0].id&&e[29].is_shift_key_down||e[29].id!=e[0].id&&(e[29].is_shift_key_down||e[29].is_mouse_down))&&e[3]>1),z(t,"id",j="user-"+e[29].id),z(t,"class","user svelte-uiimm6"),z(t,"data-isself",he=e[29].id==e[0].id),hi(t,"--color",e[29].color),hi(t,"--x",parseFloat(e[29].x)+"vw"),hi(t,"--y",parseFloat(e[29].y)+"vh"),this.first=t},m(K,A){Nn(K,t,A),Ne(t,n),Ne(n,s),Ne(t,r),Ne(t,a),Ne(a,o),Ne(o,c),ae(),Ne(a,h),Ne(a,f),Ne(f,b),Ne(t,w),Ne(t,_),Ne(t,Q)},p(K,A){e=K,A[0]&2&&u!==(u=`user-video-${e[29].id}`)&&z(c,"id",u),d!==e[29]&&(q(),d=e[29],ae()),A[0]&2&&p!==(p=e[29].name+"")&&Wo(b,p),A[0]&2&&T!==(T=!e[29].camera_enabled)&&z(a,"data-hidevideo",T),A[0]&11&&M!==(M=(e[29].id==e[0].id&&e[29].is_shift_key_down||e[29].id!=e[0].id&&(e[29].is_shift_key_down||e[29].is_mouse_down))&&e[3]>1)&&z(_,"data-show",M),A[0]&2&&j!==(j="user-"+e[29].id)&&z(t,"id",j),A[0]&3&&he!==(he=e[29].id==e[0].id)&&z(t,"data-isself",he),A[0]&2&&hi(t,"--color",e[29].color),A[0]&2&&hi(t,"--x",parseFloat(e[29].x)+"vw"),A[0]&2&&hi(t,"--y",parseFloat(e[29].y)+"vh")},d(K){K&&nn(t),q()}}}function Dl(i){let e,t=i[0]&&i[1]&&Vr(i);return{c(){e=Ye("div"),t&&t.c(),z(e,"id","liveroom-client-element"),z(e,"class","svelte-uiimm6")},m(n,s){Nn(n,e,s),t&&t.m(e,null)},p(n,s){n[0]&&n[1]?t?t.p(n,s):(t=Vr(n),t.c(),t.m(e,null)):t&&(t.d(1),t=null)},i:Gi,o:Gi,d(n){n&&nn(e),t&&t.d()}}}function _s(i,e){if(i.tagName==="BODY")return window;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?_s(i.parentElement,e):window}function Ml(i,e,t){let{version:n}=e,{url:s}=e,{room_id:r}=e,{user_name:a=void 0}=e,{user_color:o=void 0}=e,c,u,d=!1,h=Ll(),f=Nl(),p,b,T,w,_={},M;zo(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${a}')... (v${n})`),j()}),Ko(()=>{he(),di()});async function Q(){if(console.log("[LiveKit] Beginning setup..."),t(9,u=new wo({dynacast:!0}).on(P.TrackSubscribed,async(O,oe,ce)=>{switch(console.log("[LiveKit] Track Subscribed",O,oe,ce),console.table({identity:ce.identity,source:oe.source}),oe.source){case C.Source.Camera:{const Ae=_[ce.identity];Ae&&(console.log(`[LiveKit] Attaching user camera (identity ${ce.identity})`),O.attach(Ae));break}}})),console.log("[LiveKit] Created room",u.name),!T)throw new Error("LiveKit websocket URL not set");if(!w)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${T}'...`),await u.connect(T,w,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",u.name),await Promise.all([u.localParticipant.enableCameraAndMicrophone().then(()=>console.log("[LiveKit] Local camera & mic enabled")).then(async()=>{var Ae,Oe,Z;const O=(Oe=(Ae=u==null?void 0:u.localParticipant)==null?void 0:Ae.videoTracks)==null?void 0:Oe.values(),oe=O&&((Z=Array.from(O)[0])==null?void 0:Z.track),ce=p&&_[p.id];ce&&oe&&(console.log("[LiveKit] Attaching local user camera"),oe.attach(ce))})])}function j(){c=new uu({url:s,topic:`liveroom-livestate:${r}`,params:{room_id:r,user_name:a,user_color:o,referrer:document.referrer,current_url:window.location.href,inner_width:window.innerWidth,inner_height:window.innerHeight,language:window.navigator.language,user_agent:window.navigator.userAgent},socketOptions:{logger:null}}),c.addEventListener("wheel-from-another-user",({detail:{delta_x:O,delta_y:oe,x:ce,y:Ae}})=>{const Oe=parseInt(O),Z=parseInt(oe),gt=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(ce)/100,clientY:window.innerHeight*parseFloat(Ae)/100,deltaX:Oe,deltaY:Z,deltaMode:0}),on=document.head.contains(f);on&&document.head.removeChild(f);const ie=document.elementFromPoint(gt.clientX,gt.clientY);on&&document.head.appendChild(f),(ie instanceof HTMLElement||ie instanceof SVGElement)&&(Math.abs(Z)>=Math.abs(Oe)?_s(ie,"vertical").scrollBy({top:Z,left:0,behavior:"instant"}):_s(ie,"horizontal").scrollBy({top:0,left:Oe,behavior:"instant"}))}),c.addEventListener("click-from-another-user",({detail:{x:O,y:oe}})=>{const ce=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(O)/100,clientY:window.innerHeight*parseFloat(oe)/100}),Ae=document.head.contains(f);Ae&&document.head.removeChild(f);const Oe=document.elementFromPoint(ce.clientX,ce.clientY);Ae&&document.head.appendChild(f),(Oe instanceof HTMLElement||Oe instanceof SVGElement)&&Oe.dispatchEvent(ce)}),c.addEventListener("livestate-change",({detail:{state:O}})=>{var oe,ce;(oe=O==null?void 0:O.me)!=null&&oe.name&&O.me.name!=(p==null?void 0:p.name)&&(sessionStorage==null||sessionStorage.setItem($s.SESSION_STORAGE_KEY_USER_NAME,O.me.name)),(ce=O==null?void 0:O.me)!=null&&ce.color&&O.me.color!=(p==null?void 0:p.color)&&(sessionStorage==null||sessionStorage.setItem($s.SESSION_STORAGE_KEY_USER_COLOR,O.me.color)),t(4,r=O.room_id),t(0,p=O.me),t(1,b=O.users),t(11,T=O.livekit_ws_url),t(12,w=O.livekit_token)}),c.connect(),window.addEventListener("mousemove",ae),window.addEventListener("mousedown",q),window.addEventListener("mouseup",K),window.addEventListener("keydown",F),window.addEventListener("keyup",fe),window.addEventListener("resize",Ie)}function he(){window.removeEventListener("resize",Ie),window.removeEventListener("keyup",fe),window.removeEventListener("keydown",F),window.removeEventListener("mouseup",K),window.removeEventListener("mousedown",q),window.removeEventListener("mousemove",ae),c==null||c.disconnect(),c=void 0,u==null||u.disconnect(),t(9,u=void 0)}function ae(O){c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:p.id,x:Number(O.clientX/window.innerWidth*100).toFixed(2),y:Number(O.clientY/window.innerHeight*100).toFixed(2)}}))}function q(){c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:p.id}}))}function K(){c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:p.id}}))}const A=["Shift"];function F(O){!O.repeat&&A.includes(O.key)&&c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("key_down",{detail:{key:O.key,user_id:p.id}}))}function fe(O){A.includes(O.key)&&c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("key_up",{detail:{key:O.key,user_id:p.id}}))}function Ie(){c&&(p!=null&&p.id)&&c.dispatchEvent(new CustomEvent("window_resize",{detail:{inner_width:window.innerWidth,inner_height:window.innerHeight,user_id:p.id}}))}function rn(){document.head.appendChild(h),document.head.appendChild(f),t(10,d=!0)}function di(){document.head.removeChild(h),document.head.removeChild(f),t(10,d=!1)}function an(O,oe){is[O?"unshift":"push"](()=>{_[oe.id]=O,t(2,_)})}return i.$$set=O=>{"version"in O&&t(5,n=O.version),"url"in O&&t(6,s=O.url),"room_id"in O&&t(4,r=O.room_id),"user_name"in O&&t(7,a=O.user_name),"user_color"in O&&t(8,o=O.user_color)},i.$$.update=()=>{i.$$.dirty[0]&6659&&!u&&p&&b&&T&&w&&Q(),i.$$.dirty[0]&2&&t(3,M=Object.keys(b||{}).length),i.$$.dirty[0]&1026&&!d&&b&&Object.values(b).some(O=>O.type=="admin"&&O.is_space_key_down)&&rn(),i.$$.dirty[0]&1026&&d&&b&&Object.values(b).filter(O=>O.type=="admin").every(O=>!O.is_space_key_down)&&di()},[p,b,_,M,r,n,s,a,o,u,d,T,w,an]}class Po extends cc{constructor(e){super(),ac(this,e,Ml,Dl,Jo,{version:5,url:6,room_id:4,user_name:7,user_color:8},xl,[-1,-1])}get version(){return this.$$.ctx[5]}set version(e){this.$$set({version:e}),ii()}get url(){return this.$$.ctx[6]}set url(e){this.$$set({url:e}),ii()}get room_id(){return this.$$.ctx[4]}set room_id(e){this.$$set({room_id:e}),ii()}get user_name(){return this.$$.ctx[7]}set user_name(e){this.$$set({user_name:e}),ii()}get user_color(){return this.$$.ctx[8]}set user_color(e){this.$$set({user_color:e}),ii()}}customElements.define("liveroom-client-element",oc(Po,{version:{},url:{},room_id:{},user_name:{},user_color:{}},[],[],!0));module.exports=Po;