obi-sdk 0.1.10 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,n=Symbol(),s=new WeakMap;let r=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==n)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(i&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=s.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&s.set(t,e))}return e}toString(){return this.cssText}};const a=(e,...t)=>{const i=1===e.length?e[0]:t.reduce(((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1]),e[0]);return new r(i,e,n)},o=i?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new r("string"==typeof e?e:e+"",void 0,n))(t)})(e):e,{is:c,defineProperty:d,getOwnPropertyDescriptor:l,getOwnPropertyNames:u,getOwnPropertySymbols:h,getPrototypeOf:p}=Object,m=globalThis,g=m.trustedTypes,f=g?g.emptyScript:"",v=m.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?f:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(n){i=null}}return i}},k=(e,t)=>!c(e,t),T={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:k};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),m.litPropertyMetadata??(m.litPropertyMetadata=new WeakMap);let S=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=T){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&d(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=l(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const r=n?.call(this);s?.call(this,t),this.requestUpdate(e,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??T}static _$Ei(){if(this.hasOwnProperty(y("elementProperties")))return;const e=p(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y("properties"))){const e=this.properties,t=[...u(e),...h(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const e=this._$Eu(t,i);void 0!==e&&this._$Eh.set(e,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(o(e))}else void 0!==e&&t.push(o(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,n)=>{if(i)e.adoptedStyleSheets=n.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const i of n){const n=document.createElement("style"),s=t.litNonce;void 0!==s&&n.setAttribute("nonce",s),n.textContent=i.cssText,e.appendChild(n)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:b).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:b;this._$Em=n,this[n]=s.fromAttribute(t,e.type)??this._$Ej?.get(n)??null,this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){const n=this.constructor,s=this[e];if(i??(i=n.getPropertyOptions(e)),!((i.hasChanged??k)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,r??t??this[e]),!0!==s||void 0!==r)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(e){}firstUpdated(e){}};S.elementStyles=[],S.shadowRootOptions={mode:"open"},S[y("elementProperties")]=new Map,S[y("finalized")]=new Map,v?.({ReactiveElement:S}),(m.reactiveElementVersions??(m.reactiveElementVersions=[])).push("2.1.0");const C=globalThis,w=C.trustedTypes,E=w?w.createPolicy("lit-html",{createHTML:e=>e}):void 0,_="$lit$",P=`lit$${Math.random().toFixed(9).slice(2)}$`,R="?"+P,x=`<${R}>`,I=document,O=()=>I.createComment(""),A=e=>null===e||"object"!=typeof e&&"function"!=typeof e,N=Array.isArray,D="[ \t\n\f\r]",M=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,L=/-->/g,U=/>/g,j=RegExp(`>|${D}(?:([^\\s"'>=/]+)(${D}*=${D}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),F=/'/g,B=/"/g,$=/^(?:script|style|textarea|title)$/i,V=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),q=V(1),Z=V(2),K=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),H=new WeakMap,G=I.createTreeWalker(I,129);function W(e,t){if(!N(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==E?E.createHTML(t):t}let J=class e{constructor({strings:t,_$litType$:i},n){let s;this.parts=[];let r=0,a=0;const o=t.length-1,c=this.parts,[d,l]=((e,t)=>{const i=e.length-1,n=[];let s,r=2===t?"<svg>":3===t?"<math>":"",a=M;for(let o=0;o<i;o++){const t=e[o];let i,c,d=-1,l=0;for(;l<t.length&&(a.lastIndex=l,c=a.exec(t),null!==c);)l=a.lastIndex,a===M?"!--"===c[1]?a=L:void 0!==c[1]?a=U:void 0!==c[2]?($.test(c[2])&&(s=RegExp("</"+c[2],"g")),a=j):void 0!==c[3]&&(a=j):a===j?">"===c[0]?(a=s??M,d=-1):void 0===c[1]?d=-2:(d=a.lastIndex-c[2].length,i=c[1],a=void 0===c[3]?j:'"'===c[3]?B:F):a===B||a===F?a=j:a===L||a===U?a=M:(a=j,s=void 0);const u=a===j&&e[o+1].startsWith("/>")?" ":"";r+=a===M?t+x:d>=0?(n.push(i),t.slice(0,d)+_+t.slice(d)+P+u):t+P+(-2===d?o:u)}return[W(e,r+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]})(t,i);if(this.el=e.createElement(d,n),G.currentNode=this.el.content,2===i||3===i){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(s=G.nextNode())&&c.length<o;){if(1===s.nodeType){if(s.hasAttributes())for(const e of s.getAttributeNames())if(e.endsWith(_)){const t=l[a++],i=s.getAttribute(e).split(P),n=/([.?@])?(.*)/.exec(t);c.push({type:1,index:r,name:n[2],strings:i,ctor:"."===n[1]?te:"?"===n[1]?ie:"@"===n[1]?ne:ee}),s.removeAttribute(e)}else e.startsWith(P)&&(c.push({type:6,index:r}),s.removeAttribute(e));if($.test(s.tagName)){const e=s.textContent.split(P),t=e.length-1;if(t>0){s.textContent=w?w.emptyScript:"";for(let i=0;i<t;i++)s.append(e[i],O()),G.nextNode(),c.push({type:2,index:++r});s.append(e[t],O())}}}else if(8===s.nodeType)if(s.data===R)c.push({type:2,index:r});else{let e=-1;for(;-1!==(e=s.data.indexOf(P,e+1));)c.push({type:7,index:r}),e+=P.length-1}r++}}static createElement(e,t){const i=I.createElement("template");return i.innerHTML=e,i}};function Q(e,t,i=e,n){if(t===K)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const r=A(t)?void 0:t._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),void 0===r?s=void 0:(s=new r(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??(i._$Co=[]))[n]=s:i._$Cl=s),void 0!==s&&(t=Q(e,s._$AS(e,t.values),s,n)),t}class Y{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??I).importNode(t,!0);G.currentNode=n;let s=G.nextNode(),r=0,a=0,o=i[0];for(;void 0!==o;){if(r===o.index){let t;2===o.type?t=new X(s,s.nextSibling,this,e):1===o.type?t=new o.ctor(s,o.name,o.strings,this,e):6===o.type&&(t=new se(s,this,e)),this._$AV.push(t),o=i[++a]}r!==o?.index&&(s=G.nextNode(),r++)}return G.currentNode=I,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class X{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Q(this,e,t),A(e)?e===z||null==e||""===e?(this._$AH!==z&&this._$AR(),this._$AH=z):e!==this._$AH&&e!==K&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>N(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==z&&A(this._$AH)?this._$AA.nextSibling.data=e:this.T(I.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=J.createElement(W(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new Y(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=H.get(e.strings);return void 0===t&&H.set(e.strings,t=new J(e)),t}k(e){N(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const s of e)n===t.length?t.push(i=new X(this.O(O()),this.O(O()),this,this.options)):i=t[n],i._$AI(s),n++;n<t.length&&(this._$AR(i&&i._$AB.nextSibling,n),t.length=n)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}let ee=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=z,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=z}_$AI(e,t=this,i,n){const s=this.strings;let r=!1;if(void 0===s)e=Q(this,e,t,0),r=!A(e)||e!==this._$AH&&e!==K,r&&(this._$AH=e);else{const n=e;let a,o;for(e=s[0],a=0;a<s.length-1;a++)o=Q(this,n[i+a],t,a),o===K&&(o=this._$AH[a]),r||(r=!A(o)||o!==this._$AH[a]),o===z?e=z:e!==z&&(e+=(o??"")+s[a+1]),this._$AH[a]=o}r&&!n&&this.j(e)}j(e){e===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}};class te extends ee{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===z?void 0:e}}let ie=class extends ee{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==z)}},ne=class extends ee{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=Q(this,e,t,0)??z)===K)return;const i=this._$AH,n=e===z&&i!==z||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==z&&(i===z||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},se=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){Q(this,e)}};const re=C.litHtmlPolyfillSupport;re?.(J,X),(C.litHtmlVersions??(C.litHtmlVersions=[])).push("3.3.0");const ae=globalThis;let oe=class extends S{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new X(t.insertBefore(O(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return K}};oe._$litElement$=!0,oe.finalized=!0,ae.litElementHydrateSupport?.({LitElement:oe});const ce=ae.litElementPolyfillSupport;ce?.({LitElement:oe}),(ae.litElementVersions??(ae.litElementVersions=[])).push("4.2.0");const de={attribute:!0,type:String,converter:b,reflect:!1,hasChanged:k},le=(e=de,t,i)=>{const{kind:n,metadata:s}=i;let r=globalThis.litPropertyMetadata.get(s);if(void 0===r&&globalThis.litPropertyMetadata.set(s,r=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e)}}throw Error("Unsupported decorator location: "+n)};function ue(e){return(t,i)=>"object"==typeof i?le(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function he(e){return ue({...e,state:!0,attribute:!1})}const pe=Symbol.for("@ts-pattern/matcher"),me=Symbol.for("@ts-pattern/isVariadic"),ge="@ts-pattern/anonymous-select-key",fe=e=>Boolean(e&&"object"==typeof e),ve=e=>e&&!!e[pe],ye=(e,t,i)=>{if(ve(e)){const n=e[pe](),{matched:s,selections:r}=n.match(t);return s&&r&&Object.keys(r).forEach((e=>i(e,r[e]))),s}if(fe(e)){if(!fe(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=[],s=[],r=[];for(const t of e.keys()){const i=e[t];ve(i)&&i[me]?r.push(i):r.length?s.push(i):n.push(i)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<n.length+s.length)return!1;const e=t.slice(0,n.length),a=0===s.length?[]:t.slice(-s.length),o=t.slice(n.length,0===s.length?1/0:-s.length);return n.every(((t,n)=>ye(t,e[n],i)))&&s.every(((e,t)=>ye(e,a[t],i)))&&(0===r.length||ye(r[0],o,i))}return e.length===t.length&&e.every(((e,n)=>ye(e,t[n],i)))}return Reflect.ownKeys(e).every((n=>{const s=e[n];return(n in t||ve(r=s)&&"optional"===r[pe]().matcherType)&&ye(s,t[n],i);var r}))}return Object.is(t,e)},be=e=>{var t,i,n;return fe(e)?ve(e)?null!=(t=null==(i=(n=e[pe]()).getSelectionKeys)?void 0:i.call(n))?t:[]:Array.isArray(e)?ke(e,be):ke(Object.values(e),be):[]},ke=(e,t)=>e.reduce(((e,i)=>e.concat(t(i))),[]);function Te(e){return Object.assign(e,{optional:()=>Ce(e),and:t=>_e(e,t),or:t=>Pe(e,t),select:t=>void 0===t?xe(e):xe(t,e)})}function Se(e){return Object.assign((t=e,Object.assign(t,{[Symbol.iterator](){let e=0;const i=[{value:Object.assign(t,{[me]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var t;return null!=(t=i[e++])?t:i.at(-1)}}}})),{optional:()=>Se(Ce(e)),select:t=>Se(void 0===t?xe(e):xe(t,e))});var t}function Ce(e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return void 0===t?(be(e).forEach((e=>n(e,void 0))),{matched:!0,selections:i}):{matched:ye(e,t,n),selections:i}},getSelectionKeys:()=>be(e),matcherType:"optional"})})}const we=(e,t)=>{for(const i of e)if(!t(i))return!1;return!0},Ee=(e,t)=>{for(const[i,n]of e.entries())if(!t(n,i))return!1;return!0};function _e(...e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return{matched:e.every((e=>ye(e,t,n))),selections:i}},getSelectionKeys:()=>ke(e,be),matcherType:"and"})})}function Pe(...e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return ke(e,be).forEach((e=>n(e,void 0))),{matched:e.some((e=>ye(e,t,n))),selections:i}},getSelectionKeys:()=>ke(e,be),matcherType:"or"})})}function Re(e){return{[pe]:()=>({match:t=>({matched:Boolean(e(t))})})}}function xe(...e){const t="string"==typeof e[0]?e[0]:void 0,i=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return Te({[pe]:()=>({match:e=>{let n={[null!=t?t:ge]:e};return{matched:void 0===i||ye(i,e,((e,t)=>{n[e]=t})),selections:n}},getSelectionKeys:()=>[null!=t?t:ge].concat(void 0===i?[]:be(i))})})}function Ie(e){return"number"==typeof e}function Oe(e){return"string"==typeof e}function Ae(e){return"bigint"==typeof e}const Ne=Te(Re((function(e){return!0}))),De=Ne,Me=e=>Object.assign(Te(e),{startsWith:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.startsWith(i))))));var i},endsWith:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.endsWith(i))))));var i},minLength:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length>=i)))));var i},length:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length===i)))));var i},maxLength:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length<=i)))));var i},includes:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.includes(i))))));var i},regex:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&Boolean(e.match(i)))))));var i}}),Le=Me(Re(Oe)),Ue=e=>Object.assign(Te(e),{between:(t,i)=>{return Ue(_e(e,(n=t,s=i,Re((e=>Ie(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e<i)))));var i},gt:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e>i)))));var i},lte:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e<=i)))));var i},gte:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e>=i)))));var i},int:()=>Ue(_e(e,Re((e=>Ie(e)&&Number.isInteger(e))))),finite:()=>Ue(_e(e,Re((e=>Ie(e)&&Number.isFinite(e))))),positive:()=>Ue(_e(e,Re((e=>Ie(e)&&e>0)))),negative:()=>Ue(_e(e,Re((e=>Ie(e)&&e<0))))}),je=Ue(Re(Ie)),Fe=e=>Object.assign(Te(e),{between:(t,i)=>{return Fe(_e(e,(n=t,s=i,Re((e=>Ae(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e<i)))));var i},gt:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e>i)))));var i},lte:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e<=i)))));var i},gte:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e>=i)))));var i},positive:()=>Fe(_e(e,Re((e=>Ae(e)&&e>0)))),negative:()=>Fe(_e(e,Re((e=>Ae(e)&&e<0))))}),Be=Fe(Re(Ae)),$e=Te(Re((function(e){return"boolean"==typeof e}))),Ve=Te(Re((function(e){return"symbol"==typeof e}))),qe=Te(Re((function(e){return null==e}))),Ze=Te(Re((function(e){return null!=e})));var Ke={__proto__:null,matcher:pe,optional:Ce,array:function(...e){return Se({[pe]:()=>({match:t=>{if(!Array.isArray(t))return{matched:!1};if(0===e.length)return{matched:!0};const i=e[0];let n={};if(0===t.length)return be(i).forEach((e=>{n[e]=[]})),{matched:!0,selections:n};const s=(e,t)=>{n[e]=(n[e]||[]).concat([t])};return{matched:t.every((e=>ye(i,e,s))),selections:n}},getSelectionKeys:()=>0===e.length?[]:be(e[0])})})},set:function(...e){return Te({[pe]:()=>({match:t=>{if(!(t instanceof Set))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};if(0===e.length)return{matched:!0};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])},s=e[0];return{matched:we(t,(e=>ye(s,e,n))),selections:i}},getSelectionKeys:()=>0===e.length?[]:be(e[0])})})},map:function(...e){return Te({[pe]:()=>({match:t=>{if(!(t instanceof Map))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])};if(0===e.length)return{matched:!0};var s;if(1===e.length)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null==(s=e[0])?void 0:s.toString()}`);const[r,a]=e;return{matched:Ee(t,((e,t)=>{const i=ye(r,t,n),s=ye(a,e,n);return i&&s})),selections:i}},getSelectionKeys:()=>0===e.length?[]:[...be(e[0]),...be(e[1])]})})},intersection:_e,union:Pe,not:function(e){return Te({[pe]:()=>({match:t=>({matched:!ye(e,t,(()=>{}))}),getSelectionKeys:()=>[],matcherType:"not"})})},when:Re,select:xe,any:Ne,_:De,string:Le,number:je,bigint:Be,boolean:$e,symbol:Ve,nullish:qe,nonNullable:Ze,instanceOf:function(e){return Te(Re((t=e,e=>e instanceof t)));var t},shape:function(e){return Te(Re(function(...e){if(1===e.length){const[t]=e;return e=>ye(t,e,(()=>{}))}if(2===e.length){const[t,i]=e;return ye(t,i,(()=>{}))}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${e.length}.`)}(e)))}};class ze extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(i){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const He={matched:!1,value:void 0};function Ge(e){return new We(e,He)}class We{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],i=[e[0]];let n;3===e.length&&"function"==typeof e[1]?n=e[1]:e.length>2&&i.push(...e.slice(1,e.length-1));let s=!1,r={};const a=(e,t)=>{s=!0,r[e]=t},o=!i.some((e=>ye(e,this.input,a)))||n&&!Boolean(n(this.input))?He:{matched:!0,value:t(s?ge in r?r[ge]:r:this.input,this.input)};return new We(this.input,o)}when(e,t){if(this.state.matched)return this;const i=Boolean(e(this.input));return new We(this.input,i?{matched:!0,value:t(this.input,this.input)}:He)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=Je){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}}function Je(e){throw new ze(e)}var Qe,Ye,Xe;(Ye=Qe||(Qe={})).assertEqual=e=>e,Ye.assertIs=function(e){},Ye.assertNever=function(e){throw new Error},Ye.arrayToEnum=e=>{const t={};for(const i of e)t[i]=i;return t},Ye.getValidEnumValues=e=>{const t=Ye.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),i={};for(const n of t)i[n]=e[n];return Ye.objectValues(i)},Ye.objectValues=e=>Ye.objectKeys(e).map((function(t){return e[t]})),Ye.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.push(i);return t},Ye.find=(e,t)=>{for(const i of e)if(t(i))return i},Ye.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,Ye.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},Ye.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Xe||(Xe={})).mergeShapes=(e,t)=>({...e,...t});const et=Qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=e=>{switch(typeof e){case"undefined":return et.undefined;case"string":return et.string;case"number":return isNaN(e)?et.nan:et.number;case"boolean":return et.boolean;case"function":return et.function;case"bigint":return et.bigint;case"symbol":return et.symbol;case"object":return Array.isArray(e)?et.array:null===e?et.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?et.promise:"undefined"!=typeof Map&&e instanceof Map?et.map:"undefined"!=typeof Set&&e instanceof Set?et.set:"undefined"!=typeof Date&&e instanceof Date?et.date:et.object;default:return et.unknown}},it=Qe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},i={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)i._errors.push(t(s));else{let e=i,n=0;for(;n<s.path.length;){const i=s.path[n];n===s.path.length-1?(e[i]=e[i]||{_errors:[]},e[i]._errors.push(t(s))):e[i]=e[i]||{_errors:[]},e=e[i],n++}}};return n(this),i}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Qe.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}nt.create=e=>new nt(e);const st=(e,t)=>{let i;switch(e.code){case it.invalid_type:i=e.received===et.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case it.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(e.expected,Qe.jsonStringifyReplacer)}`;break;case it.unrecognized_keys:i=`Unrecognized key(s) in object: ${Qe.joinValues(e.keys,", ")}`;break;case it.invalid_union:i="Invalid input";break;case it.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Qe.joinValues(e.options)}`;break;case it.invalid_enum_value:i=`Invalid enum value. Expected ${Qe.joinValues(e.options)}, received '${e.received}'`;break;case it.invalid_arguments:i="Invalid function arguments";break;case it.invalid_return_type:i="Invalid function return type";break;case it.invalid_date:i="Invalid date";break;case it.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(i=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(i=`${i} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?i=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?i=`Invalid input: must end with "${e.validation.endsWith}"`:Qe.assertNever(e.validation):i="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case it.too_small:i="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case it.too_big:i="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case it.custom:i="Invalid input";break;case it.invalid_intersection_types:i="Intersection results could not be merged";break;case it.not_multiple_of:i=`Number must be a multiple of ${e.multipleOf}`;break;case it.not_finite:i="Number must be finite";break;default:i=t.defaultError,Qe.assertNever(e)}return{message:i}};let rt=st;function at(){return rt}const ot=e=>{const{data:t,path:i,errorMaps:n,issueData:s}=e,r=[...i,...s.path||[]],a={...s,path:r};if(void 0!==s.message)return{...s,path:r,message:s.message};let o="";const c=n.filter((e=>!!e)).slice().reverse();for(const d of c)o=d(a,{data:t,defaultError:o}).message;return{...s,path:r,message:o}};function ct(e,t){const i=at(),n=ot({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===st?void 0:st].filter((e=>!!e))});e.common.issues.push(n)}class dt{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const n of t){if("aborted"===n.status)return lt;"dirty"===n.status&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const e=await n.key,t=await n.value;i.push({key:e,value:t})}return dt.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return lt;if("aborted"===s.status)return lt;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(i[t.value]=s.value)}return{status:e.value,value:i}}}const lt=Object.freeze({status:"aborted"}),ut=e=>({status:"dirty",value:e}),ht=e=>({status:"valid",value:e}),pt=e=>"aborted"===e.status,mt=e=>"dirty"===e.status,gt=e=>"valid"===e.status,ft=e=>"undefined"!=typeof Promise&&e instanceof Promise;function vt(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}function yt(e,t,i,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,i):s?s.value=i:t.set(e,i),i}var bt,kt,Tt,St;"function"==typeof SuppressedError&&SuppressedError,(kt=bt||(bt={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},kt.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class Ct{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const wt=(e,t)=>{if(gt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new nt(e.common.issues);return this._error=t,this._error}}};function Et(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:n,description:s}=e;if(t&&(i||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{var r,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:s.defaultError}:void 0===s.data?{message:null!==(r=null!=o?o:n)&&void 0!==r?r:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(a=null!=o?o:i)&&void 0!==a?a:s.defaultError}},description:s}}class _t{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new dt,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ft(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const n={common:{issues:[],async:null!==(i=null==t?void 0:t.async)&&void 0!==i&&i,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return wt(n,s)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return gt(t)?{value:t.value}:{issues:n.common.issues}}catch(s){(null===(i=null===(t=null==s?void 0:s.message)||void 0===t?void 0:t.toLowerCase())||void 0===i?void 0:i.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>gt(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},n=this._parse({data:e,path:i.path,parent:i}),s=await(ft(n)?n:Promise.resolve(n));return wt(i,s)}refine(e,t){const i=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),r=()=>n.addIssue({code:it.custom,...i(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(r(),!1))):!!s||(r(),!1)}))}refinement(e,t){return this._refinement(((i,n)=>!!e(i)||(n.addIssue("function"==typeof t?t(i,n):t),!1)))}_refinement(e){return new _i({schema:this,typeName:Fi.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Pi.create(this,this._def)}nullable(){return Ri.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oi.create(this)}promise(){return Ei.create(this,this._def)}or(e){return li.create([this,e],this._def)}and(e){return mi.create(this,e,this._def)}transform(e){return new _i({...Et(this._def),schema:this,typeName:Fi.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new xi({...Et(this._def),innerType:this,defaultValue:t,typeName:Fi.ZodDefault})}brand(){return new Ni({typeName:Fi.ZodBranded,type:this,...Et(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ii({...Et(this._def),innerType:this,catchValue:t,typeName:Fi.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Di.create(this,e)}readonly(){return Mi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Pt=/^c[^\s-]{8,}$/i,Rt=/^[0-9a-z]+$/,xt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,It=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ot=/^[a-z0-9_-]{21}$/i,At=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Dt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Mt;const Lt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ut=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ft=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",qt=new RegExp(`^${Vt}$`);function Zt(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function Kt(e){let t=`${Vt}T${Zt(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function zt(e,t){if(!At.test(e))return!1;try{const[i]=e.split("."),n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||!s.typ||!s.alg||t&&s.alg!==t)}catch(i){return!1}}function Ht(e,t){return!("v4"!==t&&t||!Ut.test(e))||!("v6"!==t&&t||!Ft.test(e))}class Gt extends _t{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==et.string){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.string,received:t.parsedType}),lt}const t=new dt;let i;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),ct(i,{code:it.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),ct(i,{code:it.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,s=e.data.length<a.value;(n||s)&&(i=this._getOrReturnCtx(e,i),n?ct(i,{code:it.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&ct(i,{code:it.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)Dt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"email",code:it.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)Mt||(Mt=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"emoji",code:it.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)It.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"uuid",code:it.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)Ot.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"nanoid",code:it.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)Pt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"cuid",code:it.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)Rt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"cuid2",code:it.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)xt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"ulid",code:it.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch(r){i=this._getOrReturnCtx(e,i),ct(i,{validation:"url",code:it.invalid_string,message:a.message}),t.dirty()}else"regex"===a.kind?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"regex",code:it.invalid_string,message:a.message}),t.dirty())):"trim"===a.kind?e.data=e.data.trim():"includes"===a.kind?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty()):"toLowerCase"===a.kind?e.data=e.data.toLowerCase():"toUpperCase"===a.kind?e.data=e.data.toUpperCase():"startsWith"===a.kind?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty()):"endsWith"===a.kind?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty()):"datetime"===a.kind?Kt(a).test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:"datetime",message:a.message}),t.dirty()):"date"===a.kind?qt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:"date",message:a.message}),t.dirty()):"time"===a.kind?new RegExp(`^${Zt(a)}$`).test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{code:it.invalid_string,validation:"time",message:a.message}),t.dirty()):"duration"===a.kind?Nt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"duration",code:it.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?(n=e.data,("v4"!==(s=a.version)&&s||!Lt.test(n))&&("v6"!==s&&s||!jt.test(n))&&(i=this._getOrReturnCtx(e,i),ct(i,{validation:"ip",code:it.invalid_string,message:a.message}),t.dirty())):"jwt"===a.kind?zt(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"jwt",code:it.invalid_string,message:a.message}),t.dirty()):"cidr"===a.kind?Ht(e.data,a.version)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"cidr",code:it.invalid_string,message:a.message}),t.dirty()):"base64"===a.kind?Bt.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"base64",code:it.invalid_string,message:a.message}),t.dirty()):"base64url"===a.kind?$t.test(e.data)||(i=this._getOrReturnCtx(e,i),ct(i,{validation:"base64url",code:it.invalid_string,message:a.message}),t.dirty()):Qe.assertNever(a);var n,s;return{status:t.value,value:e.data}}_regex(e,t,i){return this.refinement((t=>e.test(t)),{validation:t,code:it.invalid_string,...bt.errToObj(i)})}_addCheck(e){return new Gt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...bt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...bt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...bt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...bt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...bt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...bt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...bt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...bt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...bt.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...bt.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...bt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...bt.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...bt.errToObj(e)})}datetime(e){var t,i;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(i=null==e?void 0:e.local)&&void 0!==i&&i,...bt.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...bt.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...bt.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...bt.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...bt.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...bt.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...bt.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...bt.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...bt.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...bt.errToObj(t)})}nonempty(e){return this.min(1,bt.errToObj(e))}trim(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Gt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Wt(e,t){const i=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=i>n?i:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}Gt.create=e=>{var t;return new Gt({checks:[],typeName:Fi.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...Et(e)})};class Jt extends _t{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==et.number){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.number,received:t.parsedType}),lt}let t;const i=new dt;for(const n of this._def.checks)"int"===n.kind?Qe.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ct(t,{code:it.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==Wt(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ct(t,{code:it.not_finite,message:n.message}),i.dirty()):Qe.assertNever(n);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,bt.toString(t))}gt(e,t){return this.setLimit("min",e,!1,bt.toString(t))}lte(e,t){return this.setLimit("max",e,!0,bt.toString(t))}lt(e,t){return this.setLimit("max",e,!1,bt.toString(t))}setLimit(e,t,i,n){return new Jt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:bt.toString(n)}]})}_addCheck(e){return new Jt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:bt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:bt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:bt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:bt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:bt.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:bt.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:bt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:bt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:bt.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&Qe.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;"min"===i.kind?(null===t||i.value>t)&&(t=i.value):"max"===i.kind&&(null===e||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Jt.create=e=>new Jt({checks:[],typeName:Fi.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...Et(e)});class Qt extends _t{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==et.bigint)return this._getInvalidInput(e);let t;const i=new dt;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),ct(t,{code:it.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Qe.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.bigint,received:t.parsedType}),lt}gte(e,t){return this.setLimit("min",e,!0,bt.toString(t))}gt(e,t){return this.setLimit("min",e,!1,bt.toString(t))}lte(e,t){return this.setLimit("max",e,!0,bt.toString(t))}lt(e,t){return this.setLimit("max",e,!1,bt.toString(t))}setLimit(e,t,i,n){return new Qt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:bt.toString(n)}]})}_addCheck(e){return new Qt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:bt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:bt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:bt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:bt.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:bt.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Qt.create=e=>{var t;return new Qt({checks:[],typeName:Fi.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...Et(e)})};class Yt extends _t{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==et.boolean){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.boolean,received:t.parsedType}),lt}return ht(e.data)}}Yt.create=e=>new Yt({typeName:Fi.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...Et(e)});class Xt extends _t{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==et.date){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.date,received:t.parsedType}),lt}if(isNaN(e.data.getTime()))return ct(this._getOrReturnCtx(e),{code:it.invalid_date}),lt;const t=new dt;let i;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(i=this._getOrReturnCtx(e,i),ct(i,{code:it.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(i=this._getOrReturnCtx(e,i),ct(i,{code:it.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):Qe.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Xt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:bt.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:bt.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Xt.create=e=>new Xt({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Fi.ZodDate,...Et(e)});class ei extends _t{_parse(e){if(this._getType(e)!==et.symbol){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.symbol,received:t.parsedType}),lt}return ht(e.data)}}ei.create=e=>new ei({typeName:Fi.ZodSymbol,...Et(e)});class ti extends _t{_parse(e){if(this._getType(e)!==et.undefined){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.undefined,received:t.parsedType}),lt}return ht(e.data)}}ti.create=e=>new ti({typeName:Fi.ZodUndefined,...Et(e)});class ii extends _t{_parse(e){if(this._getType(e)!==et.null){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.null,received:t.parsedType}),lt}return ht(e.data)}}ii.create=e=>new ii({typeName:Fi.ZodNull,...Et(e)});class ni extends _t{constructor(){super(...arguments),this._any=!0}_parse(e){return ht(e.data)}}ni.create=e=>new ni({typeName:Fi.ZodAny,...Et(e)});class si extends _t{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ht(e.data)}}si.create=e=>new si({typeName:Fi.ZodUnknown,...Et(e)});class ri extends _t{_parse(e){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.never,received:t.parsedType}),lt}}ri.create=e=>new ri({typeName:Fi.ZodNever,...Et(e)});class ai extends _t{_parse(e){if(this._getType(e)!==et.undefined){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.void,received:t.parsedType}),lt}return ht(e.data)}}ai.create=e=>new ai({typeName:Fi.ZodVoid,...Et(e)});class oi extends _t{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==et.array)return ct(t,{code:it.invalid_type,expected:et.array,received:t.parsedType}),lt;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(ct(t,{code:e?it.too_big:it.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(ct(t,{code:it.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(ct(t,{code:it.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map(((e,i)=>n.type._parseAsync(new Ct(t,e,t.path,i))))).then((e=>dt.mergeArray(i,e)));const s=[...t.data].map(((e,i)=>n.type._parseSync(new Ct(t,e,t.path,i))));return dt.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new oi({...this._def,minLength:{value:e,message:bt.toString(t)}})}max(e,t){return new oi({...this._def,maxLength:{value:e,message:bt.toString(t)}})}length(e,t){return new oi({...this._def,exactLength:{value:e,message:bt.toString(t)}})}nonempty(e){return this.min(1,e)}}function ci(e){if(e instanceof di){const t={};for(const i in e.shape){const n=e.shape[i];t[i]=Pi.create(ci(n))}return new di({...e._def,shape:()=>t})}return e instanceof oi?new oi({...e._def,type:ci(e.element)}):e instanceof Pi?Pi.create(ci(e.unwrap())):e instanceof Ri?Ri.create(ci(e.unwrap())):e instanceof gi?gi.create(e.items.map((e=>ci(e)))):e}oi.create=(e,t)=>new oi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Fi.ZodArray,...Et(t)});class di extends _t{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Qe.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==et.object){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.object,received:t.parsedType}),lt}const{status:t,ctx:i}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),r=[];if(!(this._def.catchall instanceof ri&&"strip"===this._def.unknownKeys))for(const o in i.data)s.includes(o)||r.push(o);const a=[];for(const o of s){const e=n[o],t=i.data[o];a.push({key:{status:"valid",value:o},value:e._parse(new Ct(i,t,i.path,o)),alwaysSet:o in i.data})}if(this._def.catchall instanceof ri){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of r)a.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===e)r.length>0&&(ct(i,{code:it.unrecognized_keys,keys:r}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of r){const n=i.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new Ct(i,n,i.path,t)),alwaysSet:t in i.data})}}return i.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const i=await t.key,n=await t.value;e.push({key:i,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>dt.mergeObjectSync(t,e))):dt.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return bt.errToObj,new di({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,i)=>{var n,s,r,a;const o=null!==(r=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,i).message)&&void 0!==r?r:i.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=bt.errToObj(e).message)&&void 0!==a?a:o}:{message:o}}}:{}})}strip(){return new di({...this._def,unknownKeys:"strip"})}passthrough(){return new di({...this._def,unknownKeys:"passthrough"})}extend(e){return new di({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new di({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Fi.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new di({...this._def,catchall:e})}pick(e){const t={};return Qe.objectKeys(e).forEach((i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])})),new di({...this._def,shape:()=>t})}omit(e){const t={};return Qe.objectKeys(this.shape).forEach((i=>{e[i]||(t[i]=this.shape[i])})),new di({...this._def,shape:()=>t})}deepPartial(){return ci(this)}partial(e){const t={};return Qe.objectKeys(this.shape).forEach((i=>{const n=this.shape[i];e&&!e[i]?t[i]=n:t[i]=n.optional()})),new di({...this._def,shape:()=>t})}required(e){const t={};return Qe.objectKeys(this.shape).forEach((i=>{if(e&&!e[i])t[i]=this.shape[i];else{let e=this.shape[i];for(;e instanceof Pi;)e=e._def.innerType;t[i]=e}})),new di({...this._def,shape:()=>t})}keyof(){return Si(Qe.objectKeys(this.shape))}}di.create=(e,t)=>new di({shape:()=>e,unknownKeys:"strip",catchall:ri.create(),typeName:Fi.ZodObject,...Et(t)}),di.strictCreate=(e,t)=>new di({shape:()=>e,unknownKeys:"strict",catchall:ri.create(),typeName:Fi.ZodObject,...Et(t)}),di.lazycreate=(e,t)=>new di({shape:e,unknownKeys:"strip",catchall:ri.create(),typeName:Fi.ZodObject,...Et(t)});class li extends _t{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;if(t.common.async)return Promise.all(i.map((async e=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const i=e.map((e=>new nt(e.ctx.common.issues)));return ct(t,{code:it.invalid_union,unionErrors:i}),lt}));{let e;const n=[];for(const r of i){const i={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:i});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new nt(e)));return ct(t,{code:it.invalid_union,unionErrors:s}),lt}}get options(){return this._def.options}}li.create=(e,t)=>new li({options:e,typeName:Fi.ZodUnion,...Et(t)});const ui=e=>e instanceof ki?ui(e.schema):e instanceof _i?ui(e.innerType()):e instanceof Ti?[e.value]:e instanceof Ci?e.options:e instanceof wi?Qe.objectValues(e.enum):e instanceof xi?ui(e._def.innerType):e instanceof ti?[void 0]:e instanceof ii?[null]:e instanceof Pi?[void 0,...ui(e.unwrap())]:e instanceof Ri?[null,...ui(e.unwrap())]:e instanceof Ni||e instanceof Mi?ui(e.unwrap()):e instanceof Ii?ui(e._def.innerType):[];class hi extends _t{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==et.object)return ct(t,{code:it.invalid_type,expected:et.object,received:t.parsedType}),lt;const i=this.discriminator,n=t.data[i],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(ct(t,{code:it.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),lt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const s of t){const t=ui(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new hi({typeName:Fi.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...Et(i)})}}function pi(e,t){const i=tt(e),n=tt(t);if(e===t)return{valid:!0,data:e};if(i===et.object&&n===et.object){const i=Qe.objectKeys(t),n=Qe.objectKeys(e).filter((e=>-1!==i.indexOf(e))),s={...e,...t};for(const r of n){const i=pi(e[r],t[r]);if(!i.valid)return{valid:!1};s[r]=i.data}return{valid:!0,data:s}}if(i===et.array&&n===et.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let n=0;n<e.length;n++){const s=pi(e[n],t[n]);if(!s.valid)return{valid:!1};i.push(s.data)}return{valid:!0,data:i}}return i===et.date&&n===et.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class mi extends _t{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(e,n)=>{if(pt(e)||pt(n))return lt;const s=pi(e.value,n.value);return s.valid?((mt(e)||mt(n))&&t.dirty(),{status:t.value,value:s.data}):(ct(i,{code:it.invalid_intersection_types}),lt)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}mi.create=(e,t,i)=>new mi({left:e,right:t,typeName:Fi.ZodIntersection,...Et(i)});class gi extends _t{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==et.array)return ct(i,{code:it.invalid_type,expected:et.array,received:i.parsedType}),lt;if(i.data.length<this._def.items.length)return ct(i,{code:it.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),lt;!this._def.rest&&i.data.length>this._def.items.length&&(ct(i,{code:it.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new Ct(i,e,i.path,t)):null})).filter((e=>!!e));return i.common.async?Promise.all(n).then((e=>dt.mergeArray(t,e))):dt.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new gi({...this._def,rest:e})}}gi.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gi({items:e,typeName:Fi.ZodTuple,rest:null,...Et(t)})};class fi extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==et.object)return ct(i,{code:it.invalid_type,expected:et.object,received:i.parsedType}),lt;const n=[],s=this._def.keyType,r=this._def.valueType;for(const a in i.data)n.push({key:s._parse(new Ct(i,a,i.path,a)),value:r._parse(new Ct(i,i.data[a],i.path,a)),alwaysSet:a in i.data});return i.common.async?dt.mergeObjectAsync(t,n):dt.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return new fi(t instanceof _t?{keyType:e,valueType:t,typeName:Fi.ZodRecord,...Et(i)}:{keyType:Gt.create(),valueType:e,typeName:Fi.ZodRecord,...Et(t)})}}class vi extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==et.map)return ct(i,{code:it.invalid_type,expected:et.map,received:i.parsedType}),lt;const n=this._def.keyType,s=this._def.valueType,r=[...i.data.entries()].map((([e,t],r)=>({key:n._parse(new Ct(i,e,i.path,[r,"key"])),value:s._parse(new Ct(i,t,i.path,[r,"value"]))})));if(i.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const i of r){const n=await i.key,s=await i.value;if("aborted"===n.status||"aborted"===s.status)return lt;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const i of r){const n=i.key,s=i.value;if("aborted"===n.status||"aborted"===s.status)return lt;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}vi.create=(e,t,i)=>new vi({valueType:t,keyType:e,typeName:Fi.ZodMap,...Et(i)});class yi extends _t{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==et.set)return ct(i,{code:it.invalid_type,expected:et.set,received:i.parsedType}),lt;const n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(ct(i,{code:it.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(ct(i,{code:it.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function r(e){const i=new Set;for(const n of e){if("aborted"===n.status)return lt;"dirty"===n.status&&t.dirty(),i.add(n.value)}return{status:t.value,value:i}}const a=[...i.data.values()].map(((e,t)=>s._parse(new Ct(i,e,i.path,t))));return i.common.async?Promise.all(a).then((e=>r(e))):r(a)}min(e,t){return new yi({...this._def,minSize:{value:e,message:bt.toString(t)}})}max(e,t){return new yi({...this._def,maxSize:{value:e,message:bt.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}yi.create=(e,t)=>new yi({valueType:e,minSize:null,maxSize:null,typeName:Fi.ZodSet,...Et(t)});class bi extends _t{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==et.function)return ct(t,{code:it.invalid_type,expected:et.function,received:t.parsedType}),lt;function i(e,i){return ot({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,at(),st].filter((e=>!!e)),issueData:{code:it.invalid_arguments,argumentsError:i}})}function n(e,i){return ot({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,at(),st].filter((e=>!!e)),issueData:{code:it.invalid_return_type,returnTypeError:i}})}const s={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof Ei){const e=this;return ht((async function(...t){const a=new nt([]),o=await e._def.args.parseAsync(t,s).catch((e=>{throw a.addIssue(i(t,e)),a})),c=await Reflect.apply(r,this,o);return await e._def.returns._def.type.parseAsync(c,s).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return ht((function(...t){const a=e._def.args.safeParse(t,s);if(!a.success)throw new nt([i(t,a.error)]);const o=Reflect.apply(r,this,a.data),c=e._def.returns.safeParse(o,s);if(!c.success)throw new nt([n(o,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new bi({...this._def,args:gi.create(e).rest(si.create())})}returns(e){return new bi({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new bi({args:e||gi.create([]).rest(si.create()),returns:t||si.create(),typeName:Fi.ZodFunction,...Et(i)})}}class ki extends _t{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ki.create=(e,t)=>new ki({getter:e,typeName:Fi.ZodLazy,...Et(t)});class Ti extends _t{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ct(t,{received:t.data,code:it.invalid_literal,expected:this._def.value}),lt}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Si(e,t){return new Ci({values:e,typeName:Fi.ZodEnum,...Et(t)})}Ti.create=(e,t)=>new Ti({value:e,typeName:Fi.ZodLiteral,...Et(t)});class Ci extends _t{constructor(){super(...arguments),Tt.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),i=this._def.values;return ct(t,{expected:Qe.joinValues(i),received:t.parsedType,code:it.invalid_type}),lt}if(vt(this,Tt,"f")||yt(this,Tt,new Set(this._def.values),"f"),!vt(this,Tt,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return ct(t,{received:t.data,code:it.invalid_enum_value,options:i}),lt}return ht(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ci.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ci.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}Tt=new WeakMap,Ci.create=Si;class wi extends _t{constructor(){super(...arguments),St.set(this,void 0)}_parse(e){const t=Qe.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==et.string&&i.parsedType!==et.number){const e=Qe.objectValues(t);return ct(i,{expected:Qe.joinValues(e),received:i.parsedType,code:it.invalid_type}),lt}if(vt(this,St,"f")||yt(this,St,new Set(Qe.getValidEnumValues(this._def.values)),"f"),!vt(this,St,"f").has(e.data)){const e=Qe.objectValues(t);return ct(i,{received:i.data,code:it.invalid_enum_value,options:e}),lt}return ht(e.data)}get enum(){return this._def.values}}St=new WeakMap,wi.create=(e,t)=>new wi({values:e,typeName:Fi.ZodNativeEnum,...Et(t)});class Ei extends _t{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==et.promise&&!1===t.common.async)return ct(t,{code:it.invalid_type,expected:et.promise,received:t.parsedType}),lt;const i=t.parsedType===et.promise?t.data:Promise.resolve(t.data);return ht(i.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Ei.create=(e,t)=>new Ei({type:e,typeName:Fi.ZodPromise,...Et(t)});class _i extends _t{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{ct(i,e),e.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(i.data,s);if(i.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return lt;const n=await this._def.schema._parseAsync({data:e,path:i.path,parent:i});return"aborted"===n.status?lt:"dirty"===n.status||"dirty"===t.value?ut(n.value):n}));{if("aborted"===t.value)return lt;const n=this._def.schema._parseSync({data:e,path:i.path,parent:i});return"aborted"===n.status?lt:"dirty"===n.status||"dirty"===t.value?ut(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(i.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===i.common.async){const n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?lt:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((i=>"aborted"===i.status?lt:("dirty"===i.status&&t.dirty(),e(i.value).then((()=>({status:t.value,value:i.value}))))))}if("transform"===n.type){if(!1===i.common.async){const e=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!gt(e))return e;const r=n.transform(e.value,s);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((e=>gt(e)?Promise.resolve(n.transform(e.value,s)).then((e=>({status:t.value,value:e}))):e))}Qe.assertNever(n)}}_i.create=(e,t,i)=>new _i({schema:e,typeName:Fi.ZodEffects,effect:t,...Et(i)}),_i.createWithPreprocess=(e,t,i)=>new _i({schema:t,effect:{type:"preprocess",transform:e},typeName:Fi.ZodEffects,...Et(i)});class Pi extends _t{_parse(e){return this._getType(e)===et.undefined?ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pi.create=(e,t)=>new Pi({innerType:e,typeName:Fi.ZodOptional,...Et(t)});class Ri extends _t{_parse(e){return this._getType(e)===et.null?ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ri.create=(e,t)=>new Ri({innerType:e,typeName:Fi.ZodNullable,...Et(t)});class xi extends _t{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===et.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}xi.create=(e,t)=>new xi({innerType:e,typeName:Fi.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Et(t)});class Ii extends _t{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return ft(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new nt(i.common.issues)},input:i.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new nt(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Ii.create=(e,t)=>new Ii({innerType:e,typeName:Fi.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Et(t)});class Oi extends _t{_parse(e){if(this._getType(e)!==et.nan){const t=this._getOrReturnCtx(e);return ct(t,{code:it.invalid_type,expected:et.nan,received:t.parsedType}),lt}return{status:"valid",value:e.data}}}Oi.create=e=>new Oi({typeName:Fi.ZodNaN,...Et(e)});const Ai=Symbol("zod_brand");class Ni extends _t{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Di extends _t{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?lt:"dirty"===e.status?(t.dirty(),ut(e.value)):this._def.out._parseAsync({data:e.value,path:i.path,parent:i})})();{const e=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?lt:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:i.path,parent:i})}}static create(e,t){return new Di({in:e,out:t,typeName:Fi.ZodPipeline})}}class Mi extends _t{_parse(e){const t=this._def.innerType._parse(e),i=e=>(gt(e)&&(e.value=Object.freeze(e.value)),e);return ft(t)?t.then((e=>i(e))):i(t)}unwrap(){return this._def.innerType}}function Li(e,t){const i="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof i?{message:i}:i}function Ui(e,t={},i){return e?ni.create().superRefine(((n,s)=>{var r,a;const o=e(n);if(o instanceof Promise)return o.then((e=>{var r,a;if(!e){const e=Li(t,n),o=null===(a=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===a||a;s.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=Li(t,n),o=null===(a=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===a||a;s.addIssue({code:"custom",...e,fatal:o})}})):ni.create()}Mi.create=(e,t)=>new Mi({innerType:e,typeName:Fi.ZodReadonly,...Et(t)});const ji={object:di.lazycreate};var Fi,Bi;(Bi=Fi||(Fi={})).ZodString="ZodString",Bi.ZodNumber="ZodNumber",Bi.ZodNaN="ZodNaN",Bi.ZodBigInt="ZodBigInt",Bi.ZodBoolean="ZodBoolean",Bi.ZodDate="ZodDate",Bi.ZodSymbol="ZodSymbol",Bi.ZodUndefined="ZodUndefined",Bi.ZodNull="ZodNull",Bi.ZodAny="ZodAny",Bi.ZodUnknown="ZodUnknown",Bi.ZodNever="ZodNever",Bi.ZodVoid="ZodVoid",Bi.ZodArray="ZodArray",Bi.ZodObject="ZodObject",Bi.ZodUnion="ZodUnion",Bi.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Bi.ZodIntersection="ZodIntersection",Bi.ZodTuple="ZodTuple",Bi.ZodRecord="ZodRecord",Bi.ZodMap="ZodMap",Bi.ZodSet="ZodSet",Bi.ZodFunction="ZodFunction",Bi.ZodLazy="ZodLazy",Bi.ZodLiteral="ZodLiteral",Bi.ZodEnum="ZodEnum",Bi.ZodEffects="ZodEffects",Bi.ZodNativeEnum="ZodNativeEnum",Bi.ZodOptional="ZodOptional",Bi.ZodNullable="ZodNullable",Bi.ZodDefault="ZodDefault",Bi.ZodCatch="ZodCatch",Bi.ZodPromise="ZodPromise",Bi.ZodBranded="ZodBranded",Bi.ZodPipeline="ZodPipeline",Bi.ZodReadonly="ZodReadonly";const $i=Gt.create,Vi=Jt.create,qi=Oi.create,Zi=Qt.create,Ki=Yt.create,zi=Xt.create,Hi=ei.create,Gi=ti.create,Wi=ii.create,Ji=ni.create,Qi=si.create,Yi=ri.create,Xi=ai.create,en=oi.create,tn=di.create,nn=di.strictCreate,sn=li.create,rn=hi.create,an=mi.create,on=gi.create,cn=fi.create,dn=vi.create,ln=yi.create,un=bi.create,hn=ki.create,pn=Ti.create,mn=Ci.create,gn=wi.create,fn=Ei.create,vn=_i.create,yn=Pi.create,bn=Ri.create,kn=_i.createWithPreprocess,Tn=Di.create,Sn={string:e=>Gt.create({...e,coerce:!0}),number:e=>Jt.create({...e,coerce:!0}),boolean:e=>Yt.create({...e,coerce:!0}),bigint:e=>Qt.create({...e,coerce:!0}),date:e=>Xt.create({...e,coerce:!0})},Cn=lt;var wn=Object.freeze({__proto__:null,defaultErrorMap:st,setErrorMap:function(e){rt=e},getErrorMap:at,makeIssue:ot,EMPTY_PATH:[],addIssueToContext:ct,ParseStatus:dt,INVALID:lt,DIRTY:ut,OK:ht,isAborted:pt,isDirty:mt,isValid:gt,isAsync:ft,get util(){return Qe},get objectUtil(){return Xe},ZodParsedType:et,getParsedType:tt,ZodType:_t,datetimeRegex:Kt,ZodString:Gt,ZodNumber:Jt,ZodBigInt:Qt,ZodBoolean:Yt,ZodDate:Xt,ZodSymbol:ei,ZodUndefined:ti,ZodNull:ii,ZodAny:ni,ZodUnknown:si,ZodNever:ri,ZodVoid:ai,ZodArray:oi,ZodObject:di,ZodUnion:li,ZodDiscriminatedUnion:hi,ZodIntersection:mi,ZodTuple:gi,ZodRecord:fi,ZodMap:vi,ZodSet:yi,ZodFunction:bi,ZodLazy:ki,ZodLiteral:Ti,ZodEnum:Ci,ZodNativeEnum:wi,ZodPromise:Ei,ZodEffects:_i,ZodTransformer:_i,ZodOptional:Pi,ZodNullable:Ri,ZodDefault:xi,ZodCatch:Ii,ZodNaN:Oi,BRAND:Ai,ZodBranded:Ni,ZodPipeline:Di,ZodReadonly:Mi,custom:Ui,Schema:_t,ZodSchema:_t,late:ji,get ZodFirstPartyTypeKind(){return Fi},coerce:Sn,any:Ji,array:en,bigint:Zi,boolean:Ki,date:zi,discriminatedUnion:rn,effect:vn,enum:mn,function:un,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ui((t=>t instanceof e),t),intersection:an,lazy:hn,literal:pn,map:dn,nan:qi,nativeEnum:gn,never:Yi,null:Wi,nullable:bn,number:Vi,object:tn,oboolean:()=>Ki().optional(),onumber:()=>Vi().optional(),optional:yn,ostring:()=>$i().optional(),pipeline:Tn,preprocess:kn,promise:fn,record:cn,set:ln,strictObject:nn,string:$i,symbol:Hi,transformer:vn,tuple:on,undefined:Gi,union:sn,unknown:Qi,void:Xi,NEVER:Cn,ZodIssueCode:it,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:nt});const En="https://iamobi.ai/api",_n=wn.object({apiKey:wn.string().optional(),enableVoice:wn.boolean().default(!0),enableScreenCapture:wn.boolean().default(!0),debug:wn.boolean().default(!1),user:wn.object({id:wn.string(),email:wn.string().optional(),metadata:wn.any().optional()}).optional()});var Pn=(e=>(e.READY="ready",e.ERROR="error",e.VOICE_START="voice:start",e.VOICE_STOP="voice:stop",e.SCREEN_CAPTURE_START="screen:start",e.SCREEN_CAPTURE_STOP="screen:stop",e.STATE_CHANGE="state:change",e))(Pn||{}),Rn=(e=>(e.READY="ready",e.ERROR="error",e.PAUSED="paused",e.LOADING="loading",e.THINKING="thinking",e.RESEARCHING="researching",e.AGENT_SPEAKING="agent_speaking",e.USER_SPEAKING="user_speaking",e.AWAITING_USER_INPUT="awaiting_user_input",e))(Rn||{}),xn=Object.defineProperty,In=Object.getOwnPropertyDescriptor,On=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?In(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&xn(t,i,r),r};class An extends oe{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return q`
1
+ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,n=Symbol(),s=new WeakMap;let r=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==n)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(i&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=s.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&s.set(t,e))}return e}toString(){return this.cssText}};const o=(e,...t)=>{const i=1===e.length?e[0]:t.reduce(((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1]),e[0]);return new r(i,e,n)},a=i?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new r("string"==typeof e?e:e+"",void 0,n))(t)})(e):e,{is:c,defineProperty:d,getOwnPropertyDescriptor:l,getOwnPropertyNames:u,getOwnPropertySymbols:h,getPrototypeOf:p}=Object,m=globalThis,g=m.trustedTypes,f=g?g.emptyScript:"",v=m.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?f:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(n){i=null}}return i}},k=(e,t)=>!c(e,t),T={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:k};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),m.litPropertyMetadata??(m.litPropertyMetadata=new WeakMap);let S=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=T){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&d(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=l(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const r=n?.call(this);s?.call(this,t),this.requestUpdate(e,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??T}static _$Ei(){if(this.hasOwnProperty(y("elementProperties")))return;const e=p(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y("properties"))){const e=this.properties,t=[...u(e),...h(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const e=this._$Eu(t,i);void 0!==e&&this._$Eh.set(e,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(a(e))}else void 0!==e&&t.push(a(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,n)=>{if(i)e.adoptedStyleSheets=n.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const i of n){const n=document.createElement("style"),s=t.litNonce;void 0!==s&&n.setAttribute("nonce",s),n.textContent=i.cssText,e.appendChild(n)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:b).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:b;this._$Em=n,this[n]=s.fromAttribute(t,e.type)??this._$Ej?.get(n)??null,this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){const n=this.constructor,s=this[e];if(i??(i=n.getPropertyOptions(e)),!((i.hasChanged??k)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,r??t??this[e]),!0!==s||void 0!==r)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(e){}firstUpdated(e){}};S.elementStyles=[],S.shadowRootOptions={mode:"open"},S[y("elementProperties")]=new Map,S[y("finalized")]=new Map,v?.({ReactiveElement:S}),(m.reactiveElementVersions??(m.reactiveElementVersions=[])).push("2.1.0");const C=globalThis,w=C.trustedTypes,E=w?w.createPolicy("lit-html",{createHTML:e=>e}):void 0,_="$lit$",P=`lit$${Math.random().toFixed(9).slice(2)}$`,R="?"+P,x=`<${R}>`,I=document,O=()=>I.createComment(""),A=e=>null===e||"object"!=typeof e&&"function"!=typeof e,N=Array.isArray,D="[ \t\n\f\r]",M=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,L=/-->/g,U=/>/g,j=RegExp(`>|${D}(?:([^\\s"'>=/]+)(${D}*=${D}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),F=/'/g,$=/"/g,B=/^(?:script|style|textarea|title)$/i,V=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),q=V(1),Z=V(2),H=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),K=new WeakMap,G=I.createTreeWalker(I,129);function W(e,t){if(!N(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==E?E.createHTML(t):t}let J=class e{constructor({strings:t,_$litType$:i},n){let s;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[d,l]=((e,t)=>{const i=e.length-1,n=[];let s,r=2===t?"<svg>":3===t?"<math>":"",o=M;for(let a=0;a<i;a++){const t=e[a];let i,c,d=-1,l=0;for(;l<t.length&&(o.lastIndex=l,c=o.exec(t),null!==c);)l=o.lastIndex,o===M?"!--"===c[1]?o=L:void 0!==c[1]?o=U:void 0!==c[2]?(B.test(c[2])&&(s=RegExp("</"+c[2],"g")),o=j):void 0!==c[3]&&(o=j):o===j?">"===c[0]?(o=s??M,d=-1):void 0===c[1]?d=-2:(d=o.lastIndex-c[2].length,i=c[1],o=void 0===c[3]?j:'"'===c[3]?$:F):o===$||o===F?o=j:o===L||o===U?o=M:(o=j,s=void 0);const u=o===j&&e[a+1].startsWith("/>")?" ":"";r+=o===M?t+x:d>=0?(n.push(i),t.slice(0,d)+_+t.slice(d)+P+u):t+P+(-2===d?a:u)}return[W(e,r+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]})(t,i);if(this.el=e.createElement(d,n),G.currentNode=this.el.content,2===i||3===i){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(s=G.nextNode())&&c.length<a;){if(1===s.nodeType){if(s.hasAttributes())for(const e of s.getAttributeNames())if(e.endsWith(_)){const t=l[o++],i=s.getAttribute(e).split(P),n=/([.?@])?(.*)/.exec(t);c.push({type:1,index:r,name:n[2],strings:i,ctor:"."===n[1]?te:"?"===n[1]?ie:"@"===n[1]?ne:ee}),s.removeAttribute(e)}else e.startsWith(P)&&(c.push({type:6,index:r}),s.removeAttribute(e));if(B.test(s.tagName)){const e=s.textContent.split(P),t=e.length-1;if(t>0){s.textContent=w?w.emptyScript:"";for(let i=0;i<t;i++)s.append(e[i],O()),G.nextNode(),c.push({type:2,index:++r});s.append(e[t],O())}}}else if(8===s.nodeType)if(s.data===R)c.push({type:2,index:r});else{let e=-1;for(;-1!==(e=s.data.indexOf(P,e+1));)c.push({type:7,index:r}),e+=P.length-1}r++}}static createElement(e,t){const i=I.createElement("template");return i.innerHTML=e,i}};function Q(e,t,i=e,n){if(t===H)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const r=A(t)?void 0:t._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),void 0===r?s=void 0:(s=new r(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??(i._$Co=[]))[n]=s:i._$Cl=s),void 0!==s&&(t=Q(e,s._$AS(e,t.values),s,n)),t}class Y{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??I).importNode(t,!0);G.currentNode=n;let s=G.nextNode(),r=0,o=0,a=i[0];for(;void 0!==a;){if(r===a.index){let t;2===a.type?t=new X(s,s.nextSibling,this,e):1===a.type?t=new a.ctor(s,a.name,a.strings,this,e):6===a.type&&(t=new se(s,this,e)),this._$AV.push(t),a=i[++o]}r!==a?.index&&(s=G.nextNode(),r++)}return G.currentNode=I,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class X{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Q(this,e,t),A(e)?e===z||null==e||""===e?(this._$AH!==z&&this._$AR(),this._$AH=z):e!==this._$AH&&e!==H&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>N(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==z&&A(this._$AH)?this._$AA.nextSibling.data=e:this.T(I.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=J.createElement(W(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new Y(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=K.get(e.strings);return void 0===t&&K.set(e.strings,t=new J(e)),t}k(e){N(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const s of e)n===t.length?t.push(i=new X(this.O(O()),this.O(O()),this,this.options)):i=t[n],i._$AI(s),n++;n<t.length&&(this._$AR(i&&i._$AB.nextSibling,n),t.length=n)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}let ee=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=z,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=z}_$AI(e,t=this,i,n){const s=this.strings;let r=!1;if(void 0===s)e=Q(this,e,t,0),r=!A(e)||e!==this._$AH&&e!==H,r&&(this._$AH=e);else{const n=e;let o,a;for(e=s[0],o=0;o<s.length-1;o++)a=Q(this,n[i+o],t,o),a===H&&(a=this._$AH[o]),r||(r=!A(a)||a!==this._$AH[o]),a===z?e=z:e!==z&&(e+=(a??"")+s[o+1]),this._$AH[o]=a}r&&!n&&this.j(e)}j(e){e===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}};class te extends ee{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===z?void 0:e}}let ie=class extends ee{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==z)}},ne=class extends ee{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=Q(this,e,t,0)??z)===H)return;const i=this._$AH,n=e===z&&i!==z||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==z&&(i===z||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},se=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){Q(this,e)}};const re=C.litHtmlPolyfillSupport;re?.(J,X),(C.litHtmlVersions??(C.litHtmlVersions=[])).push("3.3.0");const oe=globalThis;let ae=class extends S{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new X(t.insertBefore(O(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return H}};ae._$litElement$=!0,ae.finalized=!0,oe.litElementHydrateSupport?.({LitElement:ae});const ce=oe.litElementPolyfillSupport;ce?.({LitElement:ae}),(oe.litElementVersions??(oe.litElementVersions=[])).push("4.2.0");const de={attribute:!0,type:String,converter:b,reflect:!1,hasChanged:k},le=(e=de,t,i)=>{const{kind:n,metadata:s}=i;let r=globalThis.litPropertyMetadata.get(s);if(void 0===r&&globalThis.litPropertyMetadata.set(s,r=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e)}}throw Error("Unsupported decorator location: "+n)};function ue(e){return(t,i)=>"object"==typeof i?le(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function he(e){return ue({...e,state:!0,attribute:!1})}const pe=Symbol.for("@ts-pattern/matcher"),me=Symbol.for("@ts-pattern/isVariadic"),ge="@ts-pattern/anonymous-select-key",fe=e=>Boolean(e&&"object"==typeof e),ve=e=>e&&!!e[pe],ye=(e,t,i)=>{if(ve(e)){const n=e[pe](),{matched:s,selections:r}=n.match(t);return s&&r&&Object.keys(r).forEach((e=>i(e,r[e]))),s}if(fe(e)){if(!fe(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=[],s=[],r=[];for(const t of e.keys()){const i=e[t];ve(i)&&i[me]?r.push(i):r.length?s.push(i):n.push(i)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<n.length+s.length)return!1;const e=t.slice(0,n.length),o=0===s.length?[]:t.slice(-s.length),a=t.slice(n.length,0===s.length?1/0:-s.length);return n.every(((t,n)=>ye(t,e[n],i)))&&s.every(((e,t)=>ye(e,o[t],i)))&&(0===r.length||ye(r[0],a,i))}return e.length===t.length&&e.every(((e,n)=>ye(e,t[n],i)))}return Reflect.ownKeys(e).every((n=>{const s=e[n];return(n in t||ve(r=s)&&"optional"===r[pe]().matcherType)&&ye(s,t[n],i);var r}))}return Object.is(t,e)},be=e=>{var t,i,n;return fe(e)?ve(e)?null!=(t=null==(i=(n=e[pe]()).getSelectionKeys)?void 0:i.call(n))?t:[]:Array.isArray(e)?ke(e,be):ke(Object.values(e),be):[]},ke=(e,t)=>e.reduce(((e,i)=>e.concat(t(i))),[]);function Te(e){return Object.assign(e,{optional:()=>Ce(e),and:t=>_e(e,t),or:t=>Pe(e,t),select:t=>void 0===t?xe(e):xe(t,e)})}function Se(e){return Object.assign((t=e,Object.assign(t,{[Symbol.iterator](){let e=0;const i=[{value:Object.assign(t,{[me]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var t;return null!=(t=i[e++])?t:i.at(-1)}}}})),{optional:()=>Se(Ce(e)),select:t=>Se(void 0===t?xe(e):xe(t,e))});var t}function Ce(e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return void 0===t?(be(e).forEach((e=>n(e,void 0))),{matched:!0,selections:i}):{matched:ye(e,t,n),selections:i}},getSelectionKeys:()=>be(e),matcherType:"optional"})})}const we=(e,t)=>{for(const i of e)if(!t(i))return!1;return!0},Ee=(e,t)=>{for(const[i,n]of e.entries())if(!t(n,i))return!1;return!0};function _e(...e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return{matched:e.every((e=>ye(e,t,n))),selections:i}},getSelectionKeys:()=>ke(e,be),matcherType:"and"})})}function Pe(...e){return Te({[pe]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return ke(e,be).forEach((e=>n(e,void 0))),{matched:e.some((e=>ye(e,t,n))),selections:i}},getSelectionKeys:()=>ke(e,be),matcherType:"or"})})}function Re(e){return{[pe]:()=>({match:t=>({matched:Boolean(e(t))})})}}function xe(...e){const t="string"==typeof e[0]?e[0]:void 0,i=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return Te({[pe]:()=>({match:e=>{let n={[null!=t?t:ge]:e};return{matched:void 0===i||ye(i,e,((e,t)=>{n[e]=t})),selections:n}},getSelectionKeys:()=>[null!=t?t:ge].concat(void 0===i?[]:be(i))})})}function Ie(e){return"number"==typeof e}function Oe(e){return"string"==typeof e}function Ae(e){return"bigint"==typeof e}const Ne=Te(Re((function(e){return!0}))),De=Ne,Me=e=>Object.assign(Te(e),{startsWith:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.startsWith(i))))));var i},endsWith:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.endsWith(i))))));var i},minLength:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length>=i)))));var i},length:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length===i)))));var i},maxLength:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.length<=i)))));var i},includes:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&e.includes(i))))));var i},regex:t=>{return Me(_e(e,(i=t,Re((e=>Oe(e)&&Boolean(e.match(i)))))));var i}}),Le=Me(Re(Oe)),Ue=e=>Object.assign(Te(e),{between:(t,i)=>{return Ue(_e(e,(n=t,s=i,Re((e=>Ie(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e<i)))));var i},gt:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e>i)))));var i},lte:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e<=i)))));var i},gte:t=>{return Ue(_e(e,(i=t,Re((e=>Ie(e)&&e>=i)))));var i},int:()=>Ue(_e(e,Re((e=>Ie(e)&&Number.isInteger(e))))),finite:()=>Ue(_e(e,Re((e=>Ie(e)&&Number.isFinite(e))))),positive:()=>Ue(_e(e,Re((e=>Ie(e)&&e>0)))),negative:()=>Ue(_e(e,Re((e=>Ie(e)&&e<0))))}),je=Ue(Re(Ie)),Fe=e=>Object.assign(Te(e),{between:(t,i)=>{return Fe(_e(e,(n=t,s=i,Re((e=>Ae(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e<i)))));var i},gt:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e>i)))));var i},lte:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e<=i)))));var i},gte:t=>{return Fe(_e(e,(i=t,Re((e=>Ae(e)&&e>=i)))));var i},positive:()=>Fe(_e(e,Re((e=>Ae(e)&&e>0)))),negative:()=>Fe(_e(e,Re((e=>Ae(e)&&e<0))))}),$e=Fe(Re(Ae)),Be=Te(Re((function(e){return"boolean"==typeof e}))),Ve=Te(Re((function(e){return"symbol"==typeof e}))),qe=Te(Re((function(e){return null==e}))),Ze=Te(Re((function(e){return null!=e})));var He={__proto__:null,matcher:pe,optional:Ce,array:function(...e){return Se({[pe]:()=>({match:t=>{if(!Array.isArray(t))return{matched:!1};if(0===e.length)return{matched:!0};const i=e[0];let n={};if(0===t.length)return be(i).forEach((e=>{n[e]=[]})),{matched:!0,selections:n};const s=(e,t)=>{n[e]=(n[e]||[]).concat([t])};return{matched:t.every((e=>ye(i,e,s))),selections:n}},getSelectionKeys:()=>0===e.length?[]:be(e[0])})})},set:function(...e){return Te({[pe]:()=>({match:t=>{if(!(t instanceof Set))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};if(0===e.length)return{matched:!0};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])},s=e[0];return{matched:we(t,(e=>ye(s,e,n))),selections:i}},getSelectionKeys:()=>0===e.length?[]:be(e[0])})})},map:function(...e){return Te({[pe]:()=>({match:t=>{if(!(t instanceof Map))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])};if(0===e.length)return{matched:!0};var s;if(1===e.length)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null==(s=e[0])?void 0:s.toString()}`);const[r,o]=e;return{matched:Ee(t,((e,t)=>{const i=ye(r,t,n),s=ye(o,e,n);return i&&s})),selections:i}},getSelectionKeys:()=>0===e.length?[]:[...be(e[0]),...be(e[1])]})})},intersection:_e,union:Pe,not:function(e){return Te({[pe]:()=>({match:t=>({matched:!ye(e,t,(()=>{}))}),getSelectionKeys:()=>[],matcherType:"not"})})},when:Re,select:xe,any:Ne,_:De,string:Le,number:je,bigint:$e,boolean:Be,symbol:Ve,nullish:qe,nonNullable:Ze,instanceOf:function(e){return Te(Re((t=e,e=>e instanceof t)));var t},shape:function(e){return Te(Re(function(...e){if(1===e.length){const[t]=e;return e=>ye(t,e,(()=>{}))}if(2===e.length){const[t,i]=e;return ye(t,i,(()=>{}))}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${e.length}.`)}(e)))}};class ze extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(i){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const Ke={matched:!1,value:void 0};function Ge(e){return new We(e,Ke)}class We{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],i=[e[0]];let n;3===e.length&&"function"==typeof e[1]?n=e[1]:e.length>2&&i.push(...e.slice(1,e.length-1));let s=!1,r={};const o=(e,t)=>{s=!0,r[e]=t},a=!i.some((e=>ye(e,this.input,o)))||n&&!Boolean(n(this.input))?Ke:{matched:!0,value:t(s?ge in r?r[ge]:r:this.input,this.input)};return new We(this.input,a)}when(e,t){if(this.state.matched)return this;const i=Boolean(e(this.input));return new We(this.input,i?{matched:!0,value:t(this.input,this.input)}:Ke)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=Je){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}}function Je(e){throw new ze(e)}var Qe={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function n(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function r(e,t,n,r,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,r||e,o),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=i?i+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,r=n.length,o=new Array(r);s<r;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,r,o){var a=i?i+e:e;if(!this._events[a])return!1;var c,d,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,n),!0;case 4:return l.fn.call(l.context,t,n,s),!0;case 5:return l.fn.call(l.context,t,n,s,r),!0;case 6:return l.fn.call(l.context,t,n,s,r,o),!0}for(d=1,c=new Array(u-1);d<u;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var h,p=l.length;for(d=0;d<p;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),u){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,n);break;case 4:l[d].fn.call(l[d].context,t,n,s);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];l[d].fn.apply(l[d].context,c)}}return!0},a.prototype.on=function(e,t,i){return r(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return r(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,n,s){var r=i?i+e:e;if(!this._events[r])return this;if(!t)return o(this,r),this;var a=this._events[r];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,r);else{for(var c=0,d=[],l=a.length;c<l;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&d.push(a[c]);d.length?this._events[r]=1===d.length?d[0]:d:o(this,r)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(Qe);var Ye=Qe.exports;function Xe(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var et=Object.defineProperty,tt=(e,t,i)=>((e,t,i)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class it{constructor(){tt(this,"_locking"),tt(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function nt(e,t){if(!e)throw new Error(t)}function st(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function rt(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function ot(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const at=Symbol("@bufbuild/protobuf/enum-type");function ct(e,t,i,n){e[at]=dt(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function dt(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const o of t){const e=lt(o);r.push(e),n[o.name]=e,s[o.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function lt(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class ut{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function ht(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function pt(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),o=255&(s?128|n:n);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const mt=4294967296;function gt(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=mt&&(s+=n/mt|0,n%=mt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?yt(n,s):vt(n,s)}function ft(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(mt*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+bt(r)+bt(s)}function vt(e,t){return{lo:0|e,hi:0|t}}function yt(e,t){return t=~t,e?e=1+~e:t+=1,vt(e,t)}const bt=e=>{const t=String(e);return"0000000".slice(t.length)+t};function kt(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function Tt(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const St=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>nt(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>nt(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),gt(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),gt(e)),dec:(e,t)=>function(e,t){let i=vt(e,t);const n=2147483648&i.hi;n&&(i=yt(i.lo,i.hi));const s=ft(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>ft(e,t)}}();var Ct,wt,Et,_t,Pt,Rt;function xt(e,t,i){if(t===i)return!0;if(e==Ct.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case Ct.UINT64:case Ct.FIXED64:case Ct.INT64:case Ct.SFIXED64:case Ct.SINT64:return t==i}return!1}function It(e,t){switch(e){case Ct.BOOL:return!1;case Ct.UINT64:case Ct.FIXED64:case Ct.INT64:case Ct.SFIXED64:case Ct.SINT64:return 0==t?St.zero:"0";case Ct.DOUBLE:case Ct.FLOAT:return 0;case Ct.BYTES:return new Uint8Array(0);case Ct.STRING:return"";default:return 0}}function Ot(e,t){switch(e){case Ct.BOOL:return!1===t;case Ct.STRING:return""===t;case Ct.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(wt=Ct||(Ct={}))[wt.DOUBLE=1]="DOUBLE",wt[wt.FLOAT=2]="FLOAT",wt[wt.INT64=3]="INT64",wt[wt.UINT64=4]="UINT64",wt[wt.INT32=5]="INT32",wt[wt.FIXED64=6]="FIXED64",wt[wt.FIXED32=7]="FIXED32",wt[wt.BOOL=8]="BOOL",wt[wt.STRING=9]="STRING",wt[wt.BYTES=12]="BYTES",wt[wt.UINT32=13]="UINT32",wt[wt.SFIXED32=15]="SFIXED32",wt[wt.SFIXED64=16]="SFIXED64",wt[wt.SINT32=17]="SINT32",wt[wt.SINT64=18]="SINT64",(_t=Et||(Et={}))[_t.BIGINT=0]="BIGINT",_t[_t.STRING=1]="STRING",(Rt=Pt||(Pt={}))[Rt.Varint=0]="Varint",Rt[Rt.Bit64=1]="Bit64",Rt[Rt.LengthDelimited=2]="LengthDelimited",Rt[Rt.StartGroup=3]="StartGroup",Rt[Rt.EndGroup=4]="EndGroup",Rt[Rt.Bit32=5]="Bit32";class At{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].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(rt(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return st(e),kt(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){ot(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){rt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){st(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return st(e),kt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=St.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=St.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=St.enc(e);return pt(t.lo,t.hi,this.buf),this}sint64(e){let t=St.enc(e),i=t.hi>>31;return pt(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=St.uEnc(e);return pt(t.lo,t.hi,this.buf),this}}class Nt{constructor(e,t){this.varint64=ht,this.uint32=Tt,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Pt.Varint:for(;128&this.buf[this.pos++];);break;case Pt.Bit64:this.pos+=4;case Pt.Bit32:this.pos+=4;break;case Pt.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Pt.StartGroup:for(;;){const[e,i]=this.tag();if(i===Pt.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return St.dec(...this.varint64())}uint64(){return St.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,St.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return St.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return St.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 Dt(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return It(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Lt=[];for(let pp=0;pp<Mt.length;pp++)Lt[Mt[pp].charCodeAt(0)]=pp;Lt["-".charCodeAt(0)]=Mt.indexOf("+"),Lt["_".charCodeAt(0)]=Mt.indexOf("/");const Ut={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let a=0;a<e.length;a++){if(i=Lt[e.charCodeAt(a)],void 0===i)switch(e[a]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=Mt[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=Mt[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=Mt[s|t>>6],i+=Mt[63&t],n=0}return n&&(i+=Mt[s],i+="=",1==n&&(i+="=")),i}};function jt(e,t,i){Bt(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=Dt(t);for(const a of s)t.runtime.bin.readField(r,n.readerFactory(a.data),t.field,a.wireType,n);return o()}function Ft(e,t,i,n){Bt(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if($t(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function $t(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function Bt(e,t){nt(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function Vt(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!Ot(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function qt(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?It(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Zt(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(ut.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Ht(e,t){return Zt(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}Ct.DOUBLE,Ct.FLOAT,Ct.INT64,Ct.UINT64,Ct.INT32,Ct.UINT32,Ct.BOOL,Ct.STRING,Ct.BYTES;const zt={ignoreUnknownFields:!1},Kt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Gt=Symbol(),Wt=Symbol();function Jt(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Qt(e,t,i,n,s){let r=i.localName;if(i.repeated){if(nt("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ei(i.T,e,n.ignoreUnknownFields,!0);t!==Wt&&a.push(t);break;case"scalar":try{a.push(Xt(i.T,e,i.L,!0))}catch(o){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(e));throw o instanceof Error&&o.message.length>0&&(t+=": ".concat(o.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(t)));const a=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=Yt(i.K,e)}catch(o){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}switch(i.V.kind){case"message":a[c]=i.V.T.fromJson(r,n);break;case"enum":const e=ei(i.V.T,r,n.ignoreUnknownFields,!0);e!==Wt&&(a[c]=e);break;case"scalar":try{a[c]=Xt(i.V.T,r,Et.BIGINT,!0)}catch(o){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[r];Zt(c)?c.fromJson(t,n):(e[r]=c=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[r]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=ei(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Gt:qt(i,e);break;case Wt:break;default:e[r]=d}break;case"scalar":try{const n=Xt(i.T,t,i.L,!1);n===Gt?qt(i,e):e[r]=n}catch(o){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Jt(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}function Yt(e,t){if(e===Ct.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Xt(e,t,Et.BIGINT,!0).toString()}function Xt(e,t,i,n){if(null===t)return n?It(e,i):Gt;switch(e){case Ct.DOUBLE:case Ct.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==Ct.FLOAT&&ot(n),n;case Ct.INT32:case Ct.FIXED32:case Ct.SFIXED32:case Ct.SINT32:case Ct.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==Ct.UINT32||e==Ct.FIXED32?rt(r):st(r),r;case Ct.INT64:case Ct.SFIXED64:case Ct.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=St.parse(t);return i?o.toString():o;case Ct.FIXED64:case Ct.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=St.uParse(t);return i?a.toString():a;case Ct.BOOL:if("boolean"!=typeof t)break;return t;case Ct.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case Ct.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return Ut.dec(t)}throw new Error}function ei(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Gt;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return Wt}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Jt(t)))}function ti(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function ii(e,t,i){if("map"==e.kind){nt("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=si(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=ni(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){nt(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(si(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(ni(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return si(e.T,t);case"enum":return ni(e.T,t,i.enumAsInteger);case"message":return Ht(e.T,t).toJson(i)}}function ni(e,t,i){var n;if(nt("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function si(e,t){switch(e){case Ct.INT32:case Ct.SFIXED32:case Ct.SINT32:case Ct.FIXED32:case Ct.UINT32:return nt("number"==typeof t),t;case Ct.FLOAT:case Ct.DOUBLE:return nt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case Ct.STRING:return nt("string"==typeof t),t;case Ct.BOOL:return nt("boolean"==typeof t),t;case Ct.UINT64:case Ct.FIXED64:case Ct.INT64:case Ct.SFIXED64:case Ct.SINT64:return nt("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case Ct.BYTES:return nt(t instanceof Uint8Array),Ut.enc(t)}}const ri=Symbol("@bufbuild/protobuf/unknown-fields"),oi={readUnknownFields:!0,readerFactory:e=>new Nt(e)},ai={writeUnknownFields:!0,writerFactory:()=>new At};function ci(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?Ct.INT32:i.T;let c=ui;if("scalar"==i.kind&&i.L>0&&(c=li),r){let i=e[o];if(n==Pt.LengthDelimited&&a!=Ct.STRING&&a!=Ct.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(di(t,new d,s,i)):Zt(e[o])?di(t,e[o],s,i):(e[o]=di(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=ui(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=ui(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=di(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=It(e.K,Et.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===o)switch(e.V.kind){case"scalar":o=It(e.V.T,Et.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function di(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function li(e,t){const i=ui(e,t);return"bigint"==typeof i?i.toString():i}function ui(e,t){switch(t){case Ct.STRING:return e.string();case Ct.BOOL:return e.bool();case Ct.DOUBLE:return e.double();case Ct.FLOAT:return e.float();case Ct.INT32:return e.int32();case Ct.INT64:return e.int64();case Ct.UINT64:return e.uint64();case Ct.FIXED64:return e.fixed64();case Ct.BYTES:return e.bytes();case Ct.FIXED32:return e.fixed32();case Ct.SFIXED32:return e.sfixed32();case Ct.SFIXED64:return e.sfixed64();case Ct.SINT64:return e.sint64();case Ct.UINT32:return e.uint32();case Ct.SINT32:return e.sint32()}}function hi(e,t,i,n){nt(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?Ct.INT32:e.T;if(s)if(nt(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,Pt.LengthDelimited).fork();let[,s]=fi(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)gi(i,r,e.no,n);else gi(i,r,e.no,t);break;case"message":if(s){nt(Array.isArray(t));for(const s of t)mi(i,n,e,s)}else mi(i,n,e,t);break;case"map":nt("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))pi(i,n,e,s,o)}}function pi(e,t,i,n,s){e.tag(i.no,Pt.LengthDelimited),e.fork();let r=n;switch(i.K){case Ct.INT32:case Ct.FIXED32:case Ct.UINT32:case Ct.SFIXED32:case Ct.SINT32:r=Number.parseInt(n);break;case Ct.BOOL:nt("true"==n||"false"==n),r="true"==n}switch(gi(e,i.K,1,r),i.V.kind){case"scalar":gi(e,i.V.T,2,s);break;case"enum":gi(e,Ct.INT32,2,s);break;case"message":nt(void 0!==s),e.tag(2,Pt.LengthDelimited).bytes(s.toBinary(t))}e.join()}function mi(e,t,i,n){const s=Ht(i.T,n);i.delimited?e.tag(i.no,Pt.StartGroup).raw(s.toBinary(t)).tag(i.no,Pt.EndGroup):e.tag(i.no,Pt.LengthDelimited).bytes(s.toBinary(t))}function gi(e,t,i,n){nt(void 0!==n);let[s,r]=fi(t);e.tag(i,s)[r](n)}function fi(e){let t=Pt.Varint;switch(e){case Ct.BYTES:case Ct.STRING:t=Pt.LengthDelimited;break;case Ct.DOUBLE:case Ct.FIXED64:case Ct.SFIXED64:t=Pt.Bit64;break;case Ct.FIXED32:case Ct.SFIXED32:case Ct.FLOAT:t=Pt.Bit32}return[t,Ct[e].toLowerCase()]}function vi(e){if(void 0===e)return e;if(Zt(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function yi(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class bi{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ki(e,t){const i=Si(e);return t?i:Pi(_i(i))}const Ti=Si;function Si(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Ci=new Set(["constructor","toString","toJSON","valueOf"]),wi=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ei=e=>"".concat(e,"$"),_i=e=>wi.has(e)?Ei(e):e,Pi=e=>Ci.has(e)?Ei(e):e;class Ri{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ki(e,!1)}addField(e){nt(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const xi=(Ii=e=>new bi(e,(e=>function(e){var t,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=ki(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Ti(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:Et.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=Ct.BYTES&&d.T!=Ct.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ri(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),Oi=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=It(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},zt),e):zt},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Kt),e):Kt},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Jt(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}Qt(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=Dt(s);Qt(e,a,s.field,i,s),Ft(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!Vt(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!ti(s))continue}const i=ii(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&$t(e,o)){const i=jt(e,o,t),s=ii(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Xt(e,t,null!=i?i:Et.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||Ot(e,t)?si(e,t):void 0},debug:Jt},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},oi),e):oi},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},ai),e):ai},listUnknownFields(e){var t;return null!==(t=e[ri])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ri]},writeUnknownFields(e,t){const i=e[ri];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[ri])||(s[ri]=[]),s[ri].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=Pt.EndGroup);){const i=r.fields.find(a);if(i)ci(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=Pt.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ci,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(Vt(s,e))hi(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&hi(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:ct,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!Zt(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===Ct.BYTES&&(o=yi(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===Ct.BYTES&&(a=n.repeated?a.map(yi):yi(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Ct.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=yi(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>Zt(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=yi(e):s[i]=e:s[i]=Zt(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>xt(e.T,t,s[i])));case"enum":return n.every(((e,t)=>xt(Ct.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return xt(Ct.INT32,n,s);case"scalar":return xt(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return xt(Ct.INT32,n.value,s.value);case"scalar":return xt(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>xt(Ct.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>xt(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(vi);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=vi(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:vi(t.value)}:{case:void 0}:vi(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:Ii,initFields:Oi}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new ut),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=lt(s);n[e.localName]=e.no,n[e.no]=e.localName}return ct(n,e,t),n},makeEnumType:dt,getEnumType:function(e){const t=e[at];return nt(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ii,Oi;class Ai extends ut{constructor(e){super(),this.seconds=St.zero,this.nanos=0,xi.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(xi.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=St.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Ai.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ai({seconds:St.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ai).fromBinary(e,t)}static fromJson(e,t){return(new Ai).fromJson(e,t)}static fromJsonString(e,t){return(new Ai).fromJsonString(e,t)}static equals(e,t){return xi.util.equals(Ai,e,t)}}Ai.runtime=xi,Ai.typeName="google.protobuf.Timestamp",Ai.fields=xi.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Ni=xi.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ai},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Di,repeated:!0},{no:5,name:"events",kind:"message",T:Li,repeated:!0}])),Di=xi.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:Mi,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Mi=xi.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ai},{no:3,name:"value",kind:"scalar",T:2}])),Li=xi.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Ai},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ai,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Ui=xi.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ji=xi.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Fi=xi.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),$i=xi.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Bi=xi.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Vi=xi.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),qi=xi.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),Zi=xi.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Hi=xi.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),zi=xi.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),Ki=xi.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Gi,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:_n}])),Gi=xi.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),Wi=xi.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:xi.getEnumType(Fi),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),Ji=xi.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:xi.getEnumType(Qi)},{no:4,name:"tracks",kind:"message",T:nn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Wi},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:xi.getEnumType(Yi)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:xi.getEnumType(qi)},{no:18,name:"kind_details",kind:"enum",T:xi.getEnumType(Xi),repeated:!0}])),Qi=xi.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Yi=xi.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Xi=xi.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),en=xi.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),tn=xi.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:sn,repeated:!0}])),nn=xi.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:xi.getEnumType(ji)},{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:xi.getEnumType(Fi)},{no:10,name:"layers",kind:"message",T:sn,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:tn,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:xi.getEnumType(en)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:_n},{no:19,name:"audio_features",kind:"enum",T:xi.getEnumType(zi),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:xi.getEnumType(Ui)}])),sn=xi.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:xi.getEnumType($i)},{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}])),rn=xi.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:xi.getEnumType(on)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:dn,oneof:"value"},{no:3,name:"speaker",kind:"message",T:an,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ln,oneof:"value"},{no:7,name:"transcription",kind:"message",T:un,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Ni,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:pn,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:mn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:gn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:fn,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:In,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:On,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:An,oneof:"value"}])),on=xi.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),an=xi.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:cn,repeated:!0}])),cn=xi.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),dn=xi.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),ln=xi.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),un=xi.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:hn,repeated:!0}])),hn=xi.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),pn=xi.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),mn=xi.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),gn=xi.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),fn=xi.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:vn,oneof:"value"}])),vn=xi.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),yn=xi.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),bn=xi.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:xi.getEnumType(kn)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),kn=xi.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Tn=xi.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:xi.getEnumType(Sn)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),Sn=xi.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),Cn=xi.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:wn},{no:2,name:"screen",kind:"message",T:wn},{no:3,name:"resume_connection",kind:"enum",T:xi.getEnumType(Vi)},{no:4,name:"disabled_codecs",kind:"message",T:En},{no:5,name:"force_relay",kind:"enum",T:xi.getEnumType(Vi)}])),wn=xi.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:xi.getEnumType(Vi)}])),En=xi.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Gi,repeated:!0},{no:2,name:"publish",kind:"message",T:Gi,repeated:!0}])),_n=xi.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Pn=xi.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Rn=xi.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:xi.getEnumType(Pn)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),xn=xi.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),In=xi.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:xi.getEnumType(en)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Rn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:xn,oneof:"content_header"}]),{localName:"DataStream_Header"}),On=xi.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),An=xi.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),Nn=xi.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Dn=xi.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Mn=xi.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ln=xi.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:zn,oneof:"message"},{no:2,name:"answer",kind:"message",T:zn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:$n,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Fn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Bn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Gn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Wn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Yn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:es,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ps,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:gs,oneof:"message"},{no:13,name:"simulate",kind:"message",T:vs,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ts,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:ys,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Jn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Qn,oneof:"message"}])),Un=xi.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Vn,oneof:"message"},{no:2,name:"answer",kind:"message",T:zn,oneof:"message"},{no:3,name:"offer",kind:"message",T:zn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:$n,oneof:"message"},{no:5,name:"update",kind:"message",T:Kn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Zn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Yn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Bn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ns,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ss,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:os,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:cs,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:us,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ms,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Hn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:qn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:bs,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ss,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Cs,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Es,oneof:"message"}])),jn=xi.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Fn=xi.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:xi.getEnumType(ji)},{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:xi.getEnumType(Fi)},{no:9,name:"layers",kind:"message",T:sn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:jn,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:xi.getEnumType(en)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:xi.getEnumType(Ui)}])),$n=xi.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:xi.getEnumType(Nn)},{no:3,name:"final",kind:"scalar",T:8}])),Bn=xi.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Vn=xi.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Ki},{no:2,name:"participant",kind:"message",T:Ji},{no:3,name:"other_participants",kind:"message",T:Ji,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:is,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:Cn},{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:bn},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Gi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),qn=xi.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:is,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Cn}])),Zn=xi.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:nn}])),Hn=xi.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),zn=xi.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),Kn=xi.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Ji,repeated:!0}])),Gn=xi.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:yn,repeated:!0}])),Wn=xi.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:xi.getEnumType($i)},{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}])),Jn=xi.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:xi.getEnumType(zi),repeated:!0}])),Qn=xi.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),Yn=xi.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:xi.getEnumType(qi)},{no:3,name:"action",kind:"enum",T:xi.getEnumType(Xn)},{no:4,name:"regions",kind:"message",T:ks}])),Xn=xi.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),es=xi.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:sn,repeated:!0}])),ts=xi.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),is=xi.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),ns=xi.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:cn,repeated:!0}])),ss=xi.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Ki}])),rs=xi.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:xi.getEnumType(Bi)},{no:3,name:"score",kind:"scalar",T:2}])),os=xi.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:rs,repeated:!0}])),as=xi.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:xi.getEnumType(Dn)}])),cs=xi.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:as,repeated:!0}])),ds=xi.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:xi.getEnumType($i)},{no:2,name:"enabled",kind:"scalar",T:8}])),ls=xi.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ds,repeated:!0}])),us=xi.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ds,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ls,repeated:!0}])),hs=xi.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),ps=xi.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:hs,repeated:!0}])),ms=xi.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),gs=xi.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:zn},{no:2,name:"subscription",kind:"message",T:Gn},{no:3,name:"publish_tracks",kind:"message",T:Zn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:fs,repeated:!0},{no:5,name:"offer",kind:"message",T:zn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),fs=xi.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:xi.getEnumType(Nn)}])),vs=xi.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:xi.getEnumType(Mn),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),ys=xi.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),bs=xi.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),ks=xi.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Ts,repeated:!0}])),Ts=xi.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),Ss=xi.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:xi.getEnumType(Hi)}])),Cs=xi.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:xi.getEnumType(ws)},{no:3,name:"message",kind:"scalar",T:9}])),ws=xi.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Es=xi.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function _s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ps,Rs,xs,Is,Os,As,Ns,Ds,Ms={exports:{}},Ls=(Ps||(Ps=1,xs=Ms.exports,Is=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,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 c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(Rs=Ms).exports?Rs.exports=Is():xs.log=Is()),Ms.exports);(As=Os||(Os={}))[As.trace=0]="trace",As[As.debug=1]="debug",As[As.info=2]="info",As[As.warn=3]="warn",As[As.error=4]="error",As[As.silent=5]="silent",(Ds=Ns||(Ns={})).Default="livekit",Ds.Room="livekit-room",Ds.Participant="livekit-participant",Ds.Track="livekit-track",Ds.Publication="livekit-track-publication",Ds.Engine="livekit-engine",Ds.Signal="livekit-signal",Ds.PCManager="livekit-pc-manager",Ds.PCTransport="livekit-pc-transport",Ds.E2EE="lk-e2ee";let Us=Ls.getLogger("livekit");function js(e){const t=Ls.getLogger(e);return t.setDefaultLevel(Us.getLevel()),t}Object.values(Ns).map((e=>Ls.getLogger(e))),Us.setDefaultLevel(Os.info);const Fs=Ls.getLogger("lk-e2ee"),$s=7e3,Bs=[0,300,1200,2700,4800,$s,$s,$s,$s,$s];function Vs(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(t){r(t)}}function a(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function qs(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Zs,Hs={exports:{}},zs=function(){if(Zs)return Hs.exports;Zs=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}Hs.exports=s,Hs.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Hs.exports}();let Ks=!0,Gs=!0;function Ws(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Js(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Qs(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ks=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ys(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Gs=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Xs(){if("object"==typeof window){if(Ks)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function er(e,t){Gs&&console.warn(e+" is deprecated, please use "+t+" instead.")}function tr(e){return"[object Object]"===Object.prototype.toString.call(e)}function ir(e){return tr(e)?Object.keys(e).reduce((function(t,i){const n=tr(e[i]),s=n?ir(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function nr(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?nr(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{nr(e,e.get(t),i)}))})))}function sr(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&nr(e,i,s)}))})),s}const rr=Xs;function or(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),rr("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return rr("chrome: "+JSON.stringify(e)),s(e)},r=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(r(e))))))}}}function ar(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function cr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Js(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function dr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function lr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>sr(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Js(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>sr(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ur(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function hr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ur(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function pr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function mr(e,t){Js(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var gr=Object.freeze({__proto__:null,fixNegotiationNeeded:mr,shimAddTrackRemoveTrack:hr,shimAddTrackRemoveTrackWithNative:ur,shimGetSendersWithDtmf:dr,shimGetUserMedia:or,shimMediaStream:ar,shimOnTrack:cr,shimPeerConnection:pr,shimSenderReceiverGetStats:lr});function fr(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){er("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function vr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function yr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function br(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function kr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Js(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Tr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){er("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Sr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Cr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function wr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Er(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function _r(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Pr=Object.freeze({__proto__:null,shimAddTransceiver:Cr,shimCreateAnswer:_r,shimCreateOffer:Er,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:wr,shimGetUserMedia:fr,shimOnTrack:vr,shimPeerConnection:yr,shimRTCDataChannel:Sr,shimReceiverGetStats:kr,shimRemoveStream:Tr,shimSenderGetStats:br});function Rr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function xr(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Or(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Ar(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Ar(e){return e&&void 0!==e.video?Object.assign({},e,{video:ir(e.video)}):e}function Nr(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(er("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Dr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Mr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Lr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ur,jr=Object.freeze({__proto__:null,shimAudioContext:Lr,shimCallbacksAPI:Ir,shimConstraints:Ar,shimCreateOfferLegacy:Mr,shimGetUserMedia:Or,shimLocalStreamsAPI:Rr,shimRTCIceServerUrls:Nr,shimRemoteStreamsAPI:xr,shimTrackEventTransceiver:Dr}),Fr={exports:{}},$r=(Ur||(Ur=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(Fr)),Fr.exports),Br=_s($r),Vr=Xe({__proto__:null,default:Br},[$r]);function qr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Br.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Js(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Zr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Js(e,"icecandidate",(e=>{if(e.candidate){const t=Br.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Hr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Br.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Br.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Br.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function zr(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},Js(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Kr(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Gr(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Wr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Jr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Qr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Gr,shimAddIceCandidateNullOrEmpty:Wr,shimConnectionState:Kr,shimMaxMessageSize:Hr,shimParameterlessSetLocalDescription:Jr,shimRTCIceCandidate:qr,shimRTCIceCandidateRelayProtocol:Zr,shimSendThrowTypeError:zr});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Xs,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=Ws(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Ws(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Ws(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Qr,extractVersion:Ws,disableLog:Qs,disableWarnings:Ys,sdp:Vr};switch(n.browser){case"chrome":if(!gr||!pr||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=gr,Wr(e,n),Jr(e),or(e,n),ar(e),pr(e,n),cr(e),hr(e,n),dr(e),lr(e),mr(e,n),qr(e),Zr(e),Kr(e),Hr(e,n),zr(e),Gr(e,n);break;case"firefox":if(!Pr||!yr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Pr,Wr(e,n),Jr(e),fr(e,n),yr(e,n),vr(e),Tr(e),br(e),kr(e),Sr(e),Cr(e),wr(e),Er(e),_r(e),qr(e),Kr(e),Hr(e,n),zr(e);break;case"safari":if(!jr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=jr,Wr(e,n),Jr(e),Nr(e),Mr(e),Ir(e),Rr(e),xr(e),Dr(e),Or(e),Lr(e),qr(e),Zr(e),Hr(e,n),zr(e),Gr(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Yr="lk_e2ee";var Xr,eo,to,io,no,so,ro,oo,ao,co,lo,uo,ho,po,mo,go,fo,vo,yo,bo;function ko(){return void 0!==window.RTCRtpScriptTransform}(eo=Xr||(Xr={})).SetKey="setKey",eo.RatchetRequest="ratchetRequest",eo.KeyRatcheted="keyRatcheted",(to||(to={})).KeyRatcheted="keyRatcheted",(no=io||(io={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",no.EncryptionError="encryptionError",(so||(so={})).Error="cryptorError",zs.EventEmitter;class To extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(oo=ro||(ro={}))[oo.NotAllowed=0]="NotAllowed",oo[oo.ServerUnreachable=1]="ServerUnreachable",oo[oo.InternalError=2]="InternalError",oo[oo.Cancelled=3]="Cancelled",oo[oo.LeaveRequest=4]="LeaveRequest";class So extends To{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ro[t]}}class Co extends To{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class wo extends To{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Eo extends To{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class _o extends To{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Po extends To{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ro extends To{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class xo extends To{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:ws[t]}}(co=ao||(ao={})).PermissionDenied="PermissionDenied",co.NotFound="NotFound",co.DeviceInUse="DeviceInUse",co.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(ao||(ao={})),(uo=lo||(lo={}))[uo.InvalidKey=0]="InvalidKey",uo[uo.MissingKey=1]="MissingKey",uo[uo.InternalError=2]="InternalError",(po=ho||(ho={})).Connected="connected",po.Reconnecting="reconnecting",po.SignalReconnecting="signalReconnecting",po.Reconnected="reconnected",po.Disconnected="disconnected",po.ConnectionStateChanged="connectionStateChanged",po.MediaDevicesChanged="mediaDevicesChanged",po.ParticipantConnected="participantConnected",po.ParticipantDisconnected="participantDisconnected",po.TrackPublished="trackPublished",po.TrackSubscribed="trackSubscribed",po.TrackSubscriptionFailed="trackSubscriptionFailed",po.TrackUnpublished="trackUnpublished",po.TrackUnsubscribed="trackUnsubscribed",po.TrackMuted="trackMuted",po.TrackUnmuted="trackUnmuted",po.LocalTrackPublished="localTrackPublished",po.LocalTrackUnpublished="localTrackUnpublished",po.LocalAudioSilenceDetected="localAudioSilenceDetected",po.ActiveSpeakersChanged="activeSpeakersChanged",po.ParticipantMetadataChanged="participantMetadataChanged",po.ParticipantNameChanged="participantNameChanged",po.ParticipantAttributesChanged="participantAttributesChanged",po.RoomMetadataChanged="roomMetadataChanged",po.DataReceived="dataReceived",po.SipDTMFReceived="sipDTMFReceived",po.TranscriptionReceived="transcriptionReceived",po.ConnectionQualityChanged="connectionQualityChanged",po.TrackStreamStateChanged="trackStreamStateChanged",po.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",po.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",po.AudioPlaybackStatusChanged="audioPlaybackChanged",po.VideoPlaybackStatusChanged="videoPlaybackChanged",po.MediaDevicesError="mediaDevicesError",po.ParticipantPermissionsChanged="participantPermissionsChanged",po.SignalConnected="signalConnected",po.RecordingStatusChanged="recordingStatusChanged",po.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",po.EncryptionError="encryptionError",po.DCBufferStatusChanged="dcBufferStatusChanged",po.ActiveDeviceChanged="activeDeviceChanged",po.ChatMessage="chatMessage",po.LocalTrackSubscribed="localTrackSubscribed",po.MetricsReceived="metricsReceived",(go=mo||(mo={})).TrackPublished="trackPublished",go.TrackSubscribed="trackSubscribed",go.TrackSubscriptionFailed="trackSubscriptionFailed",go.TrackUnpublished="trackUnpublished",go.TrackUnsubscribed="trackUnsubscribed",go.TrackMuted="trackMuted",go.TrackUnmuted="trackUnmuted",go.LocalTrackPublished="localTrackPublished",go.LocalTrackUnpublished="localTrackUnpublished",go.ParticipantMetadataChanged="participantMetadataChanged",go.ParticipantNameChanged="participantNameChanged",go.DataReceived="dataReceived",go.SipDTMFReceived="sipDTMFReceived",go.TranscriptionReceived="transcriptionReceived",go.IsSpeakingChanged="isSpeakingChanged",go.ConnectionQualityChanged="connectionQualityChanged",go.TrackStreamStateChanged="trackStreamStateChanged",go.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",go.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",go.MediaDevicesError="mediaDevicesError",go.AudioStreamAcquired="audioStreamAcquired",go.ParticipantPermissionsChanged="participantPermissionsChanged",go.PCTrackAdded="pcTrackAdded",go.AttributesChanged="attributesChanged",go.LocalTrackSubscribed="localTrackSubscribed",go.ChatMessage="chatMessage",(vo=fo||(fo={})).TransportsCreated="transportsCreated",vo.Connected="connected",vo.Disconnected="disconnected",vo.Resuming="resuming",vo.Resumed="resumed",vo.Restarting="restarting",vo.Restarted="restarted",vo.SignalResumed="signalResumed",vo.SignalRestarted="signalRestarted",vo.Closing="closing",vo.MediaTrackAdded="mediaTrackAdded",vo.ActiveSpeakersUpdate="activeSpeakersUpdate",vo.DataPacketReceived="dataPacketReceived",vo.RTPVideoMapUpdate="rtpVideoMapUpdate",vo.DCBufferStatusChanged="dcBufferStatusChanged",vo.ParticipantUpdate="participantUpdate",vo.RoomUpdate="roomUpdate",vo.SpeakersChanged="speakersChanged",vo.StreamStateChanged="streamStateChanged",vo.ConnectionQualityUpdate="connectionQualityUpdate",vo.SubscriptionError="subscriptionError",vo.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",vo.RemoteMute="remoteMute",vo.SubscribedQualityUpdate="subscribedQualityUpdate",vo.LocalTrackUnpublished="localTrackUnpublished",vo.LocalTrackSubscribed="localTrackSubscribed",vo.Offline="offline",vo.SignalRequestResponse="signalRequestResponse",vo.SignalConnected="signalConnected",(bo=yo||(yo={})).Message="message",bo.Muted="muted",bo.Unmuted="unmuted",bo.Restarted="restarted",bo.Ended="ended",bo.Subscribed="subscribed",bo.Unsubscribed="unsubscribed",bo.UpdateSettings="updateSettings",bo.UpdateSubscription="updateSubscription",bo.AudioPlaybackStarted="audioPlaybackStarted",bo.AudioPlaybackFailed="audioPlaybackFailed",bo.AudioSilenceDetected="audioSilenceDetected",bo.VisibilityChanged="visibilityChanged",bo.VideoDimensionsChanged="videoDimensionsChanged",bo.VideoPlaybackStarted="videoPlaybackStarted",bo.VideoPlaybackFailed="videoPlaybackFailed",bo.ElementAttached="elementAttached",bo.ElementDetached="elementDetached",bo.UpstreamPaused="upstreamPaused",bo.UpstreamResumed="upstreamResumed",bo.SubscriptionPermissionChanged="subscriptionPermissionChanged",bo.SubscriptionStatusChanged="subscriptionStatusChanged",bo.SubscriptionFailed="subscriptionFailed",bo.TrackProcessorUpdate="trackProcessorUpdate",bo.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",bo.TranscriptionReceived="transcriptionReceived",bo.TimeSyncUpdate="timeSyncUpdate";const Io=/version\/(\d+(\.?_?\d+)+)/i;let Oo;function Ao(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Oo||t){const e=No.find((e=>{let{test:t}=e;return t.test(i)}));Oo=null==e?void 0:e.describe(i)}return Oo}const No=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Do(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Mo(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Do(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Mo(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Do(Io,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Mo(e)})}];function Do(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function Mo(e){return e.includes("mac os")?Do(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class Lo{}Lo.setTimeout=function(){return setTimeout(...arguments)},Lo.setInterval=function(){return setInterval(...arguments)},Lo.clearTimeout=function(){return clearTimeout(...arguments)},Lo.clearInterval=function(){return clearInterval(...arguments)};const Uo=[];var jo,Fo;(Fo=jo||(jo={}))[Fo.LOW=0]="LOW",Fo[Fo.MEDIUM=1]="MEDIUM",Fo[Fo.HIGH=2]="HIGH";class $o extends zs.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=$o.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Us,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=js(null!==(n=i.loggerName)&&void 0!==n?n:Ns.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=$o.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ka(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===$o.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===$o.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Uo.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Uo.splice(Uo.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Bo(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?yo.AudioPlaybackStarted:yo.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?yo.AudioPlaybackFailed:yo.VideoPlaybackFailed,t):"AbortError"===t.name?Us.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Us.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(yo.ElementAttached,e),e}detach(e){try{if(e){Vo(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(yo.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Vo(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(yo.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=js(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Uo.forEach((e=>{e.parentElement||(t=!1)})),t&&Uo.push(e)}}handleAppVisibilityChanged(){return Vs(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==$o.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){da()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){da()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Bo(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),aa()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(aa()||oa())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Vo(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var o;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(o=r=e.StreamState||(e.StreamState={})).Active="active",o.Paused="paused",o.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return ji.AUDIO;case t.Video:return ji.VIDEO;default:return ji.DATA}},e.kindFromProto=function(e){switch(e){case ji.AUDIO:return t.Audio;case ji.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return Fi.CAMERA;case n.Microphone:return Fi.MICROPHONE;case n.ScreenShare:return Fi.SCREEN_SHARE;case n.ScreenShareAudio:return Fi.SCREEN_SHARE_AUDIO;default:return Fi.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Fi.CAMERA:return n.Camera;case Fi.MICROPHONE:return n.Microphone;case Fi.SCREEN_SHARE:return n.ScreenShare;case Fi.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Dn.ACTIVE:return r.Active;case Dn.PAUSED:return r.Paused;default:return r.Unknown}}}($o||($o={}));class qo{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Zo=["vp8","h264"],Ho=["vp8","h264","vp9","av1"];function zo(e){return!!Zo.find((t=>t===e))}var Ko,Go,Wo,Jo;(Go=Ko||(Ko={}))[Go.PREFER_REGRESSION=0]="PREFER_REGRESSION",Go[Go.SIMULCAST=1]="SIMULCAST",Go[Go.REGRESSION=2]="REGRESSION",(Jo=Wo||(Wo={})).telephone={maxBitrate:12e3},Jo.speech={maxBitrate:24e3},Jo.music={maxBitrate:48e3},Jo.musicStereo={maxBitrate:64e3},Jo.musicHighQuality={maxBitrate:96e3},Jo.musicHighQualityStereo={maxBitrate:128e3};const Qo={h90:new qo(160,90,9e4,20),h180:new qo(320,180,16e4,20),h216:new qo(384,216,18e4,20),h360:new qo(640,360,45e4,20),h540:new qo(960,540,8e5,25),h720:new qo(1280,720,17e5,30),h1080:new qo(1920,1080,3e6,30),h1440:new qo(2560,1440,5e6,30),h2160:new qo(3840,2160,8e6,30)},Yo={h120:new qo(160,120,7e4,20),h180:new qo(240,180,125e3,20),h240:new qo(320,240,14e4,20),h360:new qo(480,360,33e4,20),h480:new qo(640,480,5e5,20),h540:new qo(720,540,6e5,25),h720:new qo(960,720,13e5,30),h1080:new qo(1440,1080,23e5,30),h1440:new qo(1920,1440,38e5,30)},Xo={h360fps3:new qo(640,360,2e5,3,"medium"),h360fps15:new qo(640,360,4e5,15,"medium"),h720fps5:new qo(1280,720,8e5,5,"medium"),h720fps15:new qo(1280,720,15e5,15,"medium"),h720fps30:new qo(1280,720,2e6,30,"medium"),h1080fps15:new qo(1920,1080,25e5,15,"medium"),h1080fps30:new qo(1920,1080,5e6,30,"medium"),original:new qo(0,0,7e6,30,"medium")},ea="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ta(e){return Vs(this,void 0,void 0,(function*(){return new Promise((t=>Lo.setTimeout(t,e)))}))}function ia(){return"addTransceiver"in RTCPeerConnection.prototype}function na(){return"addTrack"in RTCPeerConnection.prototype}function sa(e){return"av1"===e||"vp9"===e}function ra(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function oa(){var e;return"Firefox"===(null===(e=Ao())||void 0===e?void 0:e.name)}function aa(){var e;return"Safari"===(null===(e=Ao())||void 0===e?void 0:e.name)}function ca(){var e,t;return!!da()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function da(){return"undefined"!=typeof document}function la(){return"ReactNative"==navigator.product}function ua(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ha(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function pa(){if(!la())return;let e=ha();return e?e.platform:void 0}function ma(){if(da())return window.devicePixelRatio;if(la()){let e=ha();if(e)return e.devicePixelRatio}return 1}function ga(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function fa(e){for(const t of e)t.target.handleResize(t)}function va(e){for(const t of e)t.target.handleVisibilityChanged(t)}let ya=null;const ba=()=>(ya||(ya=new ResizeObserver(fa)),ya);let ka=null;const Ta=()=>(ka||(ka=new IntersectionObserver(va,{root:null,rootMargin:"0px"})),ka);function Sa(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let Ca;function wa(){if(!Ca){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[Ca]=n.stream.getAudioTracks(),!Ca)throw Error("Could not get empty media stream audio track");Ca.enabled=!1}return Ca.clone()}class Ea{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Vs(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function _a(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Pa(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Ra(e){switch(e.reason){case ro.LeaveRequest:return e.context;case ro.Cancelled:return qi.CLIENT_INITIATED;case ro.NotAllowed:return qi.USER_REJECTED;case ro.ServerUnreachable:return qi.JOIN_FAILURE;default:return qi.UNKNOWN_REASON}}function xa(e){return void 0!==e?Number(e):void 0}function Ia(e){return void 0!==e?BigInt(e):void 0}function Oa(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Aa(e){return!!e&&e.kind==$o.Kind.Audio}function Na(e){return!!e&&e.kind==$o.Kind.Video}function Da(e){return Oa(e)&&Na(e)}function Ma(e){return Oa(e)&&Aa(e)}function La(e){return!!e&&!e.isLocal}function Ua(e){return!!e&&!e.isLocal}function ja(e){return La(e)&&Na(e)}function Fa(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Ga(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&($a(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&($a(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function $a(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Ba(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach((e=>{"resolution"===e?$a(s,o.resolution):s[e]=o[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Va(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Vs(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function qa(e){return"audioinput"===e?$o.Source.Microphone:"videoinput"===e?$o.Source.Camera:$o.Source.Unknown}function Za(e){return e===$o.Source.Microphone?"audioinput":e===$o.Source.Camera?"videoinput":void 0}function Ha(e){return e.split("/")[1].toLowerCase()}function za(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Zn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Ka(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Ka(e.track):{})}}function Ga(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class Wa extends zs.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":Us.error(s.error.message),this.emit(io.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(io.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(io.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Xr.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{Us.error("e2ee worker encountered an error:",{error:e.error}),this.emit(io.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||ko()))throw new Co("tried to setup end-to-end encryption on an unsupported browser");if(Us.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Fs.getLevel()}};this.worker&&(Us.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Us.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Us.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(fo.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(ho.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==en.NONE,t.identity))),e.on(ho.ConnectionStateChanged,(t=>{t===pd.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==en.NONE,e.identity)}))}))})).on(ho.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(ho.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(ho.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(mo.LocalTrackPublished,(e=>Vs(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(Xr.SetKey,(e=>this.postKey(e))).on(Xr.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ha(i.mimeType):void 0)}}setupE2EESender(e,t){Oa(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Us.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Vs(this,void 0,void 0,(function*(){if(this.worker){if(ko()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Yr in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[r,s])}e[Yr]=!0}}))}handleSender(e,t,i){var n;if(!(Yr in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ko()){Us.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Us.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[Yr]=!0}}}const Ja="default";class Qa{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Qa),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Qa.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Us.debug("awaiting getUserMedia promise");try{e?yield Qa.userMediaPromiseMap.get(e):yield Promise.all(Qa.userMediaPromiseMap.values())}catch(r){Us.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!aa()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Vs(this,void 0,void 0,(function*(){if(t!==Ja)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Ja));if(!s)return void Us.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==Ja&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Us.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Qa.userMediaPromiseMap.has(e):Qa.userMediaPromiseMap.size>0}}var Ya,Xa;Qa.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Qa.userMediaPromiseMap=new Map,(Xa=Ya||(Ya={}))[Xa.WAITING=0]="WAITING",Xa[Xa.RUNNING=1]="RUNNING",Xa[Xa.COMPLETED=2]="COMPLETED";class ec{constructor(){this.pendingTasks=new Map,this.taskMutex=new it,this.nextTaskIndex=0}run(e){return Vs(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ya.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ya.RUNNING,yield e()}finally{t.status=Ya.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Vs(this,void 0,void 0,(function*(){return this.run((()=>Vs(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function tc(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const ic=["syncState","trickle","offer","answer","simulate","leave"];var nc,sc;(sc=nc||(nc={}))[sc.CONNECTING=0]="CONNECTING",sc[sc.CONNECTED=1]="CONNECTED",sc[sc.RECONNECTING=2]="RECONNECTING",sc[sc.DISCONNECTING=3]="DISCONNECTING",sc[sc.DISCONNECTED=4]="DISCONNECTED";class rc{get currentState(){return this.state}get isDisconnected(){return this.state===nc.DISCONNECTING||this.state===nc.DISCONNECTED}get isEstablishingConnection(){return this.state===nc.CONNECTING||this.state===nc.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=nc.DISCONNECTED,this.log=Us,this._requestId=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.log=js(null!==(i=t.loggerName)&&void 0!==i?i:Ns.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new ec,this.queuedRequests=[],this.closingLock=new it,this.connectionLock=new it,this.state=nc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Vs(this,void 0,void 0,(function*(){return this.state=nc.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Vs(this,void 0,void 0,(function*(){if(this.options)return this.state=nc.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",la()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new Tn({sdk:Sn.JS,protocol:15,version:"2.11.4"});return la()&&(t.os=null!==(e=pa())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),tc(i,"rtc")}(e,s),o=tc(new URL(Pa(r)),"validate");return new Promise(((e,t)=>Vs(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>Vs(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),t(new So("room connection has been cancelled (signal)",ro.Cancelled))})),a=setTimeout((()=>{this.close(),t(new So("room connection has timed out (signal)",ro.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>Vs(this,void 0,void 0,(function*(){if(this.state===nc.CONNECTED)this.handleWSError(e);else{this.state=nc.DISCONNECTED,clearTimeout(a);try{const i=yield fetch(o);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new So(e,ro.NotAllowed,i.status))}else t(new So("Encountered unknown websocket error during connection: ".concat(e.toString()),ro.InternalError,i.status))}catch(i){t(new So(i instanceof Error?i.message:"server was not reachable",ro.ServerUnreachable))}}})),this.ws.onmessage=r=>Vs(this,void 0,void 0,(function*(){var o,a,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=Un.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=Un.fromBinary(new Uint8Array(r.data))}if(this.state!==nc.CONNECTED){let r=!1;if("join"===(null===(o=d.message)||void 0===o?void 0:o.case)?(this.state=nc.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===nc.RECONNECTING&&"leave"!==d.message.case?(this.state=nc.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new So("Received leave request while trying to (re)connect",ro.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new So("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),ro.InternalError)),!r)return}this.signalLatency&&(yield ta(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new So("Websocket got closed during a (re)connection attempt",ro.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return Vs(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=nc.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,ta(250)])),e.ws=void 0}}finally{t&&(e.state=nc.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ac(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ac(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new $n({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Bn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Vs(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new ts({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 es({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ps({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:St.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new ys({timestamp:St.parse(Date.now()),rtt:St.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Jn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Yn({reason:qi.CLIENT_INITIATED,action:Xn.DISCONNECT})})}sendRequest(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=ic.indexOf(e.case)>=0;return Us.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===nc.RECONNECTING)return void t.queuedRequests.push((()=>Vs(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield ta(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new Ln({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=oc(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=oc(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Vs(this,void 0,void 0,(function*(){if(this.state===nc.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Lo.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Lo.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Lo.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Lo.clearInterval(this.pingInterval)}}function oc(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function ac(e){return new zn({sdp:e.sdp,type:e.type})}var cc,dc,lc,uc,hc,pc={},mc={},gc={exports:{}};function fc(){if(cc)return gc.exports;cc=1;var e=gc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),gc.exports}function vc(){if(uc)return lc;uc=1;var e=fc(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return lc=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"}}var yc=function(){if(hc)return pc;hc=1;var e=(dc||(dc=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=fc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(mc)),mc),t=vc(),i=fc();return pc.grammar=i,pc.write=t,pc.parse=e.parse,pc.parseParams=e.parseParams,pc.parseFmtpConfig=e.parseFmtpConfig,pc.parsePayloads=e.parsePayloads,pc.parseRemoteCandidates=e.parseRemoteCandidates,pc.parseImageAttributes=e.parseImageAttributes,pc.parseSimulcastStreamList=e.parseSimulcastStreamList,pc}();function bc(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var t=e.apply(n,i);a&&a(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const kc="negotiationStarted",Tc="negotiationComplete",Sc="rtpVideoPayloadTypes";class Cc extends zs.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Us,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=bc((e=>Vs(this,void 0,void 0,(function*(){this.emit(kc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=js(null!==(i=t.loggerName)&&void 0!==i?i:Ns.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Vs(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return Vs(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=yc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=yc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=yc.write(n)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(Tc),e.sdp)&&yc.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Sc,e.rtp)}))}))}createAndSendOffer(e){return Vs(this,void 0,void 0,(function*(){var t;if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=yc.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{Ec(e),"audio"===e.type?wc(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(sa(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,yc.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return Vs(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=yc.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Ec(e),"audio"===e.type&&wc(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,yc.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new _o("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new _o("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Vs(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Vs(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Po(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===ea)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:ea})}}}function wc(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ec(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const _c="vp8",Pc={audioPreset:Wo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_c,backupCodec:!0},Rc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},xc={deviceId:{ideal:"default"},resolution:Qo.h720.resolution},Ic={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Bs}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},Oc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ac,Nc;(Nc=Ac||(Ac={}))[Nc.NEW=0]="NEW",Nc[Nc.CONNECTING=1]="CONNECTING",Nc[Nc.CONNECTED=2]="CONNECTED",Nc[Nc.FAILED=3]="FAILED",Nc[Nc.CLOSING=4]="CLOSING",Nc[Nc.CLOSED=5]="CLOSED";class Dc{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=Oc.peerConnectionTimeout,this.log=Us,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=Ac.CONNECTED:i.some((e=>"failed"===e))?this.state=Ac.FAILED:i.some((e=>"connecting"===e))?this.state=Ac.CONNECTING:i.every((e=>"closed"===e))?this.state=Ac.CLOSED:i.some((e=>"closed"===e))?this.state=Ac.CLOSING:i.every((e=>"new"===e))&&(this.state=Ac.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(Ac[t]," to ").concat(Ac[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=js(null!==(n=i.loggerName)&&void 0!==n?n:Ns.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Cc(e,i),this.subscriber=new Cc(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Nn.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Nn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=Ac.NEW,this.connectionLock=new it,this.remoteOfferLock=new it}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Vs(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return Vs(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Vs(this,void 0,void 0,(function*(){t===Nn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return Vs(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Vs(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Vs(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Vs(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(kc,(()=>{e.signal.aborted||this.publisher.once(Tc,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Nn.PUBLISHER||e===Nn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Vs(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>Vs(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Lo.clearTimeout(r),s(new So("room connection has been cancelled",ro.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=Lo.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new So("could not establish pc connection",ro.InternalError))}),n);for(;this.state!==Ac.CONNECTED;)if(yield ta(50),null==t?void 0:t.signal.aborted)return void s(new So("room connection has been cancelled",ro.Cancelled));Lo.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class Mc extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Uc(t,Mc.MAX_MESSAGE_BYTES),this.data=i?Uc(i,Mc.MAX_DATA_BYTES):void 0}static fromProto(e){return new Mc(e.code,e.message,e.data)}toProto(){return new vn({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Mc(Mc.ErrorCode[e],Mc.ErrorMessage[e],t)}}function Lc(e){return(new TextEncoder).encode(e).length}function Uc(e,t){if(Lc(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}Mc.MAX_MESSAGE_BYTES=256,Mc.MAX_DATA_BYTES=15360,Mc.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Mc.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const jc=2e3;function Fc(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class $c extends $o{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=bc((()=>Vs(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Vs(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(yo.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new it,this.pauseUpstreamLock=new it,this.processorLock=new it,this.restartLock=new it,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==$o.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Vs(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Vo(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Bo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Bo(null!=n?n:e,t)})))}))}waitForDimensions(){return Vs(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===$o.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ao())||void 0===i?void 0:i.os)&&(yield ta(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield ta(50)}throw new wo("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Vs(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===_a(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),_a(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Vs(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===$o.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===$o.Kind.Audio?"audioinput":"videoinput";return t?Qa.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Vs(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Vs(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Vs(this,void 0,void 0,(function*(){if(!this.sender)throw new wo("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return Vs(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===$o.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{Vo(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield r.applyConstraints(n),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(yo.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?yo.Muted:yo.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Vs(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Vs(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(yo.UpstreamPaused,this);const t=Ao();if("Safari"===(null==t?void 0:t.name)&&ga(t.version,"12.0")<0)throw new Co("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return Vs(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(yo.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return Vs(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Bo(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(Vo(t._mediaStreamTrack,e),Bo(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(yo.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Vs(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(yo.TrackProcessorUpdate))}()}))}}class Bc extends $c{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,$o.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Vs(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=Fc(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(yo.AudioTrackFeatureUpdate,this,zi.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(yo.AudioTrackFeatureUpdate,this,zi.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Vs(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===$o.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Vs(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==_a(this._constraints.deviceId);return this.source!==$o.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Vs(this,void 0,void 0,(function*(){let t;if(e){const i=Ba({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Vs(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){da()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),jc)))}setProcessor(e){return Vs(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!la()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(yo.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Vs(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Vs(this,void 0,void 0,(function*(){const e=yield function(e){return Vs(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Va();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield ta(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(yo.AudioSilenceDetected)),e}))}}const Vc=Object.values(Qo),qc=Object.values(Yo),Zc=Object.values(Xo),Hc=[Qo.h180,Qo.h360],zc=[Yo.h180,Yo.h360],Kc=["q","h","f"];function Gc(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return Zc;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?Vc:qc}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let a=0;a<s.length;a+=1){const e=s[a];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Us.debug("using video encoding",o));const l=o.maxFramerate,u=new qo(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&sa(d)){const e=new Yc(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Ao();if(aa()||la()||"Chrome"===(null==i?void 0:i.name)&&ga(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:Kc[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Us.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=Qc(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Wc(e,u):null!==(r=Qc(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Wc(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Jc(t,i,[e,h,u],l);if(n>=480)return Jc(t,i,[e,u],l)}return Jc(t,i,[u])}function Wc(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new qo(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?Hc:zc}function Jc(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=Kc.length)return;const o=Math.min(e,t),a={rid:Kc[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=oa()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),la()&&"ios"===pa()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Us.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Us.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function Qc(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Yc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Xc extends $c{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,$o.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>Vs(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Fc(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new it}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!da())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),jc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Vs(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=qs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Vs(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=qs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Vs(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==$o.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Vs(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==$o.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Vs(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=jo.LOW;i<=jo.HIGH;i+=1)t.push(new ds({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return Vs(this,void 0,void 0,(function*(){var t,i,n,s,r;let o;if(e){const t=Ba({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o);try{for(var a,c=!0,d=qs(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Vs(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=qs(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Vs(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Vs(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=qs(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield ed(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return Vs(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield ed(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Vs(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ca()&&this.isInBackground&&this.source===$o.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function ed(e,t,i,n,s,r){return Vs(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:t}));let a=!1;const c=Ao();if("Chrome"===(null==c?void 0:c.name)&&ga(null==c?void 0:c.version,"133")>0&&o[0].scalabilityMode){const e=o[0],n=new Yc(e.scalabilityMode);let s=$i.OFF;if(i.forEach((e=>{e.enabled&&(s===$i.OFF||e.quality>s)&&(s=e.quality)})),s===$i.OFF)e.active&&(e.active=!1,a=!0);else if(!e.active||n.spatial!==s+1){a=!0,e.active=!0;const i=new Yc(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else o.forEach(((e,n)=>{var o;let c=null!==(o=e.rid)&&void 0!==o?o:"";""===c&&(c="q");const d=td(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(a=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),oa()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}));a&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function td(e){switch(e){case"f":default:return jo.HIGH;case"h":return jo.MEDIUM;case"q":return jo.LOW}}function id(e,t,i,n){if(!i)return[new sn({quality:jo.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Yc(n),r=[],o="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new sn({quality:Math.min(jo.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(o,c)),height:Math.ceil(t/Math.pow(o,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=td(null!==(s=i.rid)&&void 0!==s?s:"");return new sn({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const nd="_lossy",sd="_reliable",rd="leave-reconnect";var od,ad,cd,dd,ld,ud,hd,pd,md,gd,fd;(ad=od||(od={}))[ad.New=0]="New",ad[ad.Connected=1]="Connected",ad[ad.Disconnected=2]="Disconnected",ad[ad.Reconnecting=3]="Reconnecting",ad[ad.Closed=4]="Closed";class vd extends zs.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Oc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=od.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Us,this.handleDataChannel=e=>Vs(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===sd)t.reliableDCSub=i;else{if(i.label!==nd)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>Vs(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=rn.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(fo.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(fo.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?on.LOSSY:on.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===rd&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Lo.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(fo.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===od.Connected&&e();const i=()=>{this.off(fo.Disconnected,n),e()},n=()=>{this.off(fo.Restarted,i),t()};this.once(fo.Restarted,i),this.once(fo.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(fo.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===nc.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Zi.RR_SIGNAL_DISCONNECTED))},this.log=js(null!==(t=e.loggerName)&&void 0!==t?t:Ns.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new rc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new it,this.dataProcessLock=new it,this.dcBufferStatus=new Map([[on.LOSSY,!0],[on.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(fo.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(fo.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(fo.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(fo.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(fo.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(fo.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(fo.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(fo.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,o,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(a=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===a?void 0:a.sid}}join(e,t,i,n){return Vs(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(fo.SignalConnected)}),10),s}catch(s){if(s instanceof So&&s.reason===ro.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return Vs(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(fo.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return Vs(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return Vs(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new wo("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new So("publication of local track timed out, no response from server",ro.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Vs(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Vs(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==Ac.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new Dc(n,e.subscriberPrimary,this.loggerOptions),this.emit(fo.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>Vs(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===Ac.CONNECTED){const t=this.pcState===od.New;this.pcState=od.Connected,t&&this.emit(fo.Connected,e)}else t===Ac.FAILED&&this.pcState===od.Connected&&(this.pcState=od.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Zi.RR_SUBSCRIBER_FAILED:Zi.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===nc.RECONNECTING,r=[Ac.FAILED,Ac.CLOSING,Ac.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(fo.Offline)})),this.pcManager.onTrack=e=>{this.emit(fo.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>Vs(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>Vs(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(fo.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(fo.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(fo.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(fo.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Zi.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Xn.DISCONNECT:this.emit(fo.Disconnected,null==e?void 0:e.reason),this.close();break;case Xn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(rd);break;case Xn.RESUME:this.handleDisconnect(rd)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Vi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(nd,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sd,{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)}createSender(e,t,i){return Vs(this,void 0,void 0,(function*(){if(ia())return yield this.createTransceiverRTCRtpSender(e,t,i);if(na())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new _o("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Vs(this,void 0,void 0,(function*(){if(ia())return this.createSimulcastTransceiverSender(e,t,i,n);if(na())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new _o("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Vs(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _o("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Na(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Vs(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _o("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Vs(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _o("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return Vs(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Us.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Vi.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Ac.NEW)!==Ac.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof _o?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof yd||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",Zi.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(fo.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return Vs(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new _o("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(fo.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new yd;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof So&&s.reason===ro.NotAllowed)throw new _o("could not reconnect, token might be expired");throw new yd}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(fo.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==nc.CONNECTED)throw new yd("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(fo.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return Vs(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new _o("could not reconnect, url or token not saved");if(!this.pcManager)throw new _o("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(fo.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof So&&n.reason===ro.NotAllowed)throw new _o("could not reconnect, token might be expired");if(n instanceof So&&n.reason===ro.LeaveRequest)throw n;throw new yd(e)}if(this.emit(fo.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==nc.CONNECTED)throw new yd("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(fo.Resumed)}))}waitForPCInitialConnection(e,t){return Vs(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _o("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Vs(this,void 0,void 0,(function*(){this.pcState=od.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ta(2e3),!this.pcManager)throw new _o("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=od.Connected}catch(e){throw this.pcState=od.Disconnected,new So("could not establish PC connection, ".concat(e.message),ro.InternalError)}}))}publishRpcResponse(e,t,i,n){return Vs(this,void 0,void 0,(function*(){const s=new rn({destinationIdentities:[e],kind:on.RELIABLE,value:{case:"rpcResponse",value:new fn({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,on.RELIABLE)}))}publishRpcAck(e,t){return Vs(this,void 0,void 0,(function*(){const i=new rn({destinationIdentities:[e],kind:on.RELIABLE,value:{case:"rpcAck",value:new gn({requestId:t})}});yield this.sendDataPacket(i,on.RELIABLE)}))}sendDataPacket(e,t){return Vs(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>Vs(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(fo.Closing,n);!this.dcBufferStatus.get(e);)yield ta(10);this.off(fo.Closing,n),t()}}))))}ensureDataTransportConnected(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new _o("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new So("".concat(r," connection not set"),ro.InternalError);let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield ta(50)}throw new So("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),ro.InternalError)}()}))}ensurePublisherConnected(e){return Vs(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===Ac.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Vs(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Vs(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new Po("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(fo.Closing,n),this.pcManager.publisher.once(Sc,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,Ho.includes(n)&&t.set(e.payload,i)})),this.emit(fo.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Po&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Zi.RR_UNKNOWN),t(s)}finally{this.off(fo.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===on.LOSSY)return this.lossyDCSub;if(e===on.RELIABLE)return this.reliableDCSub}else{if(e===on.LOSSY)return this.lossyDC;if(e===on.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new gs({answer:s?ac({sdp:s.sdp,type:s.type}):void 0,offer:r?ac({sdp:r.sdp,type:r.type}):void 0,subscription:new Gn({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:za(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new fs({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(on.LOSSY),Nn.PUBLISHER),t(this.dataChannelForKind(on.RELIABLE),Nn.PUBLISHER),t(this.dataChannelForKind(on.LOSSY,!0),Nn.SUBSCRIBER),t(this.dataChannelForKind(on.RELIABLE,!0),Nn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Lo.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){da()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){da()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class yd extends Error{}class bd{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 ua(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Vs(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((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),Us.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Vs(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new So("Could not fetch region settings: ".concat(t.statusText),401===t.status?ro.NotAllowed:ro.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class kd{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Td extends kd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>Vs(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return Vs(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Vs(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,o=!0,a=qs(this);!(e=(r=yield a.next()).done);o=!0){n=r.value,o=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(s)}))}}class Sd extends kd{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=xa(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>Vs(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return Vs(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Vs(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,o=!0,a=qs(this);!(e=(r=yield a.next()).done);o=!0)n=r.value,o=!1,s+=n}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return s}))}}class Cd{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Vs(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class wd extends Cd{}class Ed extends Cd{}class _d extends $o{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?yo.Muted:yo.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(yo.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Vs(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),jc)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(yo.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Pd extends _d{constructor(e,t,i,n,s,r){super(e,t,$o.Kind.Audio,i,r),this.monitorReceiver=()=>Vs(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Fc(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;la()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(la())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Vs(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ra(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ra(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(yo.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(yo.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Vs(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Rd extends _d{constructor(e,t,i,n,s){super(e,t,$o.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Vs(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Fc(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=bc((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Vo(this._mediaStreamTrack,t):Bo(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new xd(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Vs(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Vs(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?Lo.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit(yo.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(yo.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?ma():t||(ma()>2?2:1)}}class xd{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Id(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Id(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Id(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Od(e),this.isPiP=da()&&Id(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Od(this.element),this.isPiP=Id(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ta().observe(this.element),ba().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Ta())||void 0===e||e.unobserve(this.element),null===(t=ba())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Id(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Od(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Od(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class Ad extends zs.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=en.NONE,this.log=Us,this.handleMuted=()=>{this.emit(yo.Muted)},this.handleUnmuted=()=>{this.emit(yo.Unmuted)},this.log=js(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ns.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=$o.Source.Unknown}setTrack(e){this.track&&(this.track.off(yo.Muted,this.handleMuted),this.track.off(yo.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(yo.Muted,this.handleMuted),e.on(yo.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ka(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==en.NONE}get audioTrack(){if(Aa(this.track))return this.track}get videoTrack(){if(Na(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=$o.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===$o.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(dd=(cd=Ad||(Ad={})).SubscriptionStatus||(cd.SubscriptionStatus={})).Desired="desired",dd.Subscribed="subscribed",dd.Unsubscribed="unsubscribed",(ld=cd.PermissionStatus||(cd.PermissionStatus={})).Allowed="allowed",ld.NotAllowed="not_allowed";class Nd extends Ad{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(yo.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(yo.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(yo.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return Vs(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Vs(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Vs(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Vs(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Aa(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(zi.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(zi.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(zi.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(zi.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(zi.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(zi.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Dd(e,t){return Vs(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Ga(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=Fa(r,Rc,xc),d=Ba(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(Qa.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Qa.userMediaPromiseMap.delete("audioinput")))),r.video&&(Qa.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Qa.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Vs(this,void 0,void 0,(function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&_a(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new Bc(e,t,!1,void 0,i);case"video":return new Xc(e,t,!1,i);default:throw new wo("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===$o.Kind.Video?h.source=$o.Source.Camera:h.kind===$o.Kind.Audio&&(h.source=$o.Source.Microphone),h.mediaStream=e,Aa(h)&&n?yield h.setProcessor(n):Na(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return Dd(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}}))}(hd=ud||(ud={})).Excellent="excellent",hd.Good="good",hd.Poor="poor",hd.Lost="lost",hd.Unknown="unknown";class Md extends zs.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===Yi.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Yi.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ud.Unknown,this.log=Us,this.log=js(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:Ns.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication($o.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication($o.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication($o.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(mo.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(mo.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(mo.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(mo.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(mo.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Bi.EXCELLENT:return ud.Excellent;case Bi.GOOD:return ud.Good;case Bi.POOR:return ud.Poor;case Bi.LOST:return ud.Lost;default:return ud.Unknown}}(e),t!==this._connectionQuality&&this.emit(mo.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>Aa(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(yo.Muted,(()=>{this.emit(mo.TrackMuted,e)})),e.on(yo.Unmuted,(()=>{this.emit(mo.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case $o.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case $o.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class Ld extends Md{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=en.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ea)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==ws.OK&&s.reject(new xo(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=Mc.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new hs({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Ka(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Ka(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Ka(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>Vs(this,void 0,void 0,(function*(){var t,i,n,s,r,o;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const r=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=qs(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;zo(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Ka(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Vs(this,void 0,void 0,(function*(){if(e.source===$o.Source.ScreenShare||e.source===$o.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Ka(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Ma(e)||Da(e))try{if(da())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===$o.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),Ka(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Ka(e))),Ma(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Ka(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==en.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(fo.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(fo.Connected,this.handleReconnected).on(fo.SignalRestarted,this.handleReconnected).on(fo.SignalResumed,this.handleReconnected).on(fo.Restarting,this.handleReconnecting).on(fo.Resuming,this.handleReconnecting).on(fo.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(fo.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(fo.Disconnected,this.handleDisconnected).on(fo.SignalRequestResponse,this.handleSignalRequestResponse).on(fo.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Vs(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Vs(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Vs(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Vs(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Vs(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield ta(50)}r(new xo("Request to update local metadata timed out","TimeoutError"))}catch(a){a instanceof Error&&r(a)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled($o.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled($o.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled($o.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(mo.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return Vs(this,void 0,void 0,(function*(){this.encryptionType=e?en.GCM:en.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return Vs(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case $o.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case $o.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case $o.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new wo(e)}}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a instanceof Error&&this.emit(mo.MediaDevicesError,a),this.pendingPublishing.delete(e),a}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Ka(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[o]=i}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===$o.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication($o.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Vs(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has($o.Source.Camera)&&!this.pendingPublishing.has($o.Source.Microphone)){this.pendingPublishing.add($o.Source.Camera),this.pendingPublishing.add($o.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete($o.Source.Camera),this.pendingPublishing.delete($o.Source.Microphone)}}}))}createTracks(e){return Vs(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=Fa(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield Dd(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(Aa(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=$o.Source.Microphone,this.emit(mo.AudioStreamAcquired)),Na(e)&&(this.cameraError=void 0,e.source=$o.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return Vs(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Co("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=Ao();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=Xo.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=aa()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new wo("no video track found");const s=new Xc(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=$o.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(mo.AudioStreamAcquired);const e=new Bc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=$o.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return Vs(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Vs(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(Ma(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Oa(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case $o.Source.Microphone:t="audioinput";break;case $o.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Bc(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Xc(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new wo("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Ka(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),Ka(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=Ao(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&ga(t,e.osVersion)>=0)||"Safari"===e.name&&ga(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>Vs(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==nc.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Ka(e)}));const i=()=>Vs(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(fo.SignalConnected,i),n(new Ro("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(fo.SignalConnected,i),this.engine.on(fo.Closing,(()=>{this.engine.off(fo.SignalConnected,i),n(new Ro("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Ka(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case Fi.CAMERA:return $o.Source.Camera;case Fi.MICROPHONE:return $o.Source.Microphone;case Fi.SCREEN_SHARE:return $o.Source.ScreenShare;case Fi.SCREEN_SHARE_AUDIO:return $o.Source.ScreenShareAudio;default:return $o.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Ka(e))),!1)}publish(e,t,i){return Vs(this,void 0,void 0,(function*(){var n,s,r,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Ro("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>Oa(e)&&t.source===e.source))&&e.source!==$o.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Ka(e))),t.stopMicTrackOnMute&&Aa(e)&&(e.stopOnMute=!0),e.source===$o.Source.ScreenShare&&oa()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(aa())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oa())return!1;if(aa()){const e=Ao();if((null==e?void 0:e.version)&&ga(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=_c),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===Ha(e.mime)))||(t.videoCodec=Ha(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(yo.Muted,this.onTrackMuted),e.on(yo.Unmuted,this.onTrackUnmuted),e.on(yo.Ended,this.handleTrackEnded),e.on(yo.UpstreamPaused,this.onTrackUpstreamPaused),e.on(yo.UpstreamResumed,this.onTrackUpstreamResumed),e.on(yo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new Fn({cid:e.mediaStreamTrack.id,name:t.name,type:$o.kindToProto(e.kind),muted:e.isMuted,source:$o.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===$o.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:Qo.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Ka(e)),{dims:i}))}m.width=i.width,m.height=i.height,Da(e)&&(sa(p)&&(e.source===$o.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Ka(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),m.simulcastCodecs=[new jn({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:_c}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===en.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new jn({codec:t.backupCodec.codec,cid:""})))),g=Gc(e.source===$o.Source.ScreenShare,m.width,m.height,t),m.layers=id(m.width,m.height,g,sa(t.videoCodec))}else e.kind===$o.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new _o("cannot publish track when not connected");const f=()=>Vs(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new _o("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),Da(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===$o.Source.ScreenShare||e.constraints.height&&_a(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if(oa()&&e.kind===$o.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&sa(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===$o.Kind.Video){const n=Ha(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Ka(e)),{codec:n})),t.videoCodec=n,g=Gc(e.source===$o.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new Nd(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),Da(e)?e.startMonitor(this.engine.client):Ma(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(mo.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Vs(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==en.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new wo("track is not published");if(!Da(e))throw new wo("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Us.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===$o.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Gc(e.source===$o.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Ka(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Fn({cid:a.mediaStreamTrack.id,type:$o.kindToProto(e.kind),muted:e.isMuted,source:$o.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=id(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new _o("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Vs(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(e,t){return Vs(this,void 0,void 0,(function*(){var i,n;if(Oa(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Ka(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?Ka(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(yo.Muted,this.onTrackMuted),e.off(yo.Unmuted,this.onTrackUnmuted),e.off(yo.Ended,this.handleTrackEnded),e.off(yo.UpstreamPaused,this.onTrackUpstreamPaused),e.off(yo.UpstreamResumed,this.onTrackUpstreamResumed),e.off(yo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ac.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),Da(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case $o.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case $o.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(mo.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Vs(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>Vs(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>Vs(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===$o.Source.ScreenShare||t.source===$o.Source.ScreenShareAudio||!Ma(t)&&!Da(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Vs(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?on.RELIABLE:on.LOSSY,s=i.destinationIdentities,r=i.topic,o=new rn({kind:n,value:{case:"user",value:new dn({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(o,n)}()}))}publishDtmf(e,t){return Vs(this,void 0,void 0,(function*(){const i=new rn({kind:on.RELIABLE,value:{case:"sipDtmf",value:new ln({code:e,digit:t})}});yield this.engine.sendDataPacket(i,on.RELIABLE)}))}sendChatMessage(e,t){return Vs(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new rn({value:{case:"chatMessage",value:new pn(Object.assign(Object.assign({},i),{timestamp:St.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,on.RELIABLE),this.emit(mo.ChatMessage,i),i}))}editChatMessage(e,t){return Vs(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new rn({value:{case:"chatMessage",value:new pn(Object.assign(Object.assign({},i),{timestamp:St.parse(i.timestamp),editTimestamp:St.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,on.RELIABLE),this.emit(mo.ChatMessage,i),i}))}sendText(e,t){return Vs(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map(((e,i)=>Vs(this,void 0,void 0,(function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(e){return Vs(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new In({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:Ia(s.timestamp),totalLength:Ia(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Rn({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Pn.UPDATE:Pn.CREATE})}}),o=null==e?void 0:e.destinationIdentities,a=new rn({destinationIdentities:o,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(a,on.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return Vs(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow(on.RELIABLE);const e=new On({content:t,streamId:n,chunkIndex:Ia(c)}),i=new rn({destinationIdentities:o,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,on.RELIABLE),c+=1}}))},close(){return Vs(this,void 0,void 0,(function*(){const e=new An({streamId:n}),t=new rn({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,on.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>Vs(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(fo.Closing,u);const h=new wd(l,s,(()=>this.engine.off(fo.Closing,u)));return h}))}sendFile(e,t){return Vs(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Vs(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return Vs(this,void 0,void 0,(function*(){var t,i,n,s,r;const o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:o,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new In({totalLength:Ia(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:Ia(Date.now()),contentHeader:{case:"byteHeader",value:new xn({name:c.name})}}),l=new rn({destinationIdentities:a,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,on.RELIABLE);let u=0;const h=new it,p=this.engine,m=this.log,g=new WritableStream({write(e){return Vs(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow(on.RELIABLE);const n=new rn({destinationIdentities:a,value:{case:"streamChunk",value:new On({content:t,streamId:o,chunkIndex:Ia(u)})}});yield p.sendDataPacket(n,on.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return Vs(this,void 0,void 0,(function*(){const e=new An({streamId:o}),t=new rn({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,on.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new Ed(g,c)}))}performRpc(e){return Vs(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,o)=>Vs(t,void 0,void 0,(function*(){var t,a,c,d;if(Lc(s)>15360)return void o(Mc.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&ga(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(Mc.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),o(Mc.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),o(Mc.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Vs(this,void 0,void 0,(function*(){const r=new rn({destinationIdentities:[e],kind:on.RELIABLE,value:{case:"rpcRequest",value:new mn({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,on.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,Mc.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Ka(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Ma(n)||Da(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Vs(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield ta(20)}}))}}class Ud extends Ad{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=jo.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(yo.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new Gn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new yn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(yo.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ad.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ad.SubscriptionStatus.Subscribed:Ad.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ad.PermissionStatus.Allowed:Ad.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}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,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(ja(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ja(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(yo.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(yo.VisibilityChanged,this.handleVisibilityChange),n.off(yo.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(yo.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(yo.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(yo.VisibilityChanged,this.handleVisibilityChange),e.on(yo.Ended,this.handleEnded),this.emit(yo.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(yo.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?yo.Muted:yo.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(yo.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(yo.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===$o.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ja(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Wn({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)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=jo.HIGH,this.emit(yo.UpdateSettings,e)}}class jd extends Md{static fromParticipantInfo(e,t,i){return new jd(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Yi.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(yo.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Ka(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on(yo.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(yo.SubscriptionPermissionChanged,(t=>{this.emit(mo.TrackSubscriptionPermissionChanged,e,t)})),e.on(yo.SubscriptionStatusChanged,(t=>{this.emit(mo.TrackSubscriptionStatusChanged,e,t)})),e.on(yo.Subscribed,(t=>{this.emit(mo.TrackSubscribed,t,e)})),e.on(yo.Unsubscribed,(t=>{this.emit(mo.TrackUnsubscribed,t,e)})),e.on(yo.SubscriptionFailed,(t=>{this.emit(mo.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$o.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$o.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let o,a=this.getTrackPublicationBySid(t);return a||t.startsWith("TR")||this.trackPublications.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),a?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Ka(a))),void this.emit(mo.TrackSubscriptionFailed,t)):(o="video"===e.kind?new Rd(e,t,n,s):new Pd(e,t,n,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&La(o)&&Aa(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(mo.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=$o.kindFromProto(e.type);if(!t)return;r=new Ud(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==$o.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Ka(o),newTrack:Ka(r)})),this.addTrackPublication(r)}t.set(e.sid,r)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Ka(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(mo.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case $o.Kind.Audio:this.audioTrackPublications.delete(e);break;case $o.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(mo.TrackUnpublished,i)}setAudioOutput(e){return Vs(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Aa(i.track)&&La(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(md=pd||(pd={})).Disconnected="disconnected",md.Connecting="connecting",md.Connected="connected",md.Reconnecting="reconnecting",md.SignalReconnecting="signalReconnecting";class Fd extends zs.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=pd.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Us,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>Vs(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!ia()&&!na())throw la()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===pd.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(pd.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ua(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new bd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,o,a)=>Vs(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof So&&u.reason!==ro.Cancelled&&u.reason!==ro.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof So&&(401===h.status||h.reason===ro.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,o,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ra(u)),o(u))}else{let e=qi.UNKNOWN_REASON;u instanceof So&&(e=Ra(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(u)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ea(((e,t)=>{r(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Vs(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Eo("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Vs(this,void 0,void 0,(function*(){var s,r;this.state===pd.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Oc),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(ho.SignalConnected)}catch(o){yield this.engine.close(),this.recreateEngine();const e=new So("could not establish signal connection",ro.ServerUnreachable);throw o instanceof Error&&(e.message="".concat(e.message,": ").concat(o.message)),o instanceof So&&(e.reason=o.reason,e.status=o.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:o})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new So("Connection attempt aborted",ro.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(a){throw yield this.engine.close(),this.recreateEngine(),a}da()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),da()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(pd.Connected),this.emit(ho.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Vs(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const o=yield e.disconnectLock.lock();try{if(e.state===pd.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===pd.Connecting||e.state===pd.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new So("Client initiated disconnect",ro.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,qi.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()}))},this.onPageLeave=()=>Vs(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Vs(this,void 0,void 0,(function*(){const e=[],t=Ao();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=wa();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(ho.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>Vs(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(pd.Reconnecting)&&this.emit(ho.Reconnecting)},this.handleSignalRestarted=e=>Vs(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(pd.Connected),this.emit(ho.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Qi.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(ho.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(ho.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=$o.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(mo.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(ho.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(ho.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(mo.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(ho.SipDTMFReceived,t,e),null==e||e.emit(mo.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(yo.TranscriptionReceived,s),null==i||i.emit(mo.TranscriptionReceived,s,n),this.emit(ho.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(ho.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(ho.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ho.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ho.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ho.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ho.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Vs(this,void 0,void 0,(function*(){var e,t,i;const n=Qa.getInstance().previousDevices,s=yield Qa.getInstance().getDevices(void 0,!1),r=Ao();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let a of s){const e=n.find((e=>e.deviceId===a.deviceId));e&&""!==e.label&&e.kind===a.kind&&e.label!==a.label&&"default"===this.getActiveDevice(a.kind)&&this.emit(ho.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const r=qa(a),o=this.localParticipant.getTrackPublication(r);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===a)),d=this.getActiveDevice(a);d===(null===(t=n.filter((e=>e.kind===a))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(a,c[0].deviceId):"audioinput"===a&&!aa()||"videoinput"===a||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(a)))&&(yield this.switchActiveDevice(a,c[0].deviceId))}this.emit(ho.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(ho.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(ho.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(ho.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(ho.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(ho.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(ho.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(ho.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Vs(this,void 0,void 0,(function*(){var t,i,n,s,r,o;null===(t=e.track)||void 0===t||t.on(yo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(yo.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(ho.LocalTrackPublished,e,this.localParticipant),Ma(e.track)&&(yield e.track.checkForSilence())&&this.emit(ho.LocalAudioSilenceDetected,e);const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=Za(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(ho.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(yo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(yo.Restarted,this.onLocalTrackRestarted),this.emit(ho.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Vs(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Za(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(ho.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(ho.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(ho.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(ho.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(ho.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ic),e),this.log=js(null!==(i=this.options.loggerName)&&void 0!==i?i:Ns.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Rc),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},xc),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Pc),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new it,this.localParticipant=new Ld("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",_a(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",_a(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",_a(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),da()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),Fd.cleanupRegistry&&Fd.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,r){return Vs(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,Mc.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,Mc.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});Lc(r)>15360?(a=Mc.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof Mc?a=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),a=Mc.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}setE2EEEnabled(e){return Vs(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Wa(this.options.e2ee),this.e2eeManager.on(io.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(ho.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(io.EncryptionError,(e=>this.emit(ho.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Vs(this,void 0,void 0,(function*(){return this.state===pd.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(fo.RoomUpdate,i),e(t.sid))};this.engine.on(fo.RoomUpdate,i),this.once(ho.Disconnected,(()=>{this.engine.off(fo.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new vd(this.options),this.engine.on(fo.ParticipantUpdate,this.handleParticipantUpdates).on(fo.RoomUpdate,this.handleRoomUpdate).on(fo.SpeakersChanged,this.handleSpeakersChanged).on(fo.StreamStateChanged,this.handleStreamStateUpdate).on(fo.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(fo.SubscriptionError,this.handleSubscriptionError).on(fo.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(fo.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(fo.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(fo.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(fo.DataPacketReceived,this.handleDataPacket).on(fo.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(pd.SignalReconnecting)&&this.emit(ho.SignalReconnecting)})).on(fo.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(pd.Connected)&&this.emit(ho.Reconnected)})).on(fo.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===pd.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(fo.Restarting,this.handleRestarting).on(fo.SignalRestarted,this.handleSignalRestarted).on(fo.Offline,(()=>{this.setAndEmitConnectionState(pd.Reconnecting)&&this.emit(ho.Reconnecting)})).on(fo.DCBufferStatusChanged,((e,t)=>{this.emit(ho.DCBufferStatusChanged,e,t)})).on(fo.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(mo.LocalTrackSubscribed,t),this.emitWhenConnected(ho.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Qa.getInstance().getDevices(e,t)}prepareConnection(e,t){return Vs(this,void 0,void 0,(function*(){if(this.state===pd.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ua(new URL(e))&&t){this.regionUrlProvider=new bd(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===pd.Disconnected&&(this.regionUrl=i,yield fetch(Pa(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Pa(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Vs(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new vs({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new vs({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new vs({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new vs({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>Vs(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new vs({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Vs(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new vs({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new vs({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Vs(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Yn({reason:qi.CLIENT_INITIATED,action:Xn.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new vs({scenario:{case:"subscriberBandwidth",value:Ia(t)}});break;case"leave-full-reconnect":i=new vs({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Vs(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===$o.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===$o.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!ra()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(o=yield Qa.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(u=i.options).audioOutput)&&void 0!==a||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(ho.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(mo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(mo.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(mo.AttributesChanged,this.onLocalAttributesChanged).on(mo.TrackMuted,this.onLocalTrackMuted).on(mo.TrackUnmuted,this.onLocalTrackUnmuted).on(mo.LocalTrackPublished,this.onLocalTrackPublished).on(mo.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(mo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(mo.MediaDevicesError,this.onMediaDevicesError).on(mo.AudioStreamAcquired,this.startAudio).on(mo.ChatMessage,this.onLocalChatMessageSent).on(mo.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===pd.Connecting||this.state===pd.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(ho.Reconnected,n),this.off(ho.Connected,n),this.off(ho.Disconnected,s)};return this.once(ho.Reconnected,n),this.once(ho.Connected,n),void this.once(ho.Disconnected,s)}if(this.state===pd.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],o=e.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==pd.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(mo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(mo.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(mo.AttributesChanged,this.onLocalAttributesChanged).off(mo.TrackMuted,this.onLocalTrackMuted).off(mo.TrackUnmuted,this.onLocalTrackUnmuted).off(mo.LocalTrackPublished,this.onLocalTrackPublished).off(mo.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(mo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(mo.MediaDevicesError,this.onMediaDevicesError).off(mo.AudioStreamAcquired,this.startAudio).off(mo.ChatMessage,this.onLocalChatMessageSent).off(mo.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),da()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(pd.Disconnected),this.emit(ho.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(ho.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return Vs(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:xa(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new Td(r,o,xa(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new Sd(s,r,xa(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return Vs(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Va())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),ta(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(ho.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?jd.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new jd(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(ho.ParticipantConnected,i),i.on(mo.TrackPublished,(e=>{this.emitWhenConnected(ho.TrackPublished,e,i)})).on(mo.TrackSubscribed,((e,t)=>{e.kind===$o.Kind.Audio?(e.on(yo.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(yo.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===$o.Kind.Video&&(e.on(yo.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(yo.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ho.TrackSubscribed,e,t,i)})).on(mo.TrackUnpublished,(e=>{this.emit(ho.TrackUnpublished,e,i)})).on(mo.TrackUnsubscribed,((e,t)=>{this.emit(ho.TrackUnsubscribed,e,t,i)})).on(mo.TrackMuted,(e=>{this.emitWhenConnected(ho.TrackMuted,e,i)})).on(mo.TrackUnmuted,(e=>{this.emitWhenConnected(ho.TrackUnmuted,e,i)})).on(mo.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(ho.ParticipantMetadataChanged,e,i)})).on(mo.ParticipantNameChanged,(e=>{this.emitWhenConnected(ho.ParticipantNameChanged,e,i)})).on(mo.AttributesChanged,(e=>{this.emitWhenConnected(ho.ParticipantAttributesChanged,e,i)})).on(mo.ConnectionQualityChanged,(e=>{this.emitWhenConnected(ho.ConnectionQualityChanged,e,i)})).on(mo.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(ho.ParticipantPermissionsChanged,e,i)})).on(mo.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(ho.TrackSubscriptionStatusChanged,e,t,i)})).on(mo.TrackSubscriptionFailed,((e,t)=>{this.emit(ho.TrackSubscriptionFailed,e,i,t)})).on(mo.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(ho.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ua(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Lo.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qi.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Lo.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(ho.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===pd.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===pd.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Vs(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ki({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:St.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ji({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ho.SignalConnected),this.emit(ho.Connected),this.setAndEmitConnectionState(pd.Connected),n.video){const e=new Nd($o.Kind.Video,new nn({source:Fi.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ji.AUDIO,name:"video-dummy"}),new Xc(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Sa(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(mo.LocalTrackPublished,e)}if(n.audio){const e=new Nd($o.Kind.Audio,new nn({source:Fi.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ji.AUDIO}),new Bc(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wa(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(mo.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new Ji({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Qi.ACTIVE,tracks:[],joinedAt:St.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Sa(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new nn({source:Fi.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ji.AUDIO});n.addSubscribedMediaTrack(r,o.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(s.audio){const e=wa(),i=new nn({source:Fi.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ji.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==ho.ActiveSpeakersChanged&&e!==ho.TranscriptionReceived){const t=$d(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function $d(e){return e.map((e=>{if(e)return Array.isArray(e)?$d(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}Fd.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(fd=gd||(gd={}))[fd.IDLE=0]="IDLE",fd[fd.RUNNING=1]="RUNNING",fd[fd.SKIPPED=2]="SKIPPED",fd[fd.SUCCESS=3]="SUCCESS",fd[fd.FAILED=4]="FAILED",zs.EventEmitter,zs.EventEmitter;const Bd={}.DEV_MODE?"http://localhost:5173/api":"https://iamobi.ai/api";var Vd,qd,Zd;(qd=Vd||(Vd={})).assertEqual=e=>e,qd.assertIs=function(e){},qd.assertNever=function(e){throw new Error},qd.arrayToEnum=e=>{const t={};for(const i of e)t[i]=i;return t},qd.getValidEnumValues=e=>{const t=qd.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),i={};for(const n of t)i[n]=e[n];return qd.objectValues(i)},qd.objectValues=e=>qd.objectKeys(e).map((function(t){return e[t]})),qd.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.push(i);return t},qd.find=(e,t)=>{for(const i of e)if(t(i))return i},qd.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,qd.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},qd.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Zd||(Zd={})).mergeShapes=(e,t)=>({...e,...t});const Hd=Vd.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zd=e=>{switch(typeof e){case"undefined":return Hd.undefined;case"string":return Hd.string;case"number":return isNaN(e)?Hd.nan:Hd.number;case"boolean":return Hd.boolean;case"function":return Hd.function;case"bigint":return Hd.bigint;case"symbol":return Hd.symbol;case"object":return Array.isArray(e)?Hd.array:null===e?Hd.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Hd.promise:"undefined"!=typeof Map&&e instanceof Map?Hd.map:"undefined"!=typeof Set&&e instanceof Set?Hd.set:"undefined"!=typeof Date&&e instanceof Date?Hd.date:Hd.object;default:return Hd.unknown}},Kd=Vd.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Gd extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},i={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)i._errors.push(t(s));else{let e=i,n=0;for(;n<s.path.length;){const i=s.path[n];n===s.path.length-1?(e[i]=e[i]||{_errors:[]},e[i]._errors.push(t(s))):e[i]=e[i]||{_errors:[]},e=e[i],n++}}};return n(this),i}static assert(e){if(!(e instanceof Gd))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Vd.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Gd.create=e=>new Gd(e);const Wd=(e,t)=>{let i;switch(e.code){case Kd.invalid_type:i=e.received===Hd.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Kd.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(e.expected,Vd.jsonStringifyReplacer)}`;break;case Kd.unrecognized_keys:i=`Unrecognized key(s) in object: ${Vd.joinValues(e.keys,", ")}`;break;case Kd.invalid_union:i="Invalid input";break;case Kd.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Vd.joinValues(e.options)}`;break;case Kd.invalid_enum_value:i=`Invalid enum value. Expected ${Vd.joinValues(e.options)}, received '${e.received}'`;break;case Kd.invalid_arguments:i="Invalid function arguments";break;case Kd.invalid_return_type:i="Invalid function return type";break;case Kd.invalid_date:i="Invalid date";break;case Kd.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(i=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(i=`${i} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?i=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?i=`Invalid input: must end with "${e.validation.endsWith}"`:Vd.assertNever(e.validation):i="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Kd.too_small:i="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Kd.too_big:i="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Kd.custom:i="Invalid input";break;case Kd.invalid_intersection_types:i="Intersection results could not be merged";break;case Kd.not_multiple_of:i=`Number must be a multiple of ${e.multipleOf}`;break;case Kd.not_finite:i="Number must be finite";break;default:i=t.defaultError,Vd.assertNever(e)}return{message:i}};let Jd=Wd;function Qd(){return Jd}const Yd=e=>{const{data:t,path:i,errorMaps:n,issueData:s}=e,r=[...i,...s.path||[]],o={...s,path:r};if(void 0!==s.message)return{...s,path:r,message:s.message};let a="";const c=n.filter((e=>!!e)).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...s,path:r,message:a}};function Xd(e,t){const i=Qd(),n=Yd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===Wd?void 0:Wd].filter((e=>!!e))});e.common.issues.push(n)}class el{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const n of t){if("aborted"===n.status)return tl;"dirty"===n.status&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const e=await n.key,t=await n.value;i.push({key:e,value:t})}return el.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return tl;if("aborted"===s.status)return tl;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(i[t.value]=s.value)}return{status:e.value,value:i}}}const tl=Object.freeze({status:"aborted"}),il=e=>({status:"dirty",value:e}),nl=e=>({status:"valid",value:e}),sl=e=>"aborted"===e.status,rl=e=>"dirty"===e.status,ol=e=>"valid"===e.status,al=e=>"undefined"!=typeof Promise&&e instanceof Promise;function cl(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}function dl(e,t,i,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,i):s?s.value=i:t.set(e,i),i}var ll,ul,hl,pl;"function"==typeof SuppressedError&&SuppressedError,(ul=ll||(ll={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},ul.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class ml{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const gl=(e,t)=>{if(ol(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Gd(e.common.issues);return this._error=t,this._error}}};function fl(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:n,description:s}=e;if(t&&(i||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{var r,o;const{message:a}=e;return"invalid_enum_value"===t.code?{message:null!=a?a:s.defaultError}:void 0===s.data?{message:null!==(r=null!=a?a:n)&&void 0!==r?r:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(o=null!=a?a:i)&&void 0!==o?o:s.defaultError}},description:s}}class vl{get description(){return this._def.description}_getType(e){return zd(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new el,ctx:{common:e.parent.common,data:e.data,parsedType:zd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(al(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const n={common:{issues:[],async:null!==(i=null==t?void 0:t.async)&&void 0!==i&&i,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zd(e)},s=this._parseSync({data:e,path:n.path,parent:n});return gl(n,s)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zd(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return ol(t)?{value:t.value}:{issues:n.common.issues}}catch(s){(null===(i=null===(t=null==s?void 0:s.message)||void 0===t?void 0:t.toLowerCase())||void 0===i?void 0:i.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>ol(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zd(e)},n=this._parse({data:e,path:i.path,parent:i}),s=await(al(n)?n:Promise.resolve(n));return gl(i,s)}refine(e,t){const i=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),r=()=>n.addIssue({code:Kd.custom,...i(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(r(),!1))):!!s||(r(),!1)}))}refinement(e,t){return this._refinement(((i,n)=>!!e(i)||(n.addIssue("function"==typeof t?t(i,n):t),!1)))}_refinement(e){return new vu({schema:this,typeName:Iu.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return yu.create(this,this._def)}nullable(){return bu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yl.create(this)}promise(){return fu.create(this,this._def)}or(e){return tu.create([this,e],this._def)}and(e){return ru.create(this,e,this._def)}transform(e){return new vu({...fl(this._def),schema:this,typeName:Iu.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ku({...fl(this._def),innerType:this,defaultValue:t,typeName:Iu.ZodDefault})}brand(){return new wu({typeName:Iu.ZodBranded,type:this,...fl(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Tu({...fl(this._def),innerType:this,catchValue:t,typeName:Iu.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Eu.create(this,e)}readonly(){return _u.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const yl=/^c[^\s-]{8,}$/i,bl=/^[0-9a-z]+$/,kl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Tl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Sl=/^[a-z0-9_-]{21}$/i,Cl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,El=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _l;const Pl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Rl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xl=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Il=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ol=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Al=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Dl=new RegExp(`^${Nl}$`);function Ml(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function Ll(e){let t=`${Nl}T${Ml(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function Ul(e,t){if(!Cl.test(e))return!1;try{const[i]=e.split("."),n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||!s.typ||!s.alg||t&&s.alg!==t)}catch(i){return!1}}function jl(e,t){return!("v4"!==t&&t||!Rl.test(e))||!("v6"!==t&&t||!Il.test(e))}class Fl extends vl{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Hd.string){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.string,received:t.parsedType}),tl}const t=new el;let i;for(const o of this._def.checks)if("min"===o.kind)e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("max"===o.kind)e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("length"===o.kind){const n=e.data.length>o.value,s=e.data.length<o.value;(n||s)&&(i=this._getOrReturnCtx(e,i),n?Xd(i,{code:Kd.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&Xd(i,{code:Kd.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),t.dirty())}else if("email"===o.kind)El.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"email",code:Kd.invalid_string,message:o.message}),t.dirty());else if("emoji"===o.kind)_l||(_l=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_l.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"emoji",code:Kd.invalid_string,message:o.message}),t.dirty());else if("uuid"===o.kind)Tl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"uuid",code:Kd.invalid_string,message:o.message}),t.dirty());else if("nanoid"===o.kind)Sl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"nanoid",code:Kd.invalid_string,message:o.message}),t.dirty());else if("cuid"===o.kind)yl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"cuid",code:Kd.invalid_string,message:o.message}),t.dirty());else if("cuid2"===o.kind)bl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"cuid2",code:Kd.invalid_string,message:o.message}),t.dirty());else if("ulid"===o.kind)kl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"ulid",code:Kd.invalid_string,message:o.message}),t.dirty());else if("url"===o.kind)try{new URL(e.data)}catch(r){i=this._getOrReturnCtx(e,i),Xd(i,{validation:"url",code:Kd.invalid_string,message:o.message}),t.dirty()}else"regex"===o.kind?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"regex",code:Kd.invalid_string,message:o.message}),t.dirty())):"trim"===o.kind?e.data=e.data.trim():"includes"===o.kind?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),t.dirty()):"toLowerCase"===o.kind?e.data=e.data.toLowerCase():"toUpperCase"===o.kind?e.data=e.data.toUpperCase():"startsWith"===o.kind?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:{startsWith:o.value},message:o.message}),t.dirty()):"endsWith"===o.kind?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:{endsWith:o.value},message:o.message}),t.dirty()):"datetime"===o.kind?Ll(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:"datetime",message:o.message}),t.dirty()):"date"===o.kind?Dl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:"date",message:o.message}),t.dirty()):"time"===o.kind?new RegExp(`^${Ml(o)}$`).test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.invalid_string,validation:"time",message:o.message}),t.dirty()):"duration"===o.kind?wl.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"duration",code:Kd.invalid_string,message:o.message}),t.dirty()):"ip"===o.kind?(n=e.data,("v4"!==(s=o.version)&&s||!Pl.test(n))&&("v6"!==s&&s||!xl.test(n))&&(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"ip",code:Kd.invalid_string,message:o.message}),t.dirty())):"jwt"===o.kind?Ul(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"jwt",code:Kd.invalid_string,message:o.message}),t.dirty()):"cidr"===o.kind?jl(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"cidr",code:Kd.invalid_string,message:o.message}),t.dirty()):"base64"===o.kind?Ol.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"base64",code:Kd.invalid_string,message:o.message}),t.dirty()):"base64url"===o.kind?Al.test(e.data)||(i=this._getOrReturnCtx(e,i),Xd(i,{validation:"base64url",code:Kd.invalid_string,message:o.message}),t.dirty()):Vd.assertNever(o);var n,s;return{status:t.value,value:e.data}}_regex(e,t,i){return this.refinement((t=>e.test(t)),{validation:t,code:Kd.invalid_string,...ll.errToObj(i)})}_addCheck(e){return new Fl({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ll.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ll.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ll.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ll.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ll.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ll.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ll.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ll.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ll.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ll.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ll.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ll.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ll.errToObj(e)})}datetime(e){var t,i;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(i=null==e?void 0:e.local)&&void 0!==i&&i,...ll.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...ll.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...ll.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ll.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...ll.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ll.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ll.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ll.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ll.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ll.errToObj(t)})}nonempty(e){return this.min(1,ll.errToObj(e))}trim(){return new Fl({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fl({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fl({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function $l(e,t){const i=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=i>n?i:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}Fl.create=e=>{var t;return new Fl({checks:[],typeName:Iu.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...fl(e)})};class Bl extends vl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Hd.number){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.number,received:t.parsedType}),tl}let t;const i=new el;for(const n of this._def.checks)"int"===n.kind?Vd.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==$l(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.not_finite,message:n.message}),i.dirty()):Vd.assertNever(n);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ll.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ll.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ll.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ll.toString(t))}setLimit(e,t,i,n){return new Bl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:ll.toString(n)}]})}_addCheck(e){return new Bl({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ll.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ll.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ll.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ll.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ll.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ll.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ll.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ll.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ll.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&Vd.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;"min"===i.kind?(null===t||i.value>t)&&(t=i.value):"max"===i.kind&&(null===e||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Bl.create=e=>new Bl({checks:[],typeName:Iu.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...fl(e)});class Vl extends vl{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==Hd.bigint)return this._getInvalidInput(e);let t;const i=new el;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Xd(t,{code:Kd.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Vd.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.bigint,received:t.parsedType}),tl}gte(e,t){return this.setLimit("min",e,!0,ll.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ll.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ll.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ll.toString(t))}setLimit(e,t,i,n){return new Vl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:ll.toString(n)}]})}_addCheck(e){return new Vl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ll.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ll.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ll.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ll.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ll.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Vl.create=e=>{var t;return new Vl({checks:[],typeName:Iu.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...fl(e)})};class ql extends vl{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==Hd.boolean){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.boolean,received:t.parsedType}),tl}return nl(e.data)}}ql.create=e=>new ql({typeName:Iu.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...fl(e)});class Zl extends vl{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Hd.date){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.date,received:t.parsedType}),tl}if(isNaN(e.data.getTime()))return Xd(this._getOrReturnCtx(e),{code:Kd.invalid_date}),tl;const t=new el;let i;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(i=this._getOrReturnCtx(e,i),Xd(i,{code:Kd.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):Vd.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Zl({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ll.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ll.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Zl.create=e=>new Zl({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Iu.ZodDate,...fl(e)});class Hl extends vl{_parse(e){if(this._getType(e)!==Hd.symbol){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.symbol,received:t.parsedType}),tl}return nl(e.data)}}Hl.create=e=>new Hl({typeName:Iu.ZodSymbol,...fl(e)});class zl extends vl{_parse(e){if(this._getType(e)!==Hd.undefined){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.undefined,received:t.parsedType}),tl}return nl(e.data)}}zl.create=e=>new zl({typeName:Iu.ZodUndefined,...fl(e)});class Kl extends vl{_parse(e){if(this._getType(e)!==Hd.null){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.null,received:t.parsedType}),tl}return nl(e.data)}}Kl.create=e=>new Kl({typeName:Iu.ZodNull,...fl(e)});class Gl extends vl{constructor(){super(...arguments),this._any=!0}_parse(e){return nl(e.data)}}Gl.create=e=>new Gl({typeName:Iu.ZodAny,...fl(e)});class Wl extends vl{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nl(e.data)}}Wl.create=e=>new Wl({typeName:Iu.ZodUnknown,...fl(e)});class Jl extends vl{_parse(e){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.never,received:t.parsedType}),tl}}Jl.create=e=>new Jl({typeName:Iu.ZodNever,...fl(e)});class Ql extends vl{_parse(e){if(this._getType(e)!==Hd.undefined){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.void,received:t.parsedType}),tl}return nl(e.data)}}Ql.create=e=>new Ql({typeName:Iu.ZodVoid,...fl(e)});class Yl extends vl{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==Hd.array)return Xd(t,{code:Kd.invalid_type,expected:Hd.array,received:t.parsedType}),tl;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(Xd(t,{code:e?Kd.too_big:Kd.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(Xd(t,{code:Kd.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(Xd(t,{code:Kd.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map(((e,i)=>n.type._parseAsync(new ml(t,e,t.path,i))))).then((e=>el.mergeArray(i,e)));const s=[...t.data].map(((e,i)=>n.type._parseSync(new ml(t,e,t.path,i))));return el.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new Yl({...this._def,minLength:{value:e,message:ll.toString(t)}})}max(e,t){return new Yl({...this._def,maxLength:{value:e,message:ll.toString(t)}})}length(e,t){return new Yl({...this._def,exactLength:{value:e,message:ll.toString(t)}})}nonempty(e){return this.min(1,e)}}function Xl(e){if(e instanceof eu){const t={};for(const i in e.shape){const n=e.shape[i];t[i]=yu.create(Xl(n))}return new eu({...e._def,shape:()=>t})}return e instanceof Yl?new Yl({...e._def,type:Xl(e.element)}):e instanceof yu?yu.create(Xl(e.unwrap())):e instanceof bu?bu.create(Xl(e.unwrap())):e instanceof ou?ou.create(e.items.map((e=>Xl(e)))):e}Yl.create=(e,t)=>new Yl({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Iu.ZodArray,...fl(t)});class eu extends vl{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Vd.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==Hd.object){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.object,received:t.parsedType}),tl}const{status:t,ctx:i}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),r=[];if(!(this._def.catchall instanceof Jl&&"strip"===this._def.unknownKeys))for(const a in i.data)s.includes(a)||r.push(a);const o=[];for(const a of s){const e=n[a],t=i.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new ml(i,t,i.path,a)),alwaysSet:a in i.data})}if(this._def.catchall instanceof Jl){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of r)o.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===e)r.length>0&&(Xd(i,{code:Kd.unrecognized_keys,keys:r}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of r){const n=i.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new ml(i,n,i.path,t)),alwaysSet:t in i.data})}}return i.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of o){const i=await t.key,n=await t.value;e.push({key:i,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>el.mergeObjectSync(t,e))):el.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return ll.errToObj,new eu({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,i)=>{var n,s,r,o;const a=null!==(r=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,i).message)&&void 0!==r?r:i.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=ll.errToObj(e).message)&&void 0!==o?o:a}:{message:a}}}:{}})}strip(){return new eu({...this._def,unknownKeys:"strip"})}passthrough(){return new eu({...this._def,unknownKeys:"passthrough"})}extend(e){return new eu({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new eu({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Iu.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new eu({...this._def,catchall:e})}pick(e){const t={};return Vd.objectKeys(e).forEach((i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])})),new eu({...this._def,shape:()=>t})}omit(e){const t={};return Vd.objectKeys(this.shape).forEach((i=>{e[i]||(t[i]=this.shape[i])})),new eu({...this._def,shape:()=>t})}deepPartial(){return Xl(this)}partial(e){const t={};return Vd.objectKeys(this.shape).forEach((i=>{const n=this.shape[i];e&&!e[i]?t[i]=n:t[i]=n.optional()})),new eu({...this._def,shape:()=>t})}required(e){const t={};return Vd.objectKeys(this.shape).forEach((i=>{if(e&&!e[i])t[i]=this.shape[i];else{let e=this.shape[i];for(;e instanceof yu;)e=e._def.innerType;t[i]=e}})),new eu({...this._def,shape:()=>t})}keyof(){return pu(Vd.objectKeys(this.shape))}}eu.create=(e,t)=>new eu({shape:()=>e,unknownKeys:"strip",catchall:Jl.create(),typeName:Iu.ZodObject,...fl(t)}),eu.strictCreate=(e,t)=>new eu({shape:()=>e,unknownKeys:"strict",catchall:Jl.create(),typeName:Iu.ZodObject,...fl(t)}),eu.lazycreate=(e,t)=>new eu({shape:e,unknownKeys:"strip",catchall:Jl.create(),typeName:Iu.ZodObject,...fl(t)});class tu extends vl{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;if(t.common.async)return Promise.all(i.map((async e=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const i=e.map((e=>new Gd(e.ctx.common.issues)));return Xd(t,{code:Kd.invalid_union,unionErrors:i}),tl}));{let e;const n=[];for(const r of i){const i={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:i});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new Gd(e)));return Xd(t,{code:Kd.invalid_union,unionErrors:s}),tl}}get options(){return this._def.options}}tu.create=(e,t)=>new tu({options:e,typeName:Iu.ZodUnion,...fl(t)});const iu=e=>e instanceof uu?iu(e.schema):e instanceof vu?iu(e.innerType()):e instanceof hu?[e.value]:e instanceof mu?e.options:e instanceof gu?Vd.objectValues(e.enum):e instanceof ku?iu(e._def.innerType):e instanceof zl?[void 0]:e instanceof Kl?[null]:e instanceof yu?[void 0,...iu(e.unwrap())]:e instanceof bu?[null,...iu(e.unwrap())]:e instanceof wu||e instanceof _u?iu(e.unwrap()):e instanceof Tu?iu(e._def.innerType):[];class nu extends vl{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Hd.object)return Xd(t,{code:Kd.invalid_type,expected:Hd.object,received:t.parsedType}),tl;const i=this.discriminator,n=t.data[i],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(Xd(t,{code:Kd.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),tl)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const s of t){const t=iu(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new nu({typeName:Iu.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...fl(i)})}}function su(e,t){const i=zd(e),n=zd(t);if(e===t)return{valid:!0,data:e};if(i===Hd.object&&n===Hd.object){const i=Vd.objectKeys(t),n=Vd.objectKeys(e).filter((e=>-1!==i.indexOf(e))),s={...e,...t};for(const r of n){const i=su(e[r],t[r]);if(!i.valid)return{valid:!1};s[r]=i.data}return{valid:!0,data:s}}if(i===Hd.array&&n===Hd.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let n=0;n<e.length;n++){const s=su(e[n],t[n]);if(!s.valid)return{valid:!1};i.push(s.data)}return{valid:!0,data:i}}return i===Hd.date&&n===Hd.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ru extends vl{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(e,n)=>{if(sl(e)||sl(n))return tl;const s=su(e.value,n.value);return s.valid?((rl(e)||rl(n))&&t.dirty(),{status:t.value,value:s.data}):(Xd(i,{code:Kd.invalid_intersection_types}),tl)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ru.create=(e,t,i)=>new ru({left:e,right:t,typeName:Iu.ZodIntersection,...fl(i)});class ou extends vl{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Hd.array)return Xd(i,{code:Kd.invalid_type,expected:Hd.array,received:i.parsedType}),tl;if(i.data.length<this._def.items.length)return Xd(i,{code:Kd.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tl;!this._def.rest&&i.data.length>this._def.items.length&&(Xd(i,{code:Kd.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ml(i,e,i.path,t)):null})).filter((e=>!!e));return i.common.async?Promise.all(n).then((e=>el.mergeArray(t,e))):el.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ou({...this._def,rest:e})}}ou.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ou({items:e,typeName:Iu.ZodTuple,rest:null,...fl(t)})};class au extends vl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Hd.object)return Xd(i,{code:Kd.invalid_type,expected:Hd.object,received:i.parsedType}),tl;const n=[],s=this._def.keyType,r=this._def.valueType;for(const o in i.data)n.push({key:s._parse(new ml(i,o,i.path,o)),value:r._parse(new ml(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?el.mergeObjectAsync(t,n):el.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return new au(t instanceof vl?{keyType:e,valueType:t,typeName:Iu.ZodRecord,...fl(i)}:{keyType:Fl.create(),valueType:e,typeName:Iu.ZodRecord,...fl(t)})}}class cu extends vl{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Hd.map)return Xd(i,{code:Kd.invalid_type,expected:Hd.map,received:i.parsedType}),tl;const n=this._def.keyType,s=this._def.valueType,r=[...i.data.entries()].map((([e,t],r)=>({key:n._parse(new ml(i,e,i.path,[r,"key"])),value:s._parse(new ml(i,t,i.path,[r,"value"]))})));if(i.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const i of r){const n=await i.key,s=await i.value;if("aborted"===n.status||"aborted"===s.status)return tl;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const i of r){const n=i.key,s=i.value;if("aborted"===n.status||"aborted"===s.status)return tl;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}cu.create=(e,t,i)=>new cu({valueType:t,keyType:e,typeName:Iu.ZodMap,...fl(i)});class du extends vl{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Hd.set)return Xd(i,{code:Kd.invalid_type,expected:Hd.set,received:i.parsedType}),tl;const n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(Xd(i,{code:Kd.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(Xd(i,{code:Kd.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function r(e){const i=new Set;for(const n of e){if("aborted"===n.status)return tl;"dirty"===n.status&&t.dirty(),i.add(n.value)}return{status:t.value,value:i}}const o=[...i.data.values()].map(((e,t)=>s._parse(new ml(i,e,i.path,t))));return i.common.async?Promise.all(o).then((e=>r(e))):r(o)}min(e,t){return new du({...this._def,minSize:{value:e,message:ll.toString(t)}})}max(e,t){return new du({...this._def,maxSize:{value:e,message:ll.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}du.create=(e,t)=>new du({valueType:e,minSize:null,maxSize:null,typeName:Iu.ZodSet,...fl(t)});class lu extends vl{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Hd.function)return Xd(t,{code:Kd.invalid_type,expected:Hd.function,received:t.parsedType}),tl;function i(e,i){return Yd({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qd(),Wd].filter((e=>!!e)),issueData:{code:Kd.invalid_arguments,argumentsError:i}})}function n(e,i){return Yd({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qd(),Wd].filter((e=>!!e)),issueData:{code:Kd.invalid_return_type,returnTypeError:i}})}const s={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof fu){const e=this;return nl((async function(...t){const o=new Gd([]),a=await e._def.args.parseAsync(t,s).catch((e=>{throw o.addIssue(i(t,e)),o})),c=await Reflect.apply(r,this,a);return await e._def.returns._def.type.parseAsync(c,s).catch((e=>{throw o.addIssue(n(c,e)),o}))}))}{const e=this;return nl((function(...t){const o=e._def.args.safeParse(t,s);if(!o.success)throw new Gd([i(t,o.error)]);const a=Reflect.apply(r,this,o.data),c=e._def.returns.safeParse(a,s);if(!c.success)throw new Gd([n(a,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new lu({...this._def,args:ou.create(e).rest(Wl.create())})}returns(e){return new lu({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new lu({args:e||ou.create([]).rest(Wl.create()),returns:t||Wl.create(),typeName:Iu.ZodFunction,...fl(i)})}}class uu extends vl{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}uu.create=(e,t)=>new uu({getter:e,typeName:Iu.ZodLazy,...fl(t)});class hu extends vl{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Xd(t,{received:t.data,code:Kd.invalid_literal,expected:this._def.value}),tl}return{status:"valid",value:e.data}}get value(){return this._def.value}}function pu(e,t){return new mu({values:e,typeName:Iu.ZodEnum,...fl(t)})}hu.create=(e,t)=>new hu({value:e,typeName:Iu.ZodLiteral,...fl(t)});class mu extends vl{constructor(){super(...arguments),hl.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),i=this._def.values;return Xd(t,{expected:Vd.joinValues(i),received:t.parsedType,code:Kd.invalid_type}),tl}if(cl(this,hl,"f")||dl(this,hl,new Set(this._def.values),"f"),!cl(this,hl,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return Xd(t,{received:t.data,code:Kd.invalid_enum_value,options:i}),tl}return nl(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return mu.create(e,{...this._def,...t})}exclude(e,t=this._def){return mu.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}hl=new WeakMap,mu.create=pu;class gu extends vl{constructor(){super(...arguments),pl.set(this,void 0)}_parse(e){const t=Vd.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==Hd.string&&i.parsedType!==Hd.number){const e=Vd.objectValues(t);return Xd(i,{expected:Vd.joinValues(e),received:i.parsedType,code:Kd.invalid_type}),tl}if(cl(this,pl,"f")||dl(this,pl,new Set(Vd.getValidEnumValues(this._def.values)),"f"),!cl(this,pl,"f").has(e.data)){const e=Vd.objectValues(t);return Xd(i,{received:i.data,code:Kd.invalid_enum_value,options:e}),tl}return nl(e.data)}get enum(){return this._def.values}}pl=new WeakMap,gu.create=(e,t)=>new gu({values:e,typeName:Iu.ZodNativeEnum,...fl(t)});class fu extends vl{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Hd.promise&&!1===t.common.async)return Xd(t,{code:Kd.invalid_type,expected:Hd.promise,received:t.parsedType}),tl;const i=t.parsedType===Hd.promise?t.data:Promise.resolve(t.data);return nl(i.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}fu.create=(e,t)=>new fu({type:e,typeName:Iu.ZodPromise,...fl(t)});class vu extends vl{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Iu.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{Xd(i,e),e.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(i.data,s);if(i.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return tl;const n=await this._def.schema._parseAsync({data:e,path:i.path,parent:i});return"aborted"===n.status?tl:"dirty"===n.status||"dirty"===t.value?il(n.value):n}));{if("aborted"===t.value)return tl;const n=this._def.schema._parseSync({data:e,path:i.path,parent:i});return"aborted"===n.status?tl:"dirty"===n.status||"dirty"===t.value?il(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(i.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===i.common.async){const n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?tl:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((i=>"aborted"===i.status?tl:("dirty"===i.status&&t.dirty(),e(i.value).then((()=>({status:t.value,value:i.value}))))))}if("transform"===n.type){if(!1===i.common.async){const e=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ol(e))return e;const r=n.transform(e.value,s);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((e=>ol(e)?Promise.resolve(n.transform(e.value,s)).then((e=>({status:t.value,value:e}))):e))}Vd.assertNever(n)}}vu.create=(e,t,i)=>new vu({schema:e,typeName:Iu.ZodEffects,effect:t,...fl(i)}),vu.createWithPreprocess=(e,t,i)=>new vu({schema:t,effect:{type:"preprocess",transform:e},typeName:Iu.ZodEffects,...fl(i)});class yu extends vl{_parse(e){return this._getType(e)===Hd.undefined?nl(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}yu.create=(e,t)=>new yu({innerType:e,typeName:Iu.ZodOptional,...fl(t)});class bu extends vl{_parse(e){return this._getType(e)===Hd.null?nl(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}bu.create=(e,t)=>new bu({innerType:e,typeName:Iu.ZodNullable,...fl(t)});class ku extends vl{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===Hd.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ku.create=(e,t)=>new ku({innerType:e,typeName:Iu.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...fl(t)});class Tu extends vl{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return al(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Gd(i.common.issues)},input:i.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new Gd(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Tu.create=(e,t)=>new Tu({innerType:e,typeName:Iu.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...fl(t)});class Su extends vl{_parse(e){if(this._getType(e)!==Hd.nan){const t=this._getOrReturnCtx(e);return Xd(t,{code:Kd.invalid_type,expected:Hd.nan,received:t.parsedType}),tl}return{status:"valid",value:e.data}}}Su.create=e=>new Su({typeName:Iu.ZodNaN,...fl(e)});const Cu=Symbol("zod_brand");class wu extends vl{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Eu extends vl{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?tl:"dirty"===e.status?(t.dirty(),il(e.value)):this._def.out._parseAsync({data:e.value,path:i.path,parent:i})})();{const e=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?tl:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:i.path,parent:i})}}static create(e,t){return new Eu({in:e,out:t,typeName:Iu.ZodPipeline})}}class _u extends vl{_parse(e){const t=this._def.innerType._parse(e),i=e=>(ol(e)&&(e.value=Object.freeze(e.value)),e);return al(t)?t.then((e=>i(e))):i(t)}unwrap(){return this._def.innerType}}function Pu(e,t){const i="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof i?{message:i}:i}function Ru(e,t={},i){return e?Gl.create().superRefine(((n,s)=>{var r,o;const a=e(n);if(a instanceof Promise)return a.then((e=>{var r,o;if(!e){const e=Pu(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}}));if(!a){const e=Pu(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}})):Gl.create()}_u.create=(e,t)=>new _u({innerType:e,typeName:Iu.ZodReadonly,...fl(t)});const xu={object:eu.lazycreate};var Iu,Ou;(Ou=Iu||(Iu={})).ZodString="ZodString",Ou.ZodNumber="ZodNumber",Ou.ZodNaN="ZodNaN",Ou.ZodBigInt="ZodBigInt",Ou.ZodBoolean="ZodBoolean",Ou.ZodDate="ZodDate",Ou.ZodSymbol="ZodSymbol",Ou.ZodUndefined="ZodUndefined",Ou.ZodNull="ZodNull",Ou.ZodAny="ZodAny",Ou.ZodUnknown="ZodUnknown",Ou.ZodNever="ZodNever",Ou.ZodVoid="ZodVoid",Ou.ZodArray="ZodArray",Ou.ZodObject="ZodObject",Ou.ZodUnion="ZodUnion",Ou.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ou.ZodIntersection="ZodIntersection",Ou.ZodTuple="ZodTuple",Ou.ZodRecord="ZodRecord",Ou.ZodMap="ZodMap",Ou.ZodSet="ZodSet",Ou.ZodFunction="ZodFunction",Ou.ZodLazy="ZodLazy",Ou.ZodLiteral="ZodLiteral",Ou.ZodEnum="ZodEnum",Ou.ZodEffects="ZodEffects",Ou.ZodNativeEnum="ZodNativeEnum",Ou.ZodOptional="ZodOptional",Ou.ZodNullable="ZodNullable",Ou.ZodDefault="ZodDefault",Ou.ZodCatch="ZodCatch",Ou.ZodPromise="ZodPromise",Ou.ZodBranded="ZodBranded",Ou.ZodPipeline="ZodPipeline",Ou.ZodReadonly="ZodReadonly";const Au=Fl.create,Nu=Bl.create,Du=Su.create,Mu=Vl.create,Lu=ql.create,Uu=Zl.create,ju=Hl.create,Fu=zl.create,$u=Kl.create,Bu=Gl.create,Vu=Wl.create,qu=Jl.create,Zu=Ql.create,Hu=Yl.create,zu=eu.create,Ku=eu.strictCreate,Gu=tu.create,Wu=nu.create,Ju=ru.create,Qu=ou.create,Yu=au.create,Xu=cu.create,eh=du.create,th=lu.create,ih=uu.create,nh=hu.create,sh=mu.create,rh=gu.create,oh=fu.create,ah=vu.create,ch=yu.create,dh=bu.create,lh=vu.createWithPreprocess,uh=Eu.create,hh={string:e=>Fl.create({...e,coerce:!0}),number:e=>Bl.create({...e,coerce:!0}),boolean:e=>ql.create({...e,coerce:!0}),bigint:e=>Vl.create({...e,coerce:!0}),date:e=>Zl.create({...e,coerce:!0})},ph=tl;var mh=Object.freeze({__proto__:null,defaultErrorMap:Wd,setErrorMap:function(e){Jd=e},getErrorMap:Qd,makeIssue:Yd,EMPTY_PATH:[],addIssueToContext:Xd,ParseStatus:el,INVALID:tl,DIRTY:il,OK:nl,isAborted:sl,isDirty:rl,isValid:ol,isAsync:al,get util(){return Vd},get objectUtil(){return Zd},ZodParsedType:Hd,getParsedType:zd,ZodType:vl,datetimeRegex:Ll,ZodString:Fl,ZodNumber:Bl,ZodBigInt:Vl,ZodBoolean:ql,ZodDate:Zl,ZodSymbol:Hl,ZodUndefined:zl,ZodNull:Kl,ZodAny:Gl,ZodUnknown:Wl,ZodNever:Jl,ZodVoid:Ql,ZodArray:Yl,ZodObject:eu,ZodUnion:tu,ZodDiscriminatedUnion:nu,ZodIntersection:ru,ZodTuple:ou,ZodRecord:au,ZodMap:cu,ZodSet:du,ZodFunction:lu,ZodLazy:uu,ZodLiteral:hu,ZodEnum:mu,ZodNativeEnum:gu,ZodPromise:fu,ZodEffects:vu,ZodTransformer:vu,ZodOptional:yu,ZodNullable:bu,ZodDefault:ku,ZodCatch:Tu,ZodNaN:Su,BRAND:Cu,ZodBranded:wu,ZodPipeline:Eu,ZodReadonly:_u,custom:Ru,Schema:vl,ZodSchema:vl,late:xu,get ZodFirstPartyTypeKind(){return Iu},coerce:hh,any:Bu,array:Hu,bigint:Mu,boolean:Lu,date:Uu,discriminatedUnion:Wu,effect:ah,enum:sh,function:th,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ru((t=>t instanceof e),t),intersection:Ju,lazy:ih,literal:nh,map:Xu,nan:Du,nativeEnum:rh,never:qu,null:$u,nullable:dh,number:Nu,object:zu,oboolean:()=>Lu().optional(),onumber:()=>Nu().optional(),optional:ch,ostring:()=>Au().optional(),pipeline:uh,preprocess:lh,promise:oh,record:Yu,set:eh,strictObject:Ku,string:Au,symbol:ju,transformer:ah,tuple:Qu,undefined:Fu,union:Gu,unknown:Vu,void:Zu,NEVER:ph,ZodIssueCode:Kd,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:Gd});mh.object({apiKey:mh.string().optional(),enableVoice:mh.boolean().default(!0),enableScreenCapture:mh.boolean().default(!0),debug:mh.boolean().default(!1),user:mh.object({id:mh.string(),email:mh.string().optional(),metadata:mh.any().optional()}).optional()});var gh=(e=>(e.READY="ready",e.ERROR="error",e.VOICE_START="voice:start",e.VOICE_STOP="voice:stop",e.SCREEN_CAPTURE_START="screen:start",e.SCREEN_CAPTURE_STOP="screen:stop",e.STATE_CHANGE="state:change",e))(gh||{}),fh=(e=>(e.READY="ready",e.ERROR="error",e.PAUSED="paused",e.LOADING="loading",e.THINKING="thinking",e.RESEARCHING="researching",e.AGENT_SPEAKING="agent_speaking",e.USER_SPEAKING="user_speaking",e.AWAITING_USER_INPUT="awaiting_user_input",e))(fh||{});class vh{constructor({sessionId:e}){this.currentState=fh.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=new Ye.EventEmitter,this.sessionId=e}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(ho.LocalTrackUnpublished,(e=>{e.source===$o.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(ho.Disconnected,(()=>{console.log("Room disconnected"),this.disconnect()})),this.room.on(ho.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(ho.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===$o.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(ho.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===fh.RESEARCHING||this.currentState===fh.PAUSED)return;const t=Ge(e["lk.agent.state"]).with("listening",(()=>fh.USER_SPEAKING)).with("speaking",(()=>fh.AGENT_SPEAKING)).with("thinking",(()=>fh.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(ho.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));Ge(t.status||t.request).with("using_tool",(()=>{this.currentState=fh.RESEARCHING,this.emitter.emit("stateChanged",{newState:this.currentState})})).with("using_tool_ended",(()=>{this.currentState=fh.AGENT_SPEAKING,this.emitter.emit("stateChanged",{newState:this.currentState})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}})))}async connect(){if(!this.sessionId)return console.error("No session ID found"),void this.emitter.emit("error",{error:new Error("No session ID provided")});await this.requestMicrophone();try{this.room=new Fd({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=`${Bd}/join-token?token=${this.sessionId}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:$o.Source.Microphone})}return{url:t.url,token:t.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",{error:e instanceof Error?e:new Error(String(e))}),e}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(fh.READY)}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",{newState:e}))}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(fh.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(fh.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===fh.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===fh.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to room")}async reconnect(e,t,i){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",{error:new Error("Missing room URL or token for reconnection")}),!1;if(await this.requestMicrophone(),this.room=new Fd({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:$o.Source.Microphone})}return this.setState(i),i===fh.PAUSED&&this.pauseRecording(),!0}catch(n){return console.error("Failed to reconnect to room:",n),this.disconnect(),this.emitter.emit("error",{error:n instanceof Error?n:new Error(String(n))}),!1}}}const yh="session_data",bh=new class{constructor(e){this.namespace=e}getItem(e){return localStorage.getItem(`${this.namespace}.${e}`)}setItem(e,t){localStorage.setItem(`${this.namespace}.${e}`,t)}removeItem(e){localStorage.removeItem(`${this.namespace}.${e}`)}clear(){for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);t&&t.startsWith(`${this.namespace}.`)&&localStorage.removeItem(t)}}}("io.obi.widget");var kh=Object.defineProperty,Th=Object.getOwnPropertyDescriptor,Sh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Th(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&kh(t,i,r),r};class Ch extends ae{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return q`
2
2
  <button
3
3
  id="obi-nav-${this.id}"
4
4
  class=${this.isSpecial?"special":""}
@@ -8,7 +8,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
8
8
  >
9
9
  <slot></slot>
10
10
  </button>
11
- `}}An.styles=a`
11
+ `}}Ch.styles=o`
12
12
  :host {
13
13
  display: block;
14
14
  }
@@ -60,7 +60,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
60
60
  width: 18px;
61
61
  height: 18px;
62
62
  }
63
- `,On([ue({type:String})],An.prototype,"id",2),On([ue({type:Boolean})],An.prototype,"isActive",2),On([ue({type:Boolean})],An.prototype,"isSpecial",2),On([ue({type:Function})],An.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",An);const Nn=e=>q`
63
+ `,Sh([ue({type:String})],Ch.prototype,"id",2),Sh([ue({type:Boolean})],Ch.prototype,"isActive",2),Sh([ue({type:Boolean})],Ch.prototype,"isSpecial",2),Sh([ue({type:Function})],Ch.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",Ch);const wh=e=>q`
64
64
  <svg
65
65
  xmlns="http://www.w3.org/2000/svg"
66
66
  width="24"
@@ -76,31 +76,31 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
76
76
  >
77
77
  ${e}
78
78
  </svg>
79
- `,Dn=Nn(Z`
79
+ `,Eh=wh(Z`
80
80
  <rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>
81
- `),Mn=Nn(Z`<polygon points="6 3 20 12 6 21 6 3"/>`),Ln=Nn(Z`
81
+ `),_h=wh(Z`<polygon points="6 3 20 12 6 21 6 3"/>`),Ph=wh(Z`
82
82
  <path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>
83
- `),Un=Nn(Z`
83
+ `),Rh=wh(Z`
84
84
  <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
85
- `),jn=Nn(Z`
85
+ `),xh=wh(Z`
86
86
  <path d="M12 7v14" />
87
87
  <path
88
88
  d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
89
89
  />
90
- `),Fn=q`
90
+ `),Ih=q`
91
91
  <img
92
92
  class="widget-icon"
93
93
  src="data:image/svg+xml;base64,${btoa('<?xml version="1.0" encoding="UTF-8"?>\n <svg width="32" height="32" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">\n <g id="obi-icon">\n <g id="Subtract">\n <path d="M15.5845 9.29177L8.20527 5.00637L8.20527 13.4502L15.5845 17.7356L15.5845 9.29177Z" fill="white" />\n <path d="M15.5896 27.7146L8.21035 31.9994L8.21032 23.4698L15.5896 19.1843L15.5896 27.7146Z" fill="white" />\n <path d="M16.4104 27.7146L16.4104 19.1786L23.7897 23.4641L23.7897 32L16.4104 27.7146Z" fill="white" />\n <path d="M32 27.7142L24.6207 31.9996L24.6207 23.47L32 19.1846L32 27.7142Z" fill="white" />\n <path d="M24.2048 22.748L31.5911 18.4585L24.2845 14.2154L16.8983 18.5048L24.2048 22.748Z" fill="white" />\n <path d="M23.7948 5.01235L23.7948 13.4564L16.4156 17.7418L16.4156 9.29775L23.7948 5.01235Z" fill="white" />\n <path d="M16.0052 0L23.3865 4.2866L16.0003 8.57606L8.61897 4.28946L16.0052 0Z" fill="white" />\n <path d="M7.72042 14.2182L15.1017 18.5048L7.79445 22.7477L0.413699 18.4615L7.72042 14.2182Z" fill="white" />\n <path d="M7.37926 31.9997L7.37926 23.4638L0 19.1784L3.79636e-05 27.7143L7.37926 31.9997Z" fill="white" />\n </g>\n </g>\n </svg>')}"
94
94
  alt="Obi Icon"
95
95
  />
96
- `;var Bn=Object.defineProperty,$n=Object.getOwnPropertyDescriptor,Vn=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?$n(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Bn(t,i,r),r};class qn extends oe{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=Rn.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return q`
96
+ `;var Oh=Object.defineProperty,Ah=Object.getOwnPropertyDescriptor,Nh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Ah(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Oh(t,i,r),r};class Dh extends ae{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=fh.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return q`
97
97
  ${this.isActive?q`
98
98
  <obi-nav-icon
99
99
  id="pause"
100
- ?isActive=${this.currentState===Rn.PAUSED}
101
- @click=${()=>this.handleIconClick("pause",this.currentState!==Rn.PAUSED)}
100
+ ?isActive=${this.currentState===fh.PAUSED}
101
+ @click=${()=>this.handleIconClick("pause",this.currentState!==fh.PAUSED)}
102
102
  >
103
- ${this.currentState===Rn.PAUSED?Mn:Dn}
103
+ ${this.currentState===fh.PAUSED?_h:Eh}
104
104
  </obi-nav-icon>
105
105
  <obi-nav-icon
106
106
  id="activate"
@@ -108,17 +108,17 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
108
108
  ?isSpecial=${!0}
109
109
  @click=${()=>this.handleIconClick("activate",!this.isActive)}
110
110
  >
111
- ${this.isActive?Un:Ln}
111
+ ${this.isActive?Rh:Ph}
112
112
  </obi-nav-icon>
113
113
  `:q`
114
114
  <obi-nav-icon
115
115
  id="experiences"
116
116
  @click=${()=>this.handleIconClick("experiences",!0)}
117
117
  >
118
- ${jn}
118
+ ${xh}
119
119
  </obi-nav-icon>
120
120
  `}
121
- `}}qn.styles=a`
121
+ `}}Dh.styles=o`
122
122
  :host {
123
123
  display: flex;
124
124
  position: absolute;
@@ -142,13 +142,13 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
142
142
  bottom: auto;
143
143
  flex-direction: column;
144
144
  }
145
- `,Vn([ue({type:Boolean})],qn.prototype,"isActive",2),Vn([ue({type:Boolean})],qn.prototype,"isScreenActive",2),Vn([ue({type:Object})],qn.prototype,"position",2),Vn([ue({type:String})],qn.prototype,"currentState",2),Vn([ue({type:String})],qn.prototype,"direction",2),Vn([ue({type:Function})],qn.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",qn);var Zn=Object.defineProperty,Kn=Object.getOwnPropertyDescriptor,zn=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Kn(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Zn(t,i,r),r};class Hn extends oe{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return q`
145
+ `,Nh([ue({type:Boolean})],Dh.prototype,"isActive",2),Nh([ue({type:Boolean})],Dh.prototype,"isScreenActive",2),Nh([ue({type:Object})],Dh.prototype,"position",2),Nh([ue({type:String})],Dh.prototype,"currentState",2),Nh([ue({type:String})],Dh.prototype,"direction",2),Nh([ue({type:Function})],Dh.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",Dh);var Mh=Object.defineProperty,Lh=Object.getOwnPropertyDescriptor,Uh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Lh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Mh(t,i,r),r};class jh extends ae{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return q`
146
146
  <div class="course-container" @click=${this.handleClick}>
147
147
  <img src=${this.imageSrc} alt="Course Preview" class="course-image" />
148
148
  <h2 class="course-title">${this.name}</h2>
149
149
  ${this.description?q`<p class="course-description">${this.description}</p>`:""}
150
150
  </div>
151
- `}}Hn.styles=a`
151
+ `}}jh.styles=o`
152
152
  :host {
153
153
  display: block;
154
154
  }
@@ -193,7 +193,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
193
193
  color: #71717a;
194
194
  margin: 0;
195
195
  }
196
- `,zn([ue({type:String})],Hn.prototype,"id",2),zn([ue({type:String})],Hn.prototype,"name",2),zn([ue({type:String})],Hn.prototype,"description",2),zn([ue({type:String})],Hn.prototype,"imageSrc",2),zn([ue({type:Function})],Hn.prototype,"onSelect",2);class Gn extends oe{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return q`<div class="loading">Loading...</div>`;if(this.error)return q`<div class="error">${this.error}</div>`;if(!this.courses||0===this.courses.length)return q`<div class="empty">No courses available</div>`;const e=1===this.courses.length?"grid-cols-1":2===this.courses.length?"grid-cols-2":"grid-cols-3";return q`
196
+ `,Uh([ue({type:String})],jh.prototype,"id",2),Uh([ue({type:String})],jh.prototype,"name",2),Uh([ue({type:String})],jh.prototype,"description",2),Uh([ue({type:String})],jh.prototype,"imageSrc",2),Uh([ue({type:Function})],jh.prototype,"onSelect",2);class Fh extends ae{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return q`<div class="loading">Loading...</div>`;if(this.error)return q`<div class="error">${this.error}</div>`;if(!this.courses||0===this.courses.length)return q`<div class="empty">No courses available</div>`;const e=1===this.courses.length?"grid-cols-1":2===this.courses.length?"grid-cols-2":"grid-cols-3";return q`
197
197
  <div class="course-grid ${e}">
198
198
  ${this.courses.map((e=>q`
199
199
  <obi-course
@@ -205,7 +205,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
205
205
  ></obi-course>
206
206
  `))}
207
207
  </div>
208
- `}}Gn.styles=a`
208
+ `}}Fh.styles=o`
209
209
  :host {
210
210
  display: block;
211
211
  }
@@ -240,7 +240,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
240
240
  .error {
241
241
  color: #ef4444;
242
242
  }
243
- `,zn([ue({type:Array})],Gn.prototype,"courses",2),zn([ue({type:Boolean})],Gn.prototype,"loading",2),zn([ue({type:String})],Gn.prototype,"error",2),zn([ue({type:Function})],Gn.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",Hn),customElements.get("obi-course-list")||customElements.define("obi-course-list",Gn);var Wn=Object.defineProperty,Jn=Object.getOwnPropertyDescriptor,Qn=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Jn(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Wn(t,i,r),r};class Yn extends oe{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const e=await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`),t=(await e.json()).map((e=>({id:e.uuid,name:e.onboarding_plan.name,description:e.onboarding_plan.description,imageSrc:e.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"}))).filter((e=>!!e.name));this.courses=[...t],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig?.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=En,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return q`
243
+ `,Uh([ue({type:Array})],Fh.prototype,"courses",2),Uh([ue({type:Boolean})],Fh.prototype,"loading",2),Uh([ue({type:String})],Fh.prototype,"error",2),Uh([ue({type:Function})],Fh.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",jh),customElements.get("obi-course-list")||customElements.define("obi-course-list",Fh);var $h=Object.defineProperty,Bh=Object.getOwnPropertyDescriptor,Vh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Bh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&$h(t,i,r),r};class qh extends ae{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiKey="",this.apiBaseUrl=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const e=await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`),t=(await e.json()).map((e=>({id:e.uuid,name:e.onboarding_plan.name,description:e.onboarding_plan.description,imageSrc:e.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"}))).filter((e=>!!e.name));this.courses=[...t],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig?.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=Bd,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return q`
244
244
  <div class="backdrop" @click=${this.handleClose}></div>
245
245
  <div class="container">
246
246
  <button class="close-button" @click=${this.handleClose}>×</button>
@@ -256,7 +256,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
256
256
  @course-select=${this.handleCourseSelect}
257
257
  ></obi-course-list>
258
258
  </div>
259
- `}}Yn.styles=a`
259
+ `}}qh.styles=o`
260
260
  :host {
261
261
  display: block;
262
262
  font-family: "Syne", sans-serif;
@@ -339,7 +339,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
339
339
  font-size: 24px;
340
340
  color: #6b7280;
341
341
  }
342
- `,Qn([ue({type:Array})],Yn.prototype,"courses",2),Qn([ue({type:Boolean})],Yn.prototype,"loading",2),Qn([ue({type:String})],Yn.prototype,"error",2),Qn([ue({type:String})],Yn.prototype,"apiBaseUrl",2),Qn([ue({type:String})],Yn.prototype,"apiKey",2),Qn([ue({type:Function})],Yn.prototype,"onCourseSelect",2),Qn([ue({type:Function})],Yn.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",Yn);class Xn{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}const es=(e,t)=>{const i=e._$AN;if(void 0===i)return!1;for(const n of i)n._$AO?.(t,!1),es(n,t);return!0},ts=e=>{let t,i;do{if(void 0===(t=e._$AM))break;i=t._$AN,i.delete(e),e=t}while(0===i?.size)},is=e=>{for(let t;t=e._$AM;e=t){let i=t._$AN;if(void 0===i)t._$AN=i=new Set;else if(i.has(e))break;i.add(e),rs(t)}};function ns(e){void 0!==this._$AN?(ts(this),this._$AM=e,is(this)):this._$AM=e}function ss(e,t=!1,i=0){const n=this._$AH,s=this._$AN;if(void 0!==s&&0!==s.size)if(t)if(Array.isArray(n))for(let r=i;r<n.length;r++)es(n[r],!1),ts(n[r]);else null!=n&&(es(n,!1),ts(n));else es(this,e)}const rs=e=>{2==e.type&&(e._$AP??(e._$AP=ss),e._$AQ??(e._$AQ=ns))};class as extends Xn{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),is(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(es(this,e),ts(this))}setValue(e){if(void 0===this._$Ct.strings)this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}let os=class{};const cs=new WeakMap,ds=(ls=class extends as{render(e){return z}update(e,[t]){const i=t!==this.G;return i&&void 0!==this.G&&this.rt(void 0),(i||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),z}rt(e){if(this.isConnected||(e=void 0),"function"==typeof this.G){const t=this.ht??globalThis;let i=cs.get(t);void 0===i&&(i=new WeakMap,cs.set(t,i)),void 0!==i.get(this.G)&&this.G.call(this.ht,void 0),i.set(this.G,e),void 0!==e&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return"function"==typeof this.G?cs.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}},(...e)=>({_$litDirective$:ls,values:e}));var ls,us=Object.defineProperty,hs=Object.getOwnPropertyDescriptor,ps=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?hs(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&us(t,i,r),r};class ms extends oe{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=new os,this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,n=e.clientWidth,s=e.clientHeight;e.width=n*i,e.height=s*i,t.scale(i,i),t.clearRect(0,0,n,s);const r=Math.max(1,(n-3*(this.barCount-1))/this.barCount),a=s/2,o=(this.volume.speaker,this.volume.volume),c=(this.volume.speaker,this.volume.spectrum);if(0===o)return;let d=[];if(c&&c.length>0){const e=c.length,t=Math.ceil(e/10);let i=[];for(let d=0;d<10;d++){const n=d*t,s=Math.min((d+1)*t,e);let r=0;for(let e=n;e<s;e++)r+=c[e]||0;i.push({region:d,startIdx:n,endIdx:s,energy:r})}i.sort(((e,t)=>t.energy-e.energy));const n=i.slice(0,3),s=Math.min(...n.map((e=>e.startIdx))),r=Math.max(...n.map((e=>e.endIdx)));if(r>s)for(let l=0;l<this.barCount;l++){const t=s+l/(this.barCount-1)*(r-s),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}else for(let l=0;l<this.barCount;l++){const t=l/(this.barCount-1)*(e/2),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}const a=Math.max(...d,1),o="USER"===this.volume.speaker?.7:.6;d=d.map(((e,t)=>{const i=e/a,n=o+t/(this.barCount-1)*.3;return Math.min(1,i*n)}))}else if("USER"!==this.volume.speaker)for(let l=0;l<this.barCount;l++){const e=.002*Date.now(),t=.3+.2*Math.sin(e+.7*l);d[l]=t}for(let l=0;l<this.barCount;l++){const e=d.length>0&&void 0!==d[l]?d[l]:o;"USER"===this.volume.speaker?t.fillStyle=`rgba(109, 40, 217, ${.5*e+.5})`:t.fillStyle=`rgba(255, 255, 255, ${.5*e+.5})`;const i=Math.max(2,.8*e*a),c=n-(this.barCount-l)*(r+3),u=r/2;t.beginPath(),t.moveTo(c+u,s/2-i),t.lineTo(c+r-u,s/2-i),t.quadraticCurveTo(c+r,s/2-i,c+r,s/2-i+u),t.lineTo(c+r,s/2),t.lineTo(c,s/2),t.lineTo(c,s/2-i+u),t.quadraticCurveTo(c,s/2-i,c+u,s/2-i),t.fill(),t.beginPath(),t.moveTo(c,s/2),t.lineTo(c+r,s/2),t.lineTo(c+r,s/2+i-u),t.quadraticCurveTo(c+r,s/2+i,c+r-u,s/2+i),t.lineTo(c+u,s/2+i),t.quadraticCurveTo(c,s/2+i,c,s/2+i-u),t.lineTo(c,s/2),t.fill()}}render(){return q` <canvas ${ds(this.canvasRef)} width="52" height="52"></canvas> `}}ms.styles=a`
342
+ `,Vh([ue({type:Array})],qh.prototype,"courses",2),Vh([ue({type:Boolean})],qh.prototype,"loading",2),Vh([ue({type:String})],qh.prototype,"error",2),Vh([ue({type:String})],qh.prototype,"apiKey",2),Vh([ue({type:Function})],qh.prototype,"onCourseSelect",2),Vh([ue({type:Function})],qh.prototype,"onClose",2),Vh([he()],qh.prototype,"apiBaseUrl",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",qh);class Zh{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}const Hh=(e,t)=>{const i=e._$AN;if(void 0===i)return!1;for(const n of i)n._$AO?.(t,!1),Hh(n,t);return!0},zh=e=>{let t,i;do{if(void 0===(t=e._$AM))break;i=t._$AN,i.delete(e),e=t}while(0===i?.size)},Kh=e=>{for(let t;t=e._$AM;e=t){let i=t._$AN;if(void 0===i)t._$AN=i=new Set;else if(i.has(e))break;i.add(e),Jh(t)}};function Gh(e){void 0!==this._$AN?(zh(this),this._$AM=e,Kh(this)):this._$AM=e}function Wh(e,t=!1,i=0){const n=this._$AH,s=this._$AN;if(void 0!==s&&0!==s.size)if(t)if(Array.isArray(n))for(let r=i;r<n.length;r++)Hh(n[r],!1),zh(n[r]);else null!=n&&(Hh(n,!1),zh(n));else Hh(this,e)}const Jh=e=>{2==e.type&&(e._$AP??(e._$AP=Wh),e._$AQ??(e._$AQ=Gh))};class Qh extends Zh{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Kh(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Hh(this,e),zh(this))}setValue(e){if(void 0===this._$Ct.strings)this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}class Yh{}const Xh=new WeakMap,ep=(tp=class extends Qh{render(e){return z}update(e,[t]){const i=t!==this.G;return i&&void 0!==this.G&&this.rt(void 0),(i||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),z}rt(e){if(this.isConnected||(e=void 0),"function"==typeof this.G){const t=this.ht??globalThis;let i=Xh.get(t);void 0===i&&(i=new WeakMap,Xh.set(t,i)),void 0!==i.get(this.G)&&this.G.call(this.ht,void 0),i.set(this.G,e),void 0!==e&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return"function"==typeof this.G?Xh.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}},(...e)=>({_$litDirective$:tp,values:e}));var tp,ip=Object.defineProperty,np=Object.getOwnPropertyDescriptor,sp=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?np(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&ip(t,i,r),r};class rp extends ae{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=new Yh,this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,n=e.clientWidth,s=e.clientHeight;e.width=n*i,e.height=s*i,t.scale(i,i),t.clearRect(0,0,n,s);const r=Math.max(1,(n-3*(this.barCount-1))/this.barCount),o=s/2,a=(this.volume.speaker,this.volume.volume),c=(this.volume.speaker,this.volume.spectrum);if(0===a)return;let d=[];if(c&&c.length>0){const e=c.length,t=Math.ceil(e/10);let i=[];for(let d=0;d<10;d++){const n=d*t,s=Math.min((d+1)*t,e);let r=0;for(let e=n;e<s;e++)r+=c[e]||0;i.push({region:d,startIdx:n,endIdx:s,energy:r})}i.sort(((e,t)=>t.energy-e.energy));const n=i.slice(0,3),s=Math.min(...n.map((e=>e.startIdx))),r=Math.max(...n.map((e=>e.endIdx)));if(r>s)for(let l=0;l<this.barCount;l++){const t=s+l/(this.barCount-1)*(r-s),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}else for(let l=0;l<this.barCount;l++){const t=l/(this.barCount-1)*(e/2),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}const o=Math.max(...d,1),a="USER"===this.volume.speaker?.7:.6;d=d.map(((e,t)=>{const i=e/o,n=a+t/(this.barCount-1)*.3;return Math.min(1,i*n)}))}else if("USER"!==this.volume.speaker)for(let l=0;l<this.barCount;l++){const e=.002*Date.now(),t=.3+.2*Math.sin(e+.7*l);d[l]=t}for(let l=0;l<this.barCount;l++){const e=d.length>0&&void 0!==d[l]?d[l]:a;"USER"===this.volume.speaker?t.fillStyle=`rgba(109, 40, 217, ${.5*e+.5})`:t.fillStyle=`rgba(255, 255, 255, ${.5*e+.5})`;const i=Math.max(2,.8*e*o),c=n-(this.barCount-l)*(r+3),u=r/2;t.beginPath(),t.moveTo(c+u,s/2-i),t.lineTo(c+r-u,s/2-i),t.quadraticCurveTo(c+r,s/2-i,c+r,s/2-i+u),t.lineTo(c+r,s/2),t.lineTo(c,s/2),t.lineTo(c,s/2-i+u),t.quadraticCurveTo(c,s/2-i,c+u,s/2-i),t.fill(),t.beginPath(),t.moveTo(c,s/2),t.lineTo(c+r,s/2),t.lineTo(c+r,s/2+i-u),t.quadraticCurveTo(c+r,s/2+i,c+r-u,s/2+i),t.lineTo(c+u,s/2+i),t.quadraticCurveTo(c,s/2+i,c,s/2+i-u),t.lineTo(c,s/2),t.fill()}}render(){return q` <canvas ${ep(this.canvasRef)} width="52" height="52"></canvas> `}}rp.styles=o`
343
343
  :host {
344
344
  display: block;
345
345
  width: 40px;
@@ -351,7 +351,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
351
351
  width: 100%;
352
352
  height: 100%;
353
353
  }
354
- `,ps([ue({type:Object})],ms.prototype,"volume",2),ps([he()],ms.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",ms);var gs=Object.defineProperty;Object.getOwnPropertyDescriptor;class fs extends oe{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach((e=>window.clearTimeout(e))),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const e=t*(this.animationDuration*this.overlapFactor),i=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const e=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1}),this.animationDuration);this.timeoutIds.push(e)}),e);this.timeoutIds.push(i)}const e=window.setTimeout((()=>{this.animateSequence()}),this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return q`
354
+ `,sp([ue({type:Object})],rp.prototype,"volume",2),sp([he()],rp.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",rp);var op=Object.defineProperty;Object.getOwnPropertyDescriptor;class ap extends ae{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach((e=>window.clearTimeout(e))),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const e=t*(this.animationDuration*this.overlapFactor),i=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const e=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1}),this.animationDuration);this.timeoutIds.push(e)}),e);this.timeoutIds.push(i)}const e=window.setTimeout((()=>{this.animateSequence()}),this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return q`
355
355
  <div class="dot-loader">
356
356
  ${this.activeDots.map((e=>q`
357
357
  <div
@@ -360,7 +360,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
360
360
  ></div>
361
361
  `))}
362
362
  </div>
363
- `}}fs.styles=a`
363
+ `}}ap.styles=o`
364
364
  :host {
365
365
  display: block;
366
366
  }
@@ -387,10 +387,10 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
387
387
  transition: transform 0.2s ease-in-out;
388
388
  opacity: 1;
389
389
  }
390
- `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&gs(t,i,s)})([he()],fs.prototype,"activeDots"),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",fs);class vs extends oe{render(){return q`
390
+ `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&op(t,i,s)})([he()],ap.prototype,"activeDots"),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",ap);class cp extends ae{render(){return q`
391
391
  <obi-dot-loader loading style="margin-left: 2px"></obi-dot-loader>
392
392
  <span class="text">Searching the knowledge base</span>
393
- `}}vs.styles=a`
393
+ `}}cp.styles=o`
394
394
  :host {
395
395
  display: flex;
396
396
  align-items: center;
@@ -405,16 +405,16 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
405
405
  font-weight: 500;
406
406
  font-size: 14px;
407
407
  }
408
- `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",vs);var ys=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,ks=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?bs(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&ys(t,i,r),r};class Ts extends oe{constructor(){super(),this.apiBaseUrl=En,this.apiKey="",this.position="bottom-right",this.user=null,this.state=Rn.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}handleItemSelect(e,t){"experiences"!==e?Ge([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.activeSession?.disconnect()})).otherwise((()=>{})):this.showCourseModal=!0}async handleSessionStart(e){this.showCourseModal=!1,this.state=Rn.LOADING;try{const{ObiSession:t}=await Promise.resolve().then((()=>lp)),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",(e=>{this.state=e.newState})),i.on("volume",(e=>{this.volume=e})),i.on("error",(e=>{console.error("Session error:",e.error),this.state=Rn.ERROR,this.activeSession=null})),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=Rn.ERROR}}render(){const e=Ge(this.state).with(Rn.LOADING,(()=>q`<obi-dot-loader></obi-dot-loader>`)).with(Rn.RESEARCHING,(()=>q`<obi-searching-loader></obi-searching-loader>`)).with(Ke.union(Rn.USER_SPEAKING,Rn.AGENT_SPEAKING),(()=>q`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Rn.PAUSED,(()=>Fn)).otherwise((()=>Fn));return q`
408
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",cp);var dp=Object.defineProperty,lp=Object.getOwnPropertyDescriptor,up=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?lp(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&dp(t,i,r),r};class hp extends ae{constructor(){super(),this.apiKey="",this.isActive=!0,this.position="bottom-right",this.user=null,this.state=fh.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.closeNavTimeoutRef=null,this.updateFromConfig();const e=()=>{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}updateFromConfig(){window.obiWidgetConfig&&(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,this.position=window.obiWidgetConfig.position||this.position,this.user=window.obiWidgetConfig.user||this.user,void 0!==window.obiWidgetConfig.isActive&&(this.isActive=window.obiWidgetConfig.isActive))}async connectObi(e){if(this.activeSession)console.log("Connection already exists");else try{const t=new vh({sessionId:e});if(!t)return console.error("Failed to create session"),this.state=fh.ERROR,void(this.activeSession=null);t.on("stateChanged",(e=>{this.state=e.newState,e.newState!==fh.READY&&(this.storedActiveState=e.newState)})),t.on("volume",(e=>{this.volume=e})),t.on("error",(e=>{console.error("Session error:",e.error),this.state=fh.ERROR,this.activeSession=null}));const i=await t.connect();i&&(this.sessionToken=e,this.roomToken=i.token,this.roomUrl=i.url),this.activeSession=t}catch(t){console.error("Failed to start session:",t),this.state=fh.ERROR,this.activeSession=null}}async handleSessionStart(e){this.activeSession?console.log("Connection already in progress or active session exists"):(this.showCourseModal=!1,this.state=fh.LOADING,await this.connectObi(e))}async checkExistingSession(){try{const e=JSON.parse(bh.getItem(yh)||"{}"),{sessionToken:t,roomToken:i,roomUrl:n,sessionExpiry:s,obiState:r}=e;if(!t||!i||!n)return;if(s&&new Date(s)<new Date)return void this.clearSessionStorage();this.state=fh.LOADING;const o=new vh({sessionId:t});if(!o)return console.error("Failed to create session"),this.state=fh.ERROR,void this.clearSessionStorage();o.on("stateChanged",(e=>{this.state=e.newState,e.newState!==fh.READY&&(this.storedActiveState=e.newState)})),o.on("volume",(e=>{this.volume=e})),o.on("error",(e=>{console.error("Session error:",e.error),this.state=fh.ERROR,this.activeSession=null,this.clearSessionStorage()})),await o.reconnect(n,i,r)?(this.activeSession=o,this.sessionToken=t,this.roomToken=i,this.roomUrl=n,this.state=r,this.storedActiveState=r):this.clearSessionStorage()}catch(e){console.error("Error reconnecting to session:",e),this.state=fh.ERROR,this.clearSessionStorage()}}clearSessionStorage(){bh.removeItem(yh)}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.checkExistingSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};bh.setItem(yh,JSON.stringify(t))}}disconnectedCallback(){null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),super.disconnectedCallback()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=fh.READY}handleItemSelect(e,t){"experiences"!==e?Ge([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.terminateSession()})).otherwise((()=>{})):this.showCourseModal=!0}render(){if(this.updateFromConfig(),!this.isActive)return z;const e=Ge(this.state).with(fh.LOADING,(()=>q`<obi-dot-loader></obi-dot-loader>`)).with(fh.RESEARCHING,(()=>q`<obi-searching-loader></obi-searching-loader>`)).with(He.union(fh.USER_SPEAKING,fh.AGENT_SPEAKING),(()=>q`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(fh.PAUSED,(()=>Ih)).otherwise((()=>Ih));return q`
409
409
  <div
410
- class="widget-container ${this.state===Rn.USER_SPEAKING||this.state===Rn.AGENT_SPEAKING?"pulse":""} ${this.state!==Rn.READY||this.navVisible?"rounded":""} ${this.state===Rn.RESEARCHING?"researching":""} ${this.state===Rn.USER_SPEAKING?"user-speaking":""}"
410
+ class="widget-container ${this.state===fh.USER_SPEAKING||this.state===fh.AGENT_SPEAKING?"pulse":""} ${this.state!==fh.READY||this.navVisible?"rounded":""} ${this.state===fh.RESEARCHING?"researching":""} ${this.state===fh.USER_SPEAKING?"user-speaking":""}"
411
411
  @mouseenter=${this.handleMouseEnter}
412
412
  @mouseleave=${this.handleMouseLeave}
413
413
  >
414
414
  ${e}
415
- ${this.navVisible&&this.state!==Rn.RESEARCHING?q`
415
+ ${this.navVisible&&this.state!==fh.RESEARCHING?q`
416
416
  <obi-navigation-bar
417
- ?isActive=${this.state!==Rn.READY}
417
+ ?isActive=${this.state!==fh.READY}
418
418
  .position=${this.position}
419
419
  data-direction="up"
420
420
  .currentState=${this.state}
@@ -425,10 +425,9 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
425
425
  ${this.showCourseModal?q`<obi-course-modal
426
426
  .onClose=${()=>this.showCourseModal=!1}
427
427
  .onCourseSelect=${this.handleSessionStart.bind(this)}
428
- .apiBaseUrl=${this.apiBaseUrl}
429
428
  .apiKey=${this.apiKey}
430
429
  ></obi-course-modal>`:z}
431
- `}}function Ss(e){return{all:e=e||new Map,on:function(t,i){var n=e.get(t);n?n.push(i):e.set(t,[i])},off:function(t,i){var n=e.get(t);n&&(i?n.splice(n.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var n=e.get(t);n&&n.slice().map((function(e){e(i)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,i)}))}}}function Cs(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}Ts.styles=a`
430
+ `}}return hp.styles=o`
432
431
  :host {
433
432
  display: block;
434
433
  position: fixed;
@@ -450,6 +449,12 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
450
449
  left: 20px;
451
450
  }
452
451
 
452
+ :host([position="bottom-center"]) {
453
+ bottom: 80px;
454
+ left: 50%;
455
+ transform: translateX(-50%);
456
+ }
457
+
453
458
  :host([position="top-right"]) {
454
459
  top: 20px;
455
460
  right: 80px;
@@ -460,6 +465,24 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
460
465
  left: 20px;
461
466
  }
462
467
 
468
+ :host([position="top-center"]) {
469
+ top: 20px;
470
+ left: 50%;
471
+ transform: translateX(-50%);
472
+ }
473
+
474
+ :host([position="middle-left"]) {
475
+ top: 50%;
476
+ left: 20px;
477
+ transform: translateY(-50%);
478
+ }
479
+
480
+ :host([position="middle-right"]) {
481
+ top: 50%;
482
+ right: 80px;
483
+ transform: translateY(-50%);
484
+ }
485
+
463
486
  /* Adjust position when in researching state to accommodate wider container */
464
487
  :host([position="bottom-right"]) .widget-container.researching {
465
488
  right: 20px;
@@ -469,6 +492,10 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
469
492
  right: 20px;
470
493
  }
471
494
 
495
+ :host([position="middle-right"]) .widget-container.researching {
496
+ right: 20px;
497
+ }
498
+
472
499
  .widget-container {
473
500
  position: fixed;
474
501
  width: 56px;
@@ -527,5 +554,5 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
527
554
  .pulse {
528
555
  animation: pulse-shadow 2s ease-in-out infinite;
529
556
  }
530
- `,ks([ue({type:String})],Ts.prototype,"apiBaseUrl",2),ks([ue({type:String})],Ts.prototype,"apiKey",2),ks([ue({type:String})],Ts.prototype,"position",2),ks([ue({type:Object})],Ts.prototype,"user",2),ks([he()],Ts.prototype,"state",2),ks([he()],Ts.prototype,"showCourseModal",2),ks([he()],Ts.prototype,"isHovering",2),ks([he()],Ts.prototype,"navVisible",2),ks([he()],Ts.prototype,"activeSession",2),ks([he()],Ts.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Ts);var ws=Object.defineProperty,Es=(e,t,i)=>((e,t,i)=>t in e?ws(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class _s{constructor(){Es(this,"_locking"),Es(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Ps(e,t){if(!e)throw new Error(t)}function Rs(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function xs(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Is(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Os=Symbol("@bufbuild/protobuf/enum-type");function As(e,t,i,n){e[Os]=Ns(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Ns(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const a of t){const e=Ds(a);r.push(e),n[a.name]=e,s[a.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function Ds(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ms{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Ls(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Us(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),a=255&(s?128|n:n);if(i.push(a),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const js=4294967296;function Fs(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const a=Number(e.slice(t,r));s*=i,n=n*i+a,n>=js&&(s+=n/js|0,n%=js)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?Vs(n,s):$s(n,s)}function Bs(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(js*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,a=2*n;const o=1e7;return s>=o&&(r+=Math.floor(s/o),s%=o),r>=o&&(a+=Math.floor(r/o),r%=o),a.toString()+qs(r)+qs(s)}function $s(e,t){return{lo:0|e,hi:0|t}}function Vs(e,t){return t=~t,e?e=1+~e:t+=1,$s(e,t)}const qs=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Zs(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function Ks(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const zs=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>Ps(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Ps(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),Fs(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),Fs(e)),dec:(e,t)=>function(e,t){let i=$s(e,t);const n=2147483648&i.hi;n&&(i=Vs(i.lo,i.hi));const s=Bs(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>Bs(e,t)}}();var Hs,Gs,Ws,Js,Qs,Ys;function Xs(e,t,i){if(t===i)return!0;if(e==Hs.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case Hs.UINT64:case Hs.FIXED64:case Hs.INT64:case Hs.SFIXED64:case Hs.SINT64:return t==i}return!1}function er(e,t){switch(e){case Hs.BOOL:return!1;case Hs.UINT64:case Hs.FIXED64:case Hs.INT64:case Hs.SFIXED64:case Hs.SINT64:return 0==t?zs.zero:"0";case Hs.DOUBLE:case Hs.FLOAT:return 0;case Hs.BYTES:return new Uint8Array(0);case Hs.STRING:return"";default:return 0}}function tr(e,t){switch(e){case Hs.BOOL:return!1===t;case Hs.STRING:return""===t;case Hs.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(Gs=Hs||(Hs={}))[Gs.DOUBLE=1]="DOUBLE",Gs[Gs.FLOAT=2]="FLOAT",Gs[Gs.INT64=3]="INT64",Gs[Gs.UINT64=4]="UINT64",Gs[Gs.INT32=5]="INT32",Gs[Gs.FIXED64=6]="FIXED64",Gs[Gs.FIXED32=7]="FIXED32",Gs[Gs.BOOL=8]="BOOL",Gs[Gs.STRING=9]="STRING",Gs[Gs.BYTES=12]="BYTES",Gs[Gs.UINT32=13]="UINT32",Gs[Gs.SFIXED32=15]="SFIXED32",Gs[Gs.SFIXED64=16]="SFIXED64",Gs[Gs.SINT32=17]="SINT32",Gs[Gs.SINT64=18]="SINT64",(Js=Ws||(Ws={}))[Js.BIGINT=0]="BIGINT",Js[Js.STRING=1]="STRING",(Ys=Qs||(Qs={}))[Ys.Varint=0]="Varint",Ys[Ys.Bit64=1]="Bit64",Ys[Ys.LengthDelimited=2]="LengthDelimited",Ys[Ys.StartGroup=3]="StartGroup",Ys[Ys.EndGroup=4]="EndGroup",Ys[Ys.Bit32=5]="Bit32";class ir{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].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(xs(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Rs(e),Zs(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){Is(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){xs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Rs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Rs(e),Zs(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=zs.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=zs.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=zs.enc(e);return Us(t.lo,t.hi,this.buf),this}sint64(e){let t=zs.enc(e),i=t.hi>>31;return Us(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=zs.uEnc(e);return Us(t.lo,t.hi,this.buf),this}}class nr{constructor(e,t){this.varint64=Ls,this.uint32=Ks,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Qs.Varint:for(;128&this.buf[this.pos++];);break;case Qs.Bit64:this.pos+=4;case Qs.Bit32:this.pos+=4;break;case Qs.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Qs.StartGroup:for(;;){const[e,i]=this.tag();if(i===Qs.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return zs.dec(...this.varint64())}uint64(){return zs.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,zs.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return zs.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return zs.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 sr(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return er(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ar=[];for(let up=0;up<rr.length;up++)ar[rr[up].charCodeAt(0)]=up;ar["-".charCodeAt(0)]=rr.indexOf("+"),ar["_".charCodeAt(0)]=rr.indexOf("/");const or={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,a=0;for(let o=0;o<e.length;o++){if(i=ar[e.charCodeAt(o)],void 0===i)switch(e[o]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=i,r=1;break;case 1:n[s++]=a<<2|(48&i)>>4,a=i,r=2;break;case 2:n[s++]=(15&a)<<4|(60&i)>>2,a=i,r=3;break;case 3:n[s++]=(3&a)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=rr[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=rr[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=rr[s|t>>6],i+=rr[63&t],n=0}return n&&(i+=rr[s],i+="=",1==n&&(i+="=")),i}};function cr(e,t,i){ur(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,a]=sr(t);for(const o of s)t.runtime.bin.readField(r,n.readerFactory(o.data),t.field,o.wireType,n);return a()}function dr(e,t,i,n){ur(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(lr(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=r.writerFactory();let o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function lr(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function ur(e,t){Ps(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function hr(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!tr(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function pr(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?er(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function mr(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Ms.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function gr(e,t){return mr(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}Hs.DOUBLE,Hs.FLOAT,Hs.INT64,Hs.UINT64,Hs.INT32,Hs.UINT32,Hs.BOOL,Hs.STRING,Hs.BYTES;const fr={ignoreUnknownFields:!1},vr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const yr=Symbol(),br=Symbol();function kr(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Tr(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Ps("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(t)));const o=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(e)));switch(i.kind){case"message":o.push(i.T.fromJson(e,n));break;case"enum":const t=wr(i.T,e,n.ignoreUnknownFields,!0);t!==br&&o.push(t);break;case"scalar":try{o.push(Cr(i.T,e,i.L,!0))}catch(a){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(e));throw a instanceof Error&&a.message.length>0&&(t+=": ".concat(a.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=Sr(i.K,e)}catch(a){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}switch(i.V.kind){case"message":o[c]=i.V.T.fromJson(r,n);break;case"enum":const e=wr(i.V.T,r,n.ignoreUnknownFields,!0);e!==br&&(o[c]=e);break;case"scalar":try{o[c]=Cr(i.V.T,r,Ws.BIGINT,!0)}catch(a){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let c=e[r];mr(c)?c.fromJson(t,n):(e[r]=c=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[r]=o.fieldWrapper.unwrapField(c)));break;case"enum":const d=wr(i.T,t,n.ignoreUnknownFields,!1);switch(d){case yr:pr(i,e);break;case br:break;default:e[r]=d}break;case"scalar":try{const n=Cr(i.T,t,i.L,!1);n===yr?pr(i,e):e[r]=n}catch(a){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(kr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}function Sr(e,t){if(e===Hs.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Cr(e,t,Ws.BIGINT,!0).toString()}function Cr(e,t,i,n){if(null===t)return n?er(e,i):yr;switch(e){case Hs.DOUBLE:case Hs.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==Hs.FLOAT&&Is(n),n;case Hs.INT32:case Hs.FIXED32:case Hs.SFIXED32:case Hs.SINT32:case Hs.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==Hs.UINT32||e==Hs.FIXED32?xs(r):Rs(r),r;case Hs.INT64:case Hs.SFIXED64:case Hs.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=zs.parse(t);return i?a.toString():a;case Hs.FIXED64:case Hs.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=zs.uParse(t);return i?o.toString():o;case Hs.BOOL:if("boolean"!=typeof t)break;return t;case Hs.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case Hs.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return or.dec(t)}throw new Error}function wr(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:yr;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return br}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(kr(t)))}function Er(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function _r(e,t,i){if("map"==e.kind){Ps("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=Rr(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Pr(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Ps(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(Rr(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Pr(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return Rr(e.T,t);case"enum":return Pr(e.T,t,i.enumAsInteger);case"message":return gr(e.T,t).toJson(i)}}function Pr(e,t,i){var n;if(Ps("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function Rr(e,t){switch(e){case Hs.INT32:case Hs.SFIXED32:case Hs.SINT32:case Hs.FIXED32:case Hs.UINT32:return Ps("number"==typeof t),t;case Hs.FLOAT:case Hs.DOUBLE:return Ps("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case Hs.STRING:return Ps("string"==typeof t),t;case Hs.BOOL:return Ps("boolean"==typeof t),t;case Hs.UINT64:case Hs.FIXED64:case Hs.INT64:case Hs.SFIXED64:case Hs.SINT64:return Ps("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case Hs.BYTES:return Ps(t instanceof Uint8Array),or.enc(t)}}const xr=Symbol("@bufbuild/protobuf/unknown-fields"),Ir={readUnknownFields:!0,readerFactory:e=>new nr(e)},Or={writeUnknownFields:!0,writerFactory:()=>new ir};function Ar(e,t,i,n,s){let{repeated:r,localName:a}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":const o="enum"==i.kind?Hs.INT32:i.T;let c=Mr;if("scalar"==i.kind&&i.L>0&&(c=Dr),r){let i=e[a];if(n==Qs.LengthDelimited&&o!=Hs.STRING&&o!=Hs.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=i.T;r?e[a].push(Nr(t,new d,s,i)):mr(e[a])?Nr(t,e[a],s,i):(e[a]=Nr(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,a;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=Mr(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=Mr(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Nr(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=er(e.K,Ws.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===a)switch(e.V.kind){case"scalar":a=er(e.V.T,Ws.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[r,a]}(i,t,s);e[a][l]=u}}function Nr(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function Dr(e,t){const i=Mr(e,t);return"bigint"==typeof i?i.toString():i}function Mr(e,t){switch(t){case Hs.STRING:return e.string();case Hs.BOOL:return e.bool();case Hs.DOUBLE:return e.double();case Hs.FLOAT:return e.float();case Hs.INT32:return e.int32();case Hs.INT64:return e.int64();case Hs.UINT64:return e.uint64();case Hs.FIXED64:return e.fixed64();case Hs.BYTES:return e.bytes();case Hs.FIXED32:return e.fixed32();case Hs.SFIXED32:return e.sfixed32();case Hs.SFIXED64:return e.sfixed64();case Hs.SINT64:return e.sint64();case Hs.UINT32:return e.uint32();case Hs.SINT32:return e.sint32()}}function Lr(e,t,i,n){Ps(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?Hs.INT32:e.T;if(s)if(Ps(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,Qs.LengthDelimited).fork();let[,s]=Br(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)Fr(i,r,e.no,n);else Fr(i,r,e.no,t);break;case"message":if(s){Ps(Array.isArray(t));for(const s of t)jr(i,n,e,s)}else jr(i,n,e,t);break;case"map":Ps("object"==typeof t&&null!=t);for(const[s,a]of Object.entries(t))Ur(i,n,e,s,a)}}function Ur(e,t,i,n,s){e.tag(i.no,Qs.LengthDelimited),e.fork();let r=n;switch(i.K){case Hs.INT32:case Hs.FIXED32:case Hs.UINT32:case Hs.SFIXED32:case Hs.SINT32:r=Number.parseInt(n);break;case Hs.BOOL:Ps("true"==n||"false"==n),r="true"==n}switch(Fr(e,i.K,1,r),i.V.kind){case"scalar":Fr(e,i.V.T,2,s);break;case"enum":Fr(e,Hs.INT32,2,s);break;case"message":Ps(void 0!==s),e.tag(2,Qs.LengthDelimited).bytes(s.toBinary(t))}e.join()}function jr(e,t,i,n){const s=gr(i.T,n);i.delimited?e.tag(i.no,Qs.StartGroup).raw(s.toBinary(t)).tag(i.no,Qs.EndGroup):e.tag(i.no,Qs.LengthDelimited).bytes(s.toBinary(t))}function Fr(e,t,i,n){Ps(void 0!==n);let[s,r]=Br(t);e.tag(i,s)[r](n)}function Br(e){let t=Qs.Varint;switch(e){case Hs.BYTES:case Hs.STRING:t=Qs.LengthDelimited;break;case Hs.DOUBLE:case Hs.FIXED64:case Hs.SFIXED64:t=Qs.Bit64;break;case Hs.FIXED32:case Hs.SFIXED32:case Hs.FLOAT:t=Qs.Bit32}return[t,Hs[e].toLowerCase()]}function $r(e){if(void 0===e)return e;if(mr(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Vr(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class qr{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Zr(e,t){const i=zr(e);return t?i:Qr(Jr(i))}const Kr=zr;function zr(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Hr=new Set(["constructor","toString","toJSON","valueOf"]),Gr=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Wr=e=>"".concat(e,"$"),Jr=e=>Gr.has(e)?Wr(e):e,Qr=e=>Hr.has(e)?Wr(e):e;class Yr{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Zr(e,!1)}addField(e){Ps(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Xr=(ea=e=>new qr(e,(e=>function(e){var t,i,n,s,r,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Zr(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Kr(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:Ws.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=Hs.BYTES&&d.T!=Hs.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Yr(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),ta=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=er(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},fr),e):fr},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},vr),e):vr},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(kr(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[a,o]of Object.entries(t)){const t=e.fields.findJsonName(a);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(a,'"'));s.set(t.oneof,a)}Tr(n,o,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&a.startsWith("[")&&a.endsWith("]")){const s=r.findExtension(a.substring(1,a.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=sr(s);Tr(e,o,s.field,i,s),dr(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!hr(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Er(s))continue}const i=_r(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const a=r.findExtensionFor(i.typeName,s.no);if(a&&lr(e,a)){const i=cr(e,a,t),s=_r(a.field,i,t);void 0!==s&&(n[a.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Cr(e,t,null!=i?i:Ws.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||tr(e,t)?Rr(e,t):void 0},debug:kr},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Ir),e):Ir},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Or),e):Or},listUnknownFields(e){var t;return null!==(t=e[xr])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[xr]},writeUnknownFields(e,t){const i=e[xr];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[xr])||(s[xr]=[]),s[xr].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),a=s?t.len:t.pos+i;let o,c;for(;t.pos<a&&([o,c]=t.tag(),!0!==s||c!=Qs.EndGroup);){const i=r.fields.find(o);if(i)Ar(e,t,i,c,n);else{const i=t.skip(c,o);n.readUnknownFields&&this.onUnknownField(e,o,c,i)}}if(s&&(c!=Qs.EndGroup||o!==i))throw new Error("invalid end group tag")},readField:Ar,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(hr(s,e))Lr(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Lr(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:As,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let a=r[i].value;t&&"message"==t.kind&&!mr(a,t.T)?a=new t.T(a):t&&"scalar"===t.kind&&t.T===Hs.BYTES&&(a=Vr(a)),s[i]={case:e,value:a};break;case"scalar":case"enum":let o=r[i];n.T===Hs.BYTES&&(o=n.repeated?o.map(Vr):Vr(o)),s[i]=o;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Hs.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=Vr(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>mr(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Vr(e):s[i]=e:s[i]=mr(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>Xs(e.T,t,s[i])));case"enum":return n.every(((e,t)=>Xs(Hs.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return Xs(Hs.INT32,n,s);case"scalar":return Xs(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return Xs(Hs.INT32,n.value,s.value);case"scalar":return Xs(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>Xs(Hs.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>Xs(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map($r);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=$r(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:$r(t.value)}:{case:void 0}:$r(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:ea,initFields:ta}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),a={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(a.prototype,new Ms),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=Ds(s);n[e.localName]=e.no,n[e.no]=e.localName}return As(n,e,t),n},makeEnumType:Ns,getEnumType:function(e){const t=e[Os];return Ps(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var ea,ta;class ia extends Ms{constructor(e){super(),this.seconds=zs.zero,this.nanos=0,Xr.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Xr.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=zs.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return ia.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ia({seconds:zs.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new ia).fromBinary(e,t)}static fromJson(e,t){return(new ia).fromJson(e,t)}static fromJsonString(e,t){return(new ia).fromJsonString(e,t)}static equals(e,t){return Xr.util.equals(ia,e,t)}}ia.runtime=Xr,ia.typeName="google.protobuf.Timestamp",ia.fields=Xr.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const na=Xr.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ia},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:sa,repeated:!0},{no:5,name:"events",kind:"message",T:aa,repeated:!0}])),sa=Xr.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:ra,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),ra=Xr.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ia},{no:3,name:"value",kind:"scalar",T:2}])),aa=Xr.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:ia},{no:7,name:"normalized_end_timestamp",kind:"message",T:ia,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),oa=Xr.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ca=Xr.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),da=Xr.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),la=Xr.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ua=Xr.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ha=Xr.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),pa=Xr.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),ma=Xr.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),ga=Xr.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),fa=Xr.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),va=Xr.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ya,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Wa}])),ya=Xr.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ba=Xr.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Xr.getEnumType(da),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),ka=Xr.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Xr.getEnumType(Ta)},{no:4,name:"tracks",kind:"message",T:_a,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:ba},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Xr.getEnumType(Sa)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Xr.getEnumType(pa)},{no:18,name:"kind_details",kind:"enum",T:Xr.getEnumType(Ca),repeated:!0}])),Ta=Xr.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Sa=Xr.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Ca=Xr.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),wa=Xr.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ea=Xr.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Pa,repeated:!0}])),_a=Xr.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Xr.getEnumType(ca)},{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:Xr.getEnumType(da)},{no:10,name:"layers",kind:"message",T:Pa,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:Ea,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:Xr.getEnumType(wa)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Wa},{no:19,name:"audio_features",kind:"enum",T:Xr.getEnumType(fa),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Xr.getEnumType(oa)}])),Pa=Xr.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Xr.getEnumType(la)},{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}])),Ra=Xr.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Xr.getEnumType(xa)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Aa,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Ia,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Na,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Da,oneof:"value"},{no:8,name:"metrics",kind:"message",T:na,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:La,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ua,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ja,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Fa,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Xa,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:eo,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:to,oneof:"value"}])),xa=Xr.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Ia=Xr.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Oa,repeated:!0}])),Oa=Xr.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),Aa=Xr.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),Na=Xr.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Da=Xr.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Ma,repeated:!0}])),Ma=Xr.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),La=Xr.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),Ua=Xr.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),ja=Xr.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Fa=Xr.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Ba,oneof:"value"}])),Ba=Xr.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),$a=Xr.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Va=Xr.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Xr.getEnumType(qa)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),qa=Xr.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Za=Xr.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Xr.getEnumType(Ka)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),Ka=Xr.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),za=Xr.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ha},{no:2,name:"screen",kind:"message",T:Ha},{no:3,name:"resume_connection",kind:"enum",T:Xr.getEnumType(ha)},{no:4,name:"disabled_codecs",kind:"message",T:Ga},{no:5,name:"force_relay",kind:"enum",T:Xr.getEnumType(ha)}])),Ha=Xr.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Xr.getEnumType(ha)}])),Ga=Xr.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ya,repeated:!0},{no:2,name:"publish",kind:"message",T:ya,repeated:!0}])),Wa=Xr.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ja=Xr.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Qa=Xr.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Xr.getEnumType(Ja)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),Ya=Xr.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Xa=Xr.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:Xr.getEnumType(wa)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Qa,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ya,oneof:"content_header"}]),{localName:"DataStream_Header"}),eo=Xr.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),to=Xr.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),io=Xr.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),no=Xr.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),so=Xr.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ro=Xr.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:fo,oneof:"message"},{no:2,name:"answer",kind:"message",T:fo,oneof:"message"},{no:3,name:"trickle",kind:"message",T:lo,oneof:"message"},{no:4,name:"add_track",kind:"message",T:co,oneof:"message"},{no:5,name:"mute",kind:"message",T:uo,oneof:"message"},{no:6,name:"subscription",kind:"message",T:yo,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:bo,oneof:"message"},{no:8,name:"leave",kind:"message",T:So,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:wo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Uo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Fo,oneof:"message"},{no:13,name:"simulate",kind:"message",T:$o,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Eo,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Vo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ko,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:To,oneof:"message"}])),ao=Xr.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:ho,oneof:"message"},{no:2,name:"answer",kind:"message",T:fo,oneof:"message"},{no:3,name:"offer",kind:"message",T:fo,oneof:"message"},{no:4,name:"trickle",kind:"message",T:lo,oneof:"message"},{no:5,name:"update",kind:"message",T:vo,oneof:"message"},{no:6,name:"track_published",kind:"message",T:mo,oneof:"message"},{no:8,name:"leave",kind:"message",T:So,oneof:"message"},{no:9,name:"mute",kind:"message",T:uo,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Po,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ro,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Io,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ao,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Mo,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:jo,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:go,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:po,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:qo,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:zo,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ho,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Wo,oneof:"message"}])),oo=Xr.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),co=Xr.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Xr.getEnumType(ca)},{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:Xr.getEnumType(da)},{no:9,name:"layers",kind:"message",T:Pa,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:oo,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:Xr.getEnumType(wa)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Xr.getEnumType(oa)}])),lo=Xr.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Xr.getEnumType(io)},{no:3,name:"final",kind:"scalar",T:8}])),uo=Xr.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),ho=Xr.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:va},{no:2,name:"participant",kind:"message",T:ka},{no:3,name:"other_participants",kind:"message",T:ka,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:_o,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:za},{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:Va},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ya,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),po=Xr.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:_o,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:za}])),mo=Xr.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:_a}])),go=Xr.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),fo=Xr.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),vo=Xr.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:ka,repeated:!0}])),yo=Xr.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:$a,repeated:!0}])),bo=Xr.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Xr.getEnumType(la)},{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}])),ko=Xr.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Xr.getEnumType(fa),repeated:!0}])),To=Xr.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),So=Xr.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Xr.getEnumType(pa)},{no:3,name:"action",kind:"enum",T:Xr.getEnumType(Co)},{no:4,name:"regions",kind:"message",T:Zo}])),Co=Xr.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),wo=Xr.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Pa,repeated:!0}])),Eo=Xr.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),_o=Xr.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),Po=Xr.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Oa,repeated:!0}])),Ro=Xr.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:va}])),xo=Xr.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Xr.getEnumType(ua)},{no:3,name:"score",kind:"scalar",T:2}])),Io=Xr.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:xo,repeated:!0}])),Oo=Xr.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Xr.getEnumType(no)}])),Ao=Xr.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Oo,repeated:!0}])),No=Xr.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Xr.getEnumType(la)},{no:2,name:"enabled",kind:"scalar",T:8}])),Do=Xr.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:No,repeated:!0}])),Mo=Xr.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:No,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Do,repeated:!0}])),Lo=Xr.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Uo=Xr.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Lo,repeated:!0}])),jo=Xr.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Fo=Xr.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:fo},{no:2,name:"subscription",kind:"message",T:yo},{no:3,name:"publish_tracks",kind:"message",T:mo,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Bo,repeated:!0},{no:5,name:"offer",kind:"message",T:fo},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),Bo=Xr.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Xr.getEnumType(io)}])),$o=Xr.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Xr.getEnumType(so),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),Vo=Xr.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),qo=Xr.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Zo=Xr.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Ko,repeated:!0}])),Ko=Xr.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),zo=Xr.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Xr.getEnumType(ga)}])),Ho=Xr.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Xr.getEnumType(Go)},{no:3,name:"message",kind:"scalar",T:9}])),Go=Xr.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Wo=Xr.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function Jo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Qo,Yo,Xo,ec,tc,ic,nc,sc,rc={exports:{}},ac=(Qo||(Qo=1,Xo=rc.exports,ec=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?a(console,n):void 0!==console.log?a(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var a,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=o?o:a},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(a=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},a=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(Yo=rc).exports?Yo.exports=ec():Xo.log=ec()),rc.exports);(ic=tc||(tc={}))[ic.trace=0]="trace",ic[ic.debug=1]="debug",ic[ic.info=2]="info",ic[ic.warn=3]="warn",ic[ic.error=4]="error",ic[ic.silent=5]="silent",(sc=nc||(nc={})).Default="livekit",sc.Room="livekit-room",sc.Participant="livekit-participant",sc.Track="livekit-track",sc.Publication="livekit-track-publication",sc.Engine="livekit-engine",sc.Signal="livekit-signal",sc.PCManager="livekit-pc-manager",sc.PCTransport="livekit-pc-transport",sc.E2EE="lk-e2ee";let oc=ac.getLogger("livekit");function cc(e){const t=ac.getLogger(e);return t.setDefaultLevel(oc.getLevel()),t}Object.values(nc).map((e=>ac.getLogger(e))),oc.setDefaultLevel(tc.info);const dc=ac.getLogger("lk-e2ee"),lc=7e3,uc=[0,300,1200,2700,4800,lc,lc,lc,lc,lc];function hc(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{c(n.next(e))}catch(t){r(t)}}function o(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}c((n=n.apply(e,t||[])).next())}))}function pc(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var mc,gc={exports:{}},fc=function(){if(mc)return gc.exports;mc=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}gc.exports=s,gc.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(a(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=o(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;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(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},gc.exports}();let vc=!0,yc=!0;function bc(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function kc(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Tc(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(vc=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Sc(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(yc=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Cc(){if("object"==typeof window){if(vc)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function wc(e,t){yc&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ec(e){return"[object Object]"===Object.prototype.toString.call(e)}function _c(e){return Ec(e)?Object.keys(e).reduce((function(t,i){const n=Ec(e[i]),s=n?_c(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function Pc(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Pc(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Pc(e,e.get(t),i)}))})))}function Rc(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Pc(e,i,s)}))})),s}const xc=Cc;function Ic(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const a=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=r.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),xc("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return xc("chrome: "+JSON.stringify(e)),s(e)},r=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(r(e))))))}}}function Oc(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Ac(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else kc(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Nc(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Dc(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Rc(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),kc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Rc(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Mc(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Lc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Mc(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Uc(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function jc(e,t){kc(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Fc=Object.freeze({__proto__:null,fixNegotiationNeeded:jc,shimAddTrackRemoveTrack:Lc,shimAddTrackRemoveTrackWithNative:Mc,shimGetSendersWithDtmf:Nc,shimGetUserMedia:Ic,shimMediaStream:Oc,shimOnTrack:Ac,shimPeerConnection:Uc,shimSenderReceiverGetStats:Dc});function Bc(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){wc("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function $c(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Vc(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function qc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Zc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),kc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Kc(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){wc("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function zc(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Hc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Gc(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Wc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Jc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Qc=Object.freeze({__proto__:null,shimAddTransceiver:Hc,shimCreateAnswer:Jc,shimCreateOffer:Wc,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Gc,shimGetUserMedia:Bc,shimOnTrack:$c,shimPeerConnection:Vc,shimRTCDataChannel:zc,shimReceiverGetStats:Zc,shimRemoveStream:Kc,shimSenderGetStats:qc});function Yc(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Xc(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function ed(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function td(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(id(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function id(e){return e&&void 0!==e.video?Object.assign({},e,{video:_c(e.video)}):e}function nd(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(wc("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function sd(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function rd(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ad(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var od,cd=Object.freeze({__proto__:null,shimAudioContext:ad,shimCallbacksAPI:ed,shimConstraints:id,shimCreateOfferLegacy:rd,shimGetUserMedia:td,shimLocalStreamsAPI:Yc,shimRTCIceServerUrls:nd,shimRemoteStreamsAPI:Xc,shimTrackEventTransceiver:sd}),dd={exports:{}},ld=(od||(od=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(dd)),dd.exports),ud=Jo(ld),hd=Cs({__proto__:null,default:ud},[ld]);function pd(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=ud.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,kc(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function md(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||kc(e,"icecandidate",(e=>{if(e.candidate){const t=ud.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function gd(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ud.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ud.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=ud.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function fd(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},kc(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function vd(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function yd(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function bd(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function kd(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Td=Object.freeze({__proto__:null,removeExtmapAllowMixed:yd,shimAddIceCandidateNullOrEmpty:bd,shimConnectionState:vd,shimMaxMessageSize:gd,shimParameterlessSetLocalDescription:kd,shimRTCIceCandidate:pd,shimRTCIceCandidateRelayProtocol:md,shimSendThrowTypeError:fd});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Cc,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=bc(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=bc(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=bc(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Td,extractVersion:bc,disableLog:Tc,disableWarnings:Sc,sdp:hd};switch(n.browser){case"chrome":if(!Fc||!Uc||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Fc,bd(e,n),kd(e),Ic(e,n),Oc(e),Uc(e,n),Ac(e),Lc(e,n),Nc(e),Dc(e),jc(e,n),pd(e),md(e),vd(e),gd(e,n),fd(e),yd(e,n);break;case"firefox":if(!Qc||!Vc||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Qc,bd(e,n),kd(e),Bc(e,n),Vc(e,n),$c(e),Kc(e),qc(e),Zc(e),zc(e),Hc(e),Gc(e),Wc(e),Jc(e),pd(e),vd(e),gd(e,n),fd(e);break;case"safari":if(!cd||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=cd,bd(e,n),kd(e),nd(e),rd(e),ed(e),Yc(e),Xc(e),sd(e),td(e),ad(e),pd(e),md(e),gd(e,n),fd(e),yd(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Sd="lk_e2ee";var Cd,wd,Ed,_d,Pd,Rd,xd,Id,Od,Ad,Nd,Dd,Md,Ld,Ud,jd,Fd,Bd,$d,Vd;function qd(){return void 0!==window.RTCRtpScriptTransform}(wd=Cd||(Cd={})).SetKey="setKey",wd.RatchetRequest="ratchetRequest",wd.KeyRatcheted="keyRatcheted",(Ed||(Ed={})).KeyRatcheted="keyRatcheted",(Pd=_d||(_d={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Pd.EncryptionError="encryptionError",(Rd||(Rd={})).Error="cryptorError",fc.EventEmitter;class Zd extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(Id=xd||(xd={}))[Id.NotAllowed=0]="NotAllowed",Id[Id.ServerUnreachable=1]="ServerUnreachable",Id[Id.InternalError=2]="InternalError",Id[Id.Cancelled=3]="Cancelled",Id[Id.LeaveRequest=4]="LeaveRequest";class Kd extends Zd{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=xd[t]}}class zd extends Zd{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Hd extends Zd{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Gd extends Zd{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Wd extends Zd{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Jd extends Zd{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Qd extends Zd{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Yd extends Zd{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Go[t]}}(Ad=Od||(Od={})).PermissionDenied="PermissionDenied",Ad.NotFound="NotFound",Ad.DeviceInUse="DeviceInUse",Ad.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(Od||(Od={})),(Dd=Nd||(Nd={}))[Dd.InvalidKey=0]="InvalidKey",Dd[Dd.MissingKey=1]="MissingKey",Dd[Dd.InternalError=2]="InternalError",(Ld=Md||(Md={})).Connected="connected",Ld.Reconnecting="reconnecting",Ld.SignalReconnecting="signalReconnecting",Ld.Reconnected="reconnected",Ld.Disconnected="disconnected",Ld.ConnectionStateChanged="connectionStateChanged",Ld.MediaDevicesChanged="mediaDevicesChanged",Ld.ParticipantConnected="participantConnected",Ld.ParticipantDisconnected="participantDisconnected",Ld.TrackPublished="trackPublished",Ld.TrackSubscribed="trackSubscribed",Ld.TrackSubscriptionFailed="trackSubscriptionFailed",Ld.TrackUnpublished="trackUnpublished",Ld.TrackUnsubscribed="trackUnsubscribed",Ld.TrackMuted="trackMuted",Ld.TrackUnmuted="trackUnmuted",Ld.LocalTrackPublished="localTrackPublished",Ld.LocalTrackUnpublished="localTrackUnpublished",Ld.LocalAudioSilenceDetected="localAudioSilenceDetected",Ld.ActiveSpeakersChanged="activeSpeakersChanged",Ld.ParticipantMetadataChanged="participantMetadataChanged",Ld.ParticipantNameChanged="participantNameChanged",Ld.ParticipantAttributesChanged="participantAttributesChanged",Ld.RoomMetadataChanged="roomMetadataChanged",Ld.DataReceived="dataReceived",Ld.SipDTMFReceived="sipDTMFReceived",Ld.TranscriptionReceived="transcriptionReceived",Ld.ConnectionQualityChanged="connectionQualityChanged",Ld.TrackStreamStateChanged="trackStreamStateChanged",Ld.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ld.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ld.AudioPlaybackStatusChanged="audioPlaybackChanged",Ld.VideoPlaybackStatusChanged="videoPlaybackChanged",Ld.MediaDevicesError="mediaDevicesError",Ld.ParticipantPermissionsChanged="participantPermissionsChanged",Ld.SignalConnected="signalConnected",Ld.RecordingStatusChanged="recordingStatusChanged",Ld.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ld.EncryptionError="encryptionError",Ld.DCBufferStatusChanged="dcBufferStatusChanged",Ld.ActiveDeviceChanged="activeDeviceChanged",Ld.ChatMessage="chatMessage",Ld.LocalTrackSubscribed="localTrackSubscribed",Ld.MetricsReceived="metricsReceived",(jd=Ud||(Ud={})).TrackPublished="trackPublished",jd.TrackSubscribed="trackSubscribed",jd.TrackSubscriptionFailed="trackSubscriptionFailed",jd.TrackUnpublished="trackUnpublished",jd.TrackUnsubscribed="trackUnsubscribed",jd.TrackMuted="trackMuted",jd.TrackUnmuted="trackUnmuted",jd.LocalTrackPublished="localTrackPublished",jd.LocalTrackUnpublished="localTrackUnpublished",jd.ParticipantMetadataChanged="participantMetadataChanged",jd.ParticipantNameChanged="participantNameChanged",jd.DataReceived="dataReceived",jd.SipDTMFReceived="sipDTMFReceived",jd.TranscriptionReceived="transcriptionReceived",jd.IsSpeakingChanged="isSpeakingChanged",jd.ConnectionQualityChanged="connectionQualityChanged",jd.TrackStreamStateChanged="trackStreamStateChanged",jd.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",jd.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",jd.MediaDevicesError="mediaDevicesError",jd.AudioStreamAcquired="audioStreamAcquired",jd.ParticipantPermissionsChanged="participantPermissionsChanged",jd.PCTrackAdded="pcTrackAdded",jd.AttributesChanged="attributesChanged",jd.LocalTrackSubscribed="localTrackSubscribed",jd.ChatMessage="chatMessage",(Bd=Fd||(Fd={})).TransportsCreated="transportsCreated",Bd.Connected="connected",Bd.Disconnected="disconnected",Bd.Resuming="resuming",Bd.Resumed="resumed",Bd.Restarting="restarting",Bd.Restarted="restarted",Bd.SignalResumed="signalResumed",Bd.SignalRestarted="signalRestarted",Bd.Closing="closing",Bd.MediaTrackAdded="mediaTrackAdded",Bd.ActiveSpeakersUpdate="activeSpeakersUpdate",Bd.DataPacketReceived="dataPacketReceived",Bd.RTPVideoMapUpdate="rtpVideoMapUpdate",Bd.DCBufferStatusChanged="dcBufferStatusChanged",Bd.ParticipantUpdate="participantUpdate",Bd.RoomUpdate="roomUpdate",Bd.SpeakersChanged="speakersChanged",Bd.StreamStateChanged="streamStateChanged",Bd.ConnectionQualityUpdate="connectionQualityUpdate",Bd.SubscriptionError="subscriptionError",Bd.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Bd.RemoteMute="remoteMute",Bd.SubscribedQualityUpdate="subscribedQualityUpdate",Bd.LocalTrackUnpublished="localTrackUnpublished",Bd.LocalTrackSubscribed="localTrackSubscribed",Bd.Offline="offline",Bd.SignalRequestResponse="signalRequestResponse",Bd.SignalConnected="signalConnected",(Vd=$d||($d={})).Message="message",Vd.Muted="muted",Vd.Unmuted="unmuted",Vd.Restarted="restarted",Vd.Ended="ended",Vd.Subscribed="subscribed",Vd.Unsubscribed="unsubscribed",Vd.UpdateSettings="updateSettings",Vd.UpdateSubscription="updateSubscription",Vd.AudioPlaybackStarted="audioPlaybackStarted",Vd.AudioPlaybackFailed="audioPlaybackFailed",Vd.AudioSilenceDetected="audioSilenceDetected",Vd.VisibilityChanged="visibilityChanged",Vd.VideoDimensionsChanged="videoDimensionsChanged",Vd.VideoPlaybackStarted="videoPlaybackStarted",Vd.VideoPlaybackFailed="videoPlaybackFailed",Vd.ElementAttached="elementAttached",Vd.ElementDetached="elementDetached",Vd.UpstreamPaused="upstreamPaused",Vd.UpstreamResumed="upstreamResumed",Vd.SubscriptionPermissionChanged="subscriptionPermissionChanged",Vd.SubscriptionStatusChanged="subscriptionStatusChanged",Vd.SubscriptionFailed="subscriptionFailed",Vd.TrackProcessorUpdate="trackProcessorUpdate",Vd.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Vd.TranscriptionReceived="transcriptionReceived",Vd.TimeSyncUpdate="timeSyncUpdate";const Xd=/version\/(\d+(\.?_?\d+)+)/i;let el;function tl(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===el||t){const e=il.find((e=>{let{test:t}=e;return t.test(i)}));el=null==e?void 0:e.describe(i)}return el}const il=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:nl(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:sl(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:nl(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:sl(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:nl(Xd,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:sl(e)})}];function nl(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function sl(e){return e.includes("mac os")?nl(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class rl{}rl.setTimeout=function(){return setTimeout(...arguments)},rl.setInterval=function(){return setInterval(...arguments)},rl.clearTimeout=function(){return clearTimeout(...arguments)},rl.clearInterval=function(){return clearInterval(...arguments)};const al=[];var ol,cl;(cl=ol||(ol={}))[cl.LOW=0]="LOW",cl[cl.MEDIUM=1]="MEDIUM",cl[cl.HIGH=2]="HIGH";class dl extends fc.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=dl.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=oc,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=cc(null!==(n=i.loggerName)&&void 0!==n?n:nc.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=dl.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),fu(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===dl.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===dl.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(al.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&al.splice(al.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ll(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?$d.AudioPlaybackStarted:$d.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?$d.AudioPlaybackFailed:$d.VideoPlaybackFailed,t):"AbortError"===t.name?oc.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):oc.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit($d.ElementAttached,e),e}detach(e){try{if(e){ul(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit($d.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{ul(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit($d.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=cc(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),al.forEach((e=>{e.parentElement||(t=!1)})),t&&al.push(e)}}handleAppVisibilityChanged(){return hc(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==dl.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Al()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Al()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ll(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),Il()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Il()||xl())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function ul(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var a;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(a=r=e.StreamState||(e.StreamState={})).Active="active",a.Paused="paused",a.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return ca.AUDIO;case t.Video:return ca.VIDEO;default:return ca.DATA}},e.kindFromProto=function(e){switch(e){case ca.AUDIO:return t.Audio;case ca.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return da.CAMERA;case n.Microphone:return da.MICROPHONE;case n.ScreenShare:return da.SCREEN_SHARE;case n.ScreenShareAudio:return da.SCREEN_SHARE_AUDIO;default:return da.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case da.CAMERA:return n.Camera;case da.MICROPHONE:return n.Microphone;case da.SCREEN_SHARE:return n.ScreenShare;case da.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case no.ACTIVE:return r.Active;case no.PAUSED:return r.Paused;default:return r.Unknown}}}(dl||(dl={}));class hl{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const pl=["vp8","h264"],ml=["vp8","h264","vp9","av1"];function gl(e){return!!pl.find((t=>t===e))}var fl,vl,yl,bl;(vl=fl||(fl={}))[vl.PREFER_REGRESSION=0]="PREFER_REGRESSION",vl[vl.SIMULCAST=1]="SIMULCAST",vl[vl.REGRESSION=2]="REGRESSION",(bl=yl||(yl={})).telephone={maxBitrate:12e3},bl.speech={maxBitrate:24e3},bl.music={maxBitrate:48e3},bl.musicStereo={maxBitrate:64e3},bl.musicHighQuality={maxBitrate:96e3},bl.musicHighQualityStereo={maxBitrate:128e3};const kl={h90:new hl(160,90,9e4,20),h180:new hl(320,180,16e4,20),h216:new hl(384,216,18e4,20),h360:new hl(640,360,45e4,20),h540:new hl(960,540,8e5,25),h720:new hl(1280,720,17e5,30),h1080:new hl(1920,1080,3e6,30),h1440:new hl(2560,1440,5e6,30),h2160:new hl(3840,2160,8e6,30)},Tl={h120:new hl(160,120,7e4,20),h180:new hl(240,180,125e3,20),h240:new hl(320,240,14e4,20),h360:new hl(480,360,33e4,20),h480:new hl(640,480,5e5,20),h540:new hl(720,540,6e5,25),h720:new hl(960,720,13e5,30),h1080:new hl(1440,1080,23e5,30),h1440:new hl(1920,1440,38e5,30)},Sl={h360fps3:new hl(640,360,2e5,3,"medium"),h360fps15:new hl(640,360,4e5,15,"medium"),h720fps5:new hl(1280,720,8e5,5,"medium"),h720fps15:new hl(1280,720,15e5,15,"medium"),h720fps30:new hl(1280,720,2e6,30,"medium"),h1080fps15:new hl(1920,1080,25e5,15,"medium"),h1080fps30:new hl(1920,1080,5e6,30,"medium"),original:new hl(0,0,7e6,30,"medium")},Cl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function wl(e){return hc(this,void 0,void 0,(function*(){return new Promise((t=>rl.setTimeout(t,e)))}))}function El(){return"addTransceiver"in RTCPeerConnection.prototype}function _l(){return"addTrack"in RTCPeerConnection.prototype}function Pl(e){return"av1"===e||"vp9"===e}function Rl(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function xl(){var e;return"Firefox"===(null===(e=tl())||void 0===e?void 0:e.name)}function Il(){var e;return"Safari"===(null===(e=tl())||void 0===e?void 0:e.name)}function Ol(){var e,t;return!!Al()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Al(){return"undefined"!=typeof document}function Nl(){return"ReactNative"==navigator.product}function Dl(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ml(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ll(){if(!Nl())return;let e=Ml();return e?e.platform:void 0}function Ul(){if(Al())return window.devicePixelRatio;if(Nl()){let e=Ml();if(e)return e.devicePixelRatio}return 1}function jl(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Fl(e){for(const t of e)t.target.handleResize(t)}function Bl(e){for(const t of e)t.target.handleVisibilityChanged(t)}let $l=null;const Vl=()=>($l||($l=new ResizeObserver(Fl)),$l);let ql=null;const Zl=()=>(ql||(ql=new IntersectionObserver(Bl,{root:null,rootMargin:"0px"})),ql);function Kl(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!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=i,o}let zl;function Hl(){if(!zl){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[zl]=n.stream.getAudioTracks(),!zl)throw Error("Could not get empty media stream audio track");zl.enabled=!1}return zl.clone()}class Gl{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>hc(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function Wl(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Jl(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Ql(e){switch(e.reason){case xd.LeaveRequest:return e.context;case xd.Cancelled:return pa.CLIENT_INITIATED;case xd.NotAllowed:return pa.USER_REJECTED;case xd.ServerUnreachable:return pa.JOIN_FAILURE;default:return pa.UNKNOWN_REASON}}function Yl(e){return void 0!==e?Number(e):void 0}function Xl(e){return void 0!==e?BigInt(e):void 0}function eu(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function tu(e){return!!e&&e.kind==dl.Kind.Audio}function iu(e){return!!e&&e.kind==dl.Kind.Video}function nu(e){return eu(e)&&iu(e)}function su(e){return eu(e)&&tu(e)}function ru(e){return!!e&&!e.isLocal}function au(e){return!!e&&!e.isLocal}function ou(e){return ru(e)&&iu(e)}function cu(e,t,i){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=vu(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=o?o:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(du(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(du(h.video,i),null!==(s=(a=h.video).deviceId)&&void 0!==s||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function du(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function lu(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,a=e.video;Object.keys(a).forEach((e=>{"resolution"===e?du(s,a.resolution):s[e]=a[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function uu(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>hc(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function hu(e){return"audioinput"===e?dl.Source.Microphone:"videoinput"===e?dl.Source.Camera:dl.Source.Unknown}function pu(e){return e===dl.Source.Microphone?"audioinput":e===dl.Source.Camera?"videoinput":void 0}function mu(e){return e.split("/")[1].toLowerCase()}function gu(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new mo({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function fu(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?fu(e.track):{})}}function vu(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class yu extends fc.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":oc.error(s.error.message),this.emit(_d.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(_d.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(_d.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Cd.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{oc.error("e2ee worker encountered an error:",{error:e.error}),this.emit(_d.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||qd()))throw new zd("tried to setup end-to-end encryption on an unsupported browser");if(oc.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:dc.getLevel()}};this.worker&&(oc.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){oc.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):oc.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Fd.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(Md.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==wa.NONE,t.identity))),e.on(Md.ConnectionStateChanged,(t=>{t===Lh.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==wa.NONE,e.identity)}))}))})).on(Md.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(Md.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(Md.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(Ud.LocalTrackPublished,(e=>hc(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(Cd.SetKey,(e=>this.postKey(e))).on(Cd.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?mu(i.mimeType):void 0)}}setupE2EESender(e,t){eu(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||oc.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return hc(this,void 0,void 0,(function*(){if(this.worker){if(qd()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Sd in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const a={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(a,[r,s])}e[Sd]=!0}}))}handleSender(e,t,i){var n;if(!(Sd in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(qd()){oc.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{oc.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[Sd]=!0}}}const bu="default";class ku{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new ku),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=ku.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){oc.debug("awaiting getUserMedia promise");try{e?yield ku.userMediaPromiseMap.get(e):yield Promise.all(ku.userMediaPromiseMap.values())}catch(r){oc.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Il()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return hc(this,void 0,void 0,(function*(){if(t!==bu)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===bu));if(!s)return void oc.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==bu&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;oc.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?ku.userMediaPromiseMap.has(e):ku.userMediaPromiseMap.size>0}}var Tu,Su;ku.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ku.userMediaPromiseMap=new Map,(Su=Tu||(Tu={}))[Su.WAITING=0]="WAITING",Su[Su.RUNNING=1]="RUNNING",Su[Su.COMPLETED=2]="COMPLETED";class Cu{constructor(){this.pendingTasks=new Map,this.taskMutex=new _s,this.nextTaskIndex=0}run(e){return hc(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Tu.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Tu.RUNNING,yield e()}finally{t.status=Tu.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return hc(this,void 0,void 0,(function*(){return this.run((()=>hc(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function wu(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const Eu=["syncState","trickle","offer","answer","simulate","leave"];var _u,Pu;(Pu=_u||(_u={}))[Pu.CONNECTING=0]="CONNECTING",Pu[Pu.CONNECTED=1]="CONNECTED",Pu[Pu.RECONNECTING=2]="RECONNECTING",Pu[Pu.DISCONNECTING=3]="DISCONNECTING",Pu[Pu.DISCONNECTED=4]="DISCONNECTED";class Ru{get currentState(){return this.state}get isDisconnected(){return this.state===_u.DISCONNECTING||this.state===_u.DISCONNECTED}get isEstablishingConnection(){return this.state===_u.CONNECTING||this.state===_u.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=_u.DISCONNECTED,this.log=oc,this._requestId=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.log=cc(null!==(i=t.loggerName)&&void 0!==i?i:nc.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Cu,this.queuedRequests=[],this.closingLock=new _s,this.connectionLock=new _s,this.state=_u.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return hc(this,void 0,void 0,(function*(){return this.state=_u.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return hc(this,void 0,void 0,(function*(){if(this.options)return this.state=_u.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Nl()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new Za({sdk:Ka.JS,protocol:15,version:"2.11.4"});return Nl()&&(t.os=null!==(e=Ll())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),wu(i,"rtc")}(e,s),a=wu(new URL(Jl(r)),"validate");return new Promise(((e,t)=>hc(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>hc(this,void 0,void 0,(function*(){this.close(),clearTimeout(o),t(new Kd("room connection has been cancelled (signal)",xd.Cancelled))})),o=setTimeout((()=>{this.close(),t(new Kd("room connection has timed out (signal)",xd.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(o)},this.ws.onerror=e=>hc(this,void 0,void 0,(function*(){if(this.state===_u.CONNECTED)this.handleWSError(e);else{this.state=_u.DISCONNECTED,clearTimeout(o);try{const i=yield fetch(a);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new Kd(e,xd.NotAllowed,i.status))}else t(new Kd("Encountered unknown websocket error during connection: ".concat(e.toString()),xd.InternalError,i.status))}catch(i){t(new Kd(i instanceof Error?i.message:"server was not reachable",xd.ServerUnreachable))}}})),this.ws.onmessage=r=>hc(this,void 0,void 0,(function*(){var a,o,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=ao.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=ao.fromBinary(new Uint8Array(r.data))}if(this.state!==_u.CONNECTED){let r=!1;if("join"===(null===(a=d.message)||void 0===a?void 0:a.case)?(this.state=_u.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===_u.RECONNECTING&&"leave"!==d.message.case?(this.state=_u.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(o=d.message)||void 0===o?void 0:o.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new Kd("Received leave request while trying to (re)connect",xd.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new Kd("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),xd.InternalError)),!r)return}this.signalLatency&&(yield wl(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new Kd("Websocket got closed during a (re)connection attempt",xd.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return hc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=_u.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,wl(250)])),e.ws=void 0}}finally{t&&(e.state=_u.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Iu(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Iu(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new lo({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new uo({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return hc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Eo({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 wo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Uo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:zs.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Vo({timestamp:zs.parse(Date.now()),rtt:zs.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ko({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new So({reason:pa.CLIENT_INITIATED,action:Co.DISCONNECT})})}sendRequest(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=Eu.indexOf(e.case)>=0;return oc.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===_u.RECONNECTING)return void t.queuedRequests.push((()=>hc(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield wl(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new ro({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=xu(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=xu(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return hc(this,void 0,void 0,(function*(){if(this.state===_u.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=rl.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&rl.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=rl.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&rl.clearInterval(this.pingInterval)}}function xu(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Iu(e){return new fo({sdp:e.sdp,type:e.type})}var Ou,Au,Nu,Du,Mu,Lu={},Uu={},ju={exports:{}};function Fu(){if(Ou)return ju.exports;Ou=1;var e=ju.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),ju.exports}function Bu(){if(Du)return Nu;Du=1;var e=Fu(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var a=t.names[r];t.name?s.push(n[t.name][a]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Nu=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=i.outerOrder||s,o=i.innerOrder||r,c=[];return a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"}}var $u=function(){if(Mu)return Lu;Mu=1;var e=(Au||(Au=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Fu(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),a=r[r.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(s))return i(c,a,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Uu)),Uu),t=Bu(),i=Fu();return Lu.grammar=i,Lu.write=t,Lu.parse=e.parse,Lu.parseParams=e.parseParams,Lu.parseFmtpConfig=e.parseFmtpConfig,Lu.parsePayloads=e.parsePayloads,Lu.parseRemoteCandidates=e.parseRemoteCandidates,Lu.parseImageAttributes=e.parseImageAttributes,Lu.parseSimulcastStreamList=e.parseSimulcastStreamList,Lu}();function Vu(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var a=null!=(n=i.isImmediate)&&n,o=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=a&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!a){var t=e.apply(n,i);o&&o(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const qu="negotiationStarted",Zu="negotiationComplete",Ku="rtpVideoPayloadTypes";class zu extends fc.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=oc,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Vu((e=>hc(this,void 0,void 0,(function*(){this.emit(qu);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=cc(null!==(i=t.loggerName)&&void 0!==i?i:nc.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return hc(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return hc(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=$u.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=$u.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=$u.write(n)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(Zu),e.sdp)&&$u.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Ku,e.rtp)}))}))}createAndSendOffer(e){return hc(this,void 0,void 0,(function*(){var t;if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=$u.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{Gu(e),"audio"===e.type?Hu(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(Pl(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,$u.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return hc(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=$u.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Gu(e),"audio"===e.type&&Hu(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,$u.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Wd("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Wd("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return hc(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return hc(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Jd(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Cl)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Cl})}}}function Hu(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Gu(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Wu="vp8",Ju={audioPreset:yl.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Sl.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Wu,backupCodec:!0},Qu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Yu={deviceId:{ideal:"default"},resolution:kl.h720.resolution},Xu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:uc}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},eh={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var th,ih;(ih=th||(th={}))[ih.NEW=0]="NEW",ih[ih.CONNECTING=1]="CONNECTING",ih[ih.CONNECTED=2]="CONNECTED",ih[ih.FAILED=3]="FAILED",ih[ih.CLOSING=4]="CLOSING",ih[ih.CLOSED=5]="CLOSED";class nh{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=eh.peerConnectionTimeout,this.log=oc,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=th.CONNECTED:i.some((e=>"failed"===e))?this.state=th.FAILED:i.some((e=>"connecting"===e))?this.state=th.CONNECTING:i.every((e=>"closed"===e))?this.state=th.CLOSED:i.some((e=>"closed"===e))?this.state=th.CLOSING:i.every((e=>"new"===e))&&(this.state=th.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(th[t]," to ").concat(th[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=cc(null!==(n=i.loggerName)&&void 0!==n?n:nc.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new zu(e,i),this.subscriber=new zu(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,io.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,io.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=th.NEW,this.connectionLock=new _s,this.remoteOfferLock=new _s}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return hc(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return hc(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return hc(this,void 0,void 0,(function*(){t===io.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return hc(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return hc(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return hc(this,void 0,void 0,(function*(){return new Promise(((t,i)=>hc(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(qu,(()=>{e.signal.aborted||this.publisher.once(Zu,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===io.PUBLISHER||e===io.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return hc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>hc(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),rl.clearTimeout(r),s(new Kd("room connection has been cancelled",xd.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=rl.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new Kd("could not establish pc connection",xd.InternalError))}),n);for(;this.state!==th.CONNECTED;)if(yield wl(50),null==t?void 0:t.signal.aborted)return void s(new Kd("room connection has been cancelled",xd.Cancelled));rl.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class sh extends Error{constructor(e,t,i){super(t),this.code=e,this.message=ah(t,sh.MAX_MESSAGE_BYTES),this.data=i?ah(i,sh.MAX_DATA_BYTES):void 0}static fromProto(e){return new sh(e.code,e.message,e.data)}toProto(){return new Ba({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new sh(sh.ErrorCode[e],sh.ErrorMessage[e],t)}}function rh(e){return(new TextEncoder).encode(e).length}function ah(e,t){if(rh(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}sh.MAX_MESSAGE_BYTES=256,sh.MAX_DATA_BYTES=15360,sh.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},sh.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const oh=2e3;function ch(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class dh extends dl{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Vu((()=>hc(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>hc(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($d.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new _s,this.pauseUpstreamLock=new _s,this.processorLock=new _s,this.restartLock=new _s,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==dl.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return hc(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{ul(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ll(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{ll(null!=n?n:e,t)})))}))}waitForDimensions(){return hc(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===dl.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=tl())||void 0===i?void 0:i.os)&&(yield wl(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield wl(50)}throw new Hd("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return hc(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Wl(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Wl(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return hc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===dl.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===dl.Kind.Audio?"audioinput":"videoinput";return t?ku.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return hc(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return hc(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return hc(this,void 0,void 0,(function*(){if(!this.sender)throw new Hd("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return hc(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===dl.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{ul(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield r.applyConstraints(n),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit($d.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?$d.Muted:$d.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ol()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return hc(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit($d.UpstreamPaused,this);const t=tl();if("Safari"===(null==t?void 0:t.name)&&jl(t.version,"12.0")<0)throw new zd("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return hc(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit($d.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return hc(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ll(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(ul(t._mediaStreamTrack,e),ll(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit($d.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return hc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit($d.TrackProcessorUpdate))}()}))}}class lh extends dh{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,dl.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>hc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=ch(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit($d.AudioTrackFeatureUpdate,this,fa.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit($d.AudioTrackFeatureUpdate,this,fa.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return hc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===dl.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return hc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Wl(this._constraints.deviceId);return this.source!==dl.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return hc(this,void 0,void 0,(function*(){let t;if(e){const i=lu({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return hc(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Al()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),oh)))}setProcessor(e){return hc(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!Nl()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit($d.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return hc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return hc(this,void 0,void 0,(function*(){const e=yield function(e){return hc(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=uu();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield wl(t),n.getByteTimeDomainData(r);const a=r.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit($d.AudioSilenceDetected)),e}))}}const uh=Object.values(kl),hh=Object.values(Tl),ph=Object.values(Sl),mh=[kl.h180,kl.h360],gh=[Tl.h180,Tl.h360],fh=["q","h","f"];function vh(e,t,i,n){var s,r;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const o=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!a&&!o&&!c||!t||!i)return[{}];a||(a=function(e,t,i,n){const s=function(e,t,i){if(e)return ph;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?uh:hh}(e,t,i);let{encoding:r}=s[0];const a=Math.max(t,i);for(let o=0;o<s.length;o+=1){const e=s[o];if(r=e.encoding,e.width>=a)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),oc.debug("using video encoding",a));const l=a.maxFramerate,u=new hl(t,i,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Pl(d)){const e=new Th(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=tl();if(Il()||Nl()||"Chrome"===(null==i?void 0:i.name)&&jl(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:fh[2-n],maxBitrate:a.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),oc.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p=[];if(p=e?null!==(s=kh(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:yh(e,u):null!==(r=kh(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:yh(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return bh(t,i,[e,h,u],l);if(n>=480)return bh(t,i,[e,u],l)}return bh(t,i,[u])}function yh(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new hl(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?mh:gh}function bh(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=fh.length)return;const a=Math.min(e,t),o={rid:fh[r],scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);const d=xl()||0===r;i.encoding.priority&&d&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),s.push(o)})),Nl()&&"ios"===Ll()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,oc.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),oc.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function kh(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Th{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Sh extends dh{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,dl.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>hc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=ch(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new _s}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Al())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),oh))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return hc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=pc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return hc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=pc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return hc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==dl.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return hc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==dl.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return hc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=ol.LOW;i<=ol.HIGH;i+=1)t.push(new No({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return hc(this,void 0,void 0,(function*(){var t,i,n,s,r;let a;if(e){const t=lu({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a);try{for(var o,c=!0,d=pc(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){s=o.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return hc(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,a,o,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=pc(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(a=h.return)||(yield a.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return hc(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return hc(this,void 0,void 0,(function*(){var t,i,n,s,r,a,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=pc(e);!(s=(n=yield i.next()).done);t=!0){o=n.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Ch(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(a=i.return)||(yield a.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return hc(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Ch(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ol()&&this.isInBackground&&this.source===dl.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Ch(e,t,i,n,s,r){return hc(this,void 0,void 0,(function*(){const a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let o=!1;const c=tl();if("Chrome"===(null==c?void 0:c.name)&&jl(null==c?void 0:c.version,"133")>0&&a[0].scalabilityMode){const e=a[0],n=new Th(e.scalabilityMode);let s=la.OFF;if(i.forEach((e=>{e.enabled&&(s===la.OFF||e.quality>s)&&(s=e.quality)})),s===la.OFF)e.active&&(e.active=!1,o=!0);else if(!e.active||n.spatial!==s+1){o=!0,e.active=!0;const i=new Th(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else a.forEach(((e,n)=>{var a;let c=null!==(a=e.rid)&&void 0!==a?a:"";""===c&&(c="q");const d=wh(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(o=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),xl()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}));o&&(n.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function wh(e){switch(e){case"f":default:return ol.HIGH;case"h":return ol.MEDIUM;case"q":return ol.LOW}}function Eh(e,t,i,n){if(!i)return[new Pa({quality:ol.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Th(n),r=[],a="h"==s.suffix?1.5:2,o="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Pa({quality:Math.min(ol.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(a,c)),height:Math.ceil(t/Math.pow(a,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const a=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let o=wh(null!==(s=i.rid)&&void 0!==s?s:"");return new Pa({quality:o,width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const _h="_lossy",Ph="_reliable",Rh="leave-reconnect";var xh,Ih,Oh,Ah,Nh,Dh,Mh,Lh,Uh,jh,Fh;(Ih=xh||(xh={}))[Ih.New=0]="New",Ih[Ih.Connected=1]="Connected",Ih[Ih.Disconnected=2]="Disconnected",Ih[Ih.Reconnecting=3]="Reconnecting",Ih[Ih.Closed=4]="Closed";class Bh extends fc.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=eh.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=xh.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=oc,this.handleDataChannel=e=>hc(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Ph)t.reliableDCSub=i;else{if(i.label!==_h)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>hc(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=Ra.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(Fd.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(Fd.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?xa.LOSSY:xa.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===Rh&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=rl.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Fd.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===xh.Connected&&e();const i=()=>{this.off(Fd.Disconnected,n),e()},n=()=>{this.off(Fd.Restarted,i),t()};this.once(Fd.Restarted,i),this.once(Fd.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Fd.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===_u.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ma.RR_SIGNAL_DISCONNECTED))},this.log=cc(null!==(t=e.loggerName)&&void 0!==t?t:nc.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ru(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new _s,this.dataProcessLock=new _s,this.dcBufferStatus=new Map([[xa.LOSSY,!0],[xa.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Fd.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Fd.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Fd.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Fd.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Fd.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Fd.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Fd.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Fd.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,a,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(o=null===(a=this.latestJoinResponse)||void 0===a?void 0:a.participant)||void 0===o?void 0:o.sid}}join(e,t,i,n){return hc(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(Fd.SignalConnected)}),10),s}catch(s){if(s instanceof Kd&&s.reason===xd.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return hc(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Fd.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return hc(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return hc(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Hd("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new Kd("publication of local track timed out, no response from server",xd.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return hc(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return hc(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==th.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new nh(n,e.subscriberPrimary,this.loggerOptions),this.emit(Fd.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>hc(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===th.CONNECTED){const t=this.pcState===xh.New;this.pcState=xh.Connected,t&&this.emit(Fd.Connected,e)}else t===th.FAILED&&this.pcState===xh.Connected&&(this.pcState=xh.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?ma.RR_SUBSCRIBER_FAILED:ma.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===_u.RECONNECTING,r=[th.FAILED,th.CLOSING,th.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(Fd.Offline)})),this.pcManager.onTrack=e=>{this.emit(Fd.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>hc(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>hc(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Fd.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Fd.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Fd.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Fd.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ma.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Co.DISCONNECT:this.emit(Fd.Disconnected,null==e?void 0:e.reason),this.close();break;case Co.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Rh);break;case Co.RESUME:this.handleDisconnect(Rh)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ha.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(_h,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ph,{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)}createSender(e,t,i){return hc(this,void 0,void 0,(function*(){if(El())return yield this.createTransceiverRTCRtpSender(e,t,i);if(_l())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Wd("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return hc(this,void 0,void 0,(function*(){if(El())return this.createSimulcastTransceiverSender(e,t,i,n);if(_l())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Wd("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return hc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Wd("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),iu(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return hc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Wd("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return hc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Wd("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return hc(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)oc.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==ha.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:th.NEW)!==th.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof Wd?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof $h||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",ma.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Fd.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return hc(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new Wd("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Fd.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new $h;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof Kd&&s.reason===xd.NotAllowed)throw new Wd("could not reconnect, token might be expired");throw new $h}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Fd.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==_u.CONNECTED)throw new $h("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Fd.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return hc(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new Wd("could not reconnect, url or token not saved");if(!this.pcManager)throw new Wd("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Fd.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof Kd&&n.reason===xd.NotAllowed)throw new Wd("could not reconnect, token might be expired");if(n instanceof Kd&&n.reason===xd.LeaveRequest)throw n;throw new $h(e)}if(this.emit(Fd.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==_u.CONNECTED)throw new $h("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Fd.Resumed)}))}waitForPCInitialConnection(e,t){return hc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Wd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return hc(this,void 0,void 0,(function*(){this.pcState=xh.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield wl(2e3),!this.pcManager)throw new Wd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=xh.Connected}catch(e){throw this.pcState=xh.Disconnected,new Kd("could not establish PC connection, ".concat(e.message),xd.InternalError)}}))}publishRpcResponse(e,t,i,n){return hc(this,void 0,void 0,(function*(){const s=new Ra({destinationIdentities:[e],kind:xa.RELIABLE,value:{case:"rpcResponse",value:new Fa({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,xa.RELIABLE)}))}publishRpcAck(e,t){return hc(this,void 0,void 0,(function*(){const i=new Ra({destinationIdentities:[e],kind:xa.RELIABLE,value:{case:"rpcAck",value:new ja({requestId:t})}});yield this.sendDataPacket(i,xa.RELIABLE)}))}sendDataPacket(e,t){return hc(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>hc(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(Fd.Closing,n);!this.dcBufferStatus.get(e);)yield wl(10);this.off(Fd.Closing,n),t()}}))))}ensureDataTransportConnected(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new Wd("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new Kd("".concat(r," connection not set"),xd.InternalError);let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate();const o=t.dataChannelForKind(e,i);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield wl(50)}throw new Kd("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),xd.InternalError)}()}))}ensurePublisherConnected(e){return hc(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===th.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return hc(this,void 0,void 0,(function*(){return new Promise(((e,t)=>hc(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new Jd("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Fd.Closing,n),this.pcManager.publisher.once(Ku,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,ml.includes(n)&&t.set(e.payload,i)})),this.emit(Fd.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Jd&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ma.RR_UNKNOWN),t(s)}finally{this.off(Fd.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===xa.LOSSY)return this.lossyDCSub;if(e===xa.RELIABLE)return this.reliableDCSub}else{if(e===xa.LOSSY)return this.lossyDC;if(e===xa.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),a=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,o=new Array,c=new Array;e.forEach((e=>{e.isDesired!==a&&o.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Fo({answer:s?Iu({sdp:s.sdp,type:s.type}):void 0,offer:r?Iu({sdp:r.sdp,type:r.type}):void 0,subscription:new yo({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:gu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Bo({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(xa.LOSSY),io.PUBLISHER),t(this.dataChannelForKind(xa.RELIABLE),io.PUBLISHER),t(this.dataChannelForKind(xa.LOSSY,!0),io.SUBSCRIBER),t(this.dataChannelForKind(xa.RELIABLE,!0),io.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&rl.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Al()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Al()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class $h extends Error{}class Vh{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 Dl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return hc(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((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),oc.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return hc(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new Kd("Could not fetch region settings: ".concat(t.statusText),401===t.status?xd.NotAllowed:xd.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class qh{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Zh extends qh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>hc(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return hc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return hc(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,a=!0,o=pc(this);!(e=(r=yield o.next()).done);a=!0){n=r.value,a=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)}))}}class Kh extends qh{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Yl(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>hc(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return hc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return hc(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,a=!0,o=pc(this);!(e=(r=yield o.next()).done);a=!0)n=r.value,a=!1,s+=n}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return s}))}}class zh{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return hc(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Hh extends zh{}class Gh extends zh{}class Wh extends dl{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?$d.Muted:$d.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit($d.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return hc(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),oh)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit($d.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Jh extends Wh{constructor(e,t,i,n,s,r){super(e,t,dl.Kind.Audio,i,r),this.monitorReceiver=()=>hc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ch(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Nl()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Nl())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return hc(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Rl(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Rl(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit($d.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit($d.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return hc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Qh extends Wh{constructor(e,t,i,n,s){super(e,t,dl.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>hc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ch(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Vu((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?ul(this._mediaStreamTrack,t):ll(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new Yh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return hc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?rl.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit($d.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit($d.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?Ul():t||(Ul()>2?2:1)}}class Yh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Xh(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Xh(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Xh(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ep(e),this.isPiP=Al()&&Xh(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ep(this.element),this.isPiP=Xh(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Zl().observe(this.element),Vl().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Zl())||void 0===e||e.unobserve(this.element),null===(t=Vl())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Xh(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&ep(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function ep(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&s+r>i.pageXOffset&&!o&&"none"!==c}class tp extends fc.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=wa.NONE,this.log=oc,this.handleMuted=()=>{this.emit($d.Muted)},this.handleUnmuted=()=>{this.emit($d.Unmuted)},this.log=cc(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:nc.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=dl.Source.Unknown}setTrack(e){this.track&&(this.track.off($d.Muted,this.handleMuted),this.track.off($d.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on($d.Muted,this.handleMuted),e.on($d.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),fu(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==wa.NONE}get audioTrack(){if(tu(this.track))return this.track}get videoTrack(){if(iu(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=dl.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===dl.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(Ah=(Oh=tp||(tp={})).SubscriptionStatus||(Oh.SubscriptionStatus={})).Desired="desired",Ah.Subscribed="subscribed",Ah.Unsubscribed="unsubscribed",(Nh=Oh.PermissionStatus||(Oh.PermissionStatus={})).Allowed="allowed",Nh.NotAllowed="not_allowed";class ip extends tp{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit($d.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off($d.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on($d.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return hc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return hc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return hc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return hc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(tu(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(fa.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(fa.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(fa.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(fa.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(fa.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(fa.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function np(e,t){return hc(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=vu(e);let a=r.audio,o=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=cu(r,Qu,Yu),d=lu(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ku.userMediaPromiseMap.set("audioinput",l),l.catch((()=>ku.userMediaPromiseMap.delete("audioinput")))),r.video&&(ku.userMediaPromiseMap.set("videoinput",l),l.catch((()=>ku.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>hc(this,void 0,void 0,(function*(){const r="audio"===i.kind;let a,o=r?c.audio:c.video;"boolean"!=typeof o&&o||(o={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(a=l);const u=i.getSettings().deviceId;(null==a?void 0:a.deviceId)&&Wl(a.deviceId)!==u?a.deviceId=u:a||(a={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new lh(e,t,!1,void 0,i);case"video":return new Sh(e,t,!1,i);default:throw new Hd("unsupported track type: ".concat(e.kind))}}(i,a,t);return h.kind===dl.Kind.Video?h.source=dl.Source.Camera:h.kind===dl.Kind.Audio&&(h.source=dl.Source.Microphone),h.mediaStream=e,tu(h)&&n?yield h.setProcessor(n):iu(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return np(Object.assign(Object.assign({},e),{audio:a,video:o}),t)}}))}(Mh=Dh||(Dh={})).Excellent="excellent",Mh.Good="good",Mh.Poor="poor",Mh.Lost="lost",Mh.Unknown="unknown";class sp extends fc.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===Sa.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Sa.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Dh.Unknown,this.log=oc,this.log=cc(null!==(o=null==r?void 0:r.loggerName)&&void 0!==o?o:nc.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(dl.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(dl.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(dl.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(Ud.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(Ud.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(Ud.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,a;const o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(Ud.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Ud.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ua.EXCELLENT:return Dh.Excellent;case ua.GOOD:return Dh.Good;case ua.POOR:return Dh.Poor;case ua.LOST:return Dh.Lost;default:return Dh.Unknown}}(e),t!==this._connectionQuality&&this.emit(Ud.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>tu(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on($d.Muted,(()=>{this.emit(Ud.TrackMuted,e)})),e.on($d.Unmuted,(()=>{this.emit(Ud.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case dl.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case dl.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class rp extends sp{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=wa.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Gl)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Go.OK&&s.reject(new Yd(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=sh.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Lo({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),fu(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),fu(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),fu(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>hc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(o)if(e.subscribedCodecs.length>0){if(!o.videoTrack)return;const r=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=pc(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;gl(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),fu(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(a=o.videoTrack)||void 0===a?void 0:a.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>hc(this,void 0,void 0,(function*(){if(e.source===dl.Source.ScreenShare||e.source===dl.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),fu(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(su(e)||nu(e))try{if(Al())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===dl.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),fu(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),fu(e))),su(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),fu(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==wa.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Fd.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(Fd.Connected,this.handleReconnected).on(Fd.SignalRestarted,this.handleReconnected).on(Fd.SignalResumed,this.handleReconnected).on(Fd.Restarting,this.handleReconnecting).on(Fd.Resuming,this.handleReconnecting).on(Fd.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Fd.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Fd.Disconnected,this.handleDisconnected).on(Fd.SignalRequestResponse,this.handleSignalRequestResponse).on(Fd.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return hc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return hc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return hc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return hc(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>hc(t,void 0,void 0,(function*(){var t,a;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(a=null!=n?n:this.name)&&void 0!==a?a:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),o=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield wl(50)}r(new Yd("Request to update local metadata timed out","TimeoutError"))}catch(o){o instanceof Error&&r(o)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(dl.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(dl.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(dl.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Ud.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return hc(this,void 0,void 0,(function*(){this.encryptionType=e?wa.GCM:wa.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return hc(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case dl.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case dl.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case dl.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Hd(e)}}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o instanceof Error&&this.emit(Ud.MediaDevicesError,o),this.pendingPublishing.delete(e),o}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),fu(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[a]=i}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===dl.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(dl.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return hc(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(dl.Source.Camera)&&!this.pendingPublishing.has(dl.Source.Microphone)){this.pendingPublishing.add(dl.Source.Camera),this.pendingPublishing.add(dl.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(dl.Source.Camera),this.pendingPublishing.delete(dl.Source.Microphone)}}}))}createTracks(e){return hc(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=cu(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield np(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(tu(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=dl.Source.Microphone,this.emit(Ud.AudioStreamAcquired)),iu(e)&&(this.cameraError=void 0,e.source=dl.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return hc(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new zd("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=tl();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=Sl.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=Il()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Hd("no video track found");const s=new Sh(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=dl.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(Ud.AudioStreamAcquired);const e=new lh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=dl.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return hc(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return hc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,a,o;let c,d;if(su(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),eu(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case dl.Source.Microphone:t="audioinput";break;case dl.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new lh(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Sh(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Hd("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),fu(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),fu(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(a=t.dtx)&&void 0!==a||(t.dtx=!1),null!==(o=t.red)&&void 0!==o||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=tl(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&jl(t,e.osVersion)>=0)||"Safari"===e.name&&jl(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>hc(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==_u.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:fu(e)}));const i=()=>hc(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(Fd.SignalConnected,i),n(new Qd("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(Fd.SignalConnected,i),this.engine.on(Fd.Closing,(()=>{this.engine.off(Fd.SignalConnected,i),n(new Qd("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),fu(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case da.CAMERA:return dl.Source.Camera;case da.MICROPHONE:return dl.Source.Microphone;case da.SCREEN_SHARE:return dl.Source.ScreenShare;case da.SCREEN_SHARE_AUDIO:return dl.Source.ScreenShareAudio;default:return dl.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),fu(e))),!1)}publish(e,t,i){return hc(this,void 0,void 0,(function*(){var n,s,r,a,o,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Qd("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>eu(e)&&t.source===e.source))&&e.source!==dl.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),fu(e))),t.stopMicTrackOnMute&&tu(e)&&(e.stopOnMute=!0),e.source===dl.Source.ScreenShare&&xl()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Il())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(xl())return!1;if(Il()){const e=tl();if((null==e?void 0:e.version)&&jl(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Wu),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===mu(e.mime)))||(t.videoCodec=mu(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on($d.Muted,this.onTrackMuted),e.on($d.Unmuted,this.onTrackUnmuted),e.on($d.Ended,this.handleTrackEnded),e.on($d.UpstreamPaused,this.onTrackUpstreamPaused),e.on($d.UpstreamResumed,this.onTrackUpstreamResumed),e.on($d.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new co({cid:e.mediaStreamTrack.id,name:t.name,type:dl.kindToProto(e.kind),muted:e.isMuted,source:dl.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===dl.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(a=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==a?a:kl.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),fu(e)),{dims:i}))}m.width=i.width,m.height=i.height,nu(e)&&(Pl(p)&&(e.source===dl.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),fu(e))))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),m.simulcastCodecs=[new oo({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Wu}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===wa.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new oo({codec:t.backupCodec.codec,cid:""})))),g=vh(e.source===dl.Source.ScreenShare,m.width,m.height,t),m.layers=Eh(m.width,m.height,g,Pl(t.videoCodec))}else e.kind===dl.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Wd("cannot publish track when not connected");const f=()=>hc(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Wd("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),nu(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===dl.Source.ScreenShare||e.constraints.height&&Wl(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if(xl()&&e.kind===dl.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&Pl(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===dl.Kind.Video){const n=mu(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),fu(e)),{codec:n})),t.videoCodec=n,g=vh(e.source===dl.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new ip(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),nu(e)?e.startMonitor(this.engine.client):su(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(Ud.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return hc(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==wa.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Hd("track is not published");if(!nu(e))throw new Hd("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=function(e,t,i){var n,s,r,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&oc.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=o.height)&&void 0!==r?r:null===(a=e.dimensions)||void 0===a?void 0:a.height;return e.source===dl.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),vh(e.source===dl.Source.ScreenShare,c,d,i)}(e,t,r);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),fu(e)));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=new co({cid:o.mediaStreamTrack.id,type:dl.kindToProto(e.kind),muted:e.isMuted,source:dl.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=Eh(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new Wd("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>hc(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,r,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))}))}unpublishTrack(e,t){return hc(this,void 0,void 0,(function*(){var i,n;if(eu(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),fu(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?fu(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off($d.Muted,this.onTrackMuted),e.off($d.Unmuted,this.onTrackUnmuted),e.off($d.Ended,this.handleTrackEnded),e.off($d.UpstreamPaused,this.onTrackUpstreamPaused),e.off($d.UpstreamResumed,this.onTrackUpstreamResumed),e.off($d.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<th.FAILED&&o)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),nu(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case dl.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case dl.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(Ud.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return hc(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>hc(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>hc(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===dl.Source.ScreenShare||t.source===dl.Source.ScreenShareAudio||!su(t)&&!nu(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return hc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?xa.RELIABLE:xa.LOSSY,s=i.destinationIdentities,r=i.topic,a=new Ra({kind:n,value:{case:"user",value:new Aa({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(a,n)}()}))}publishDtmf(e,t){return hc(this,void 0,void 0,(function*(){const i=new Ra({kind:xa.RELIABLE,value:{case:"sipDtmf",value:new Na({code:e,digit:t})}});yield this.engine.sendDataPacket(i,xa.RELIABLE)}))}sendChatMessage(e,t){return hc(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new Ra({value:{case:"chatMessage",value:new La(Object.assign(Object.assign({},i),{timestamp:zs.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,xa.RELIABLE),this.emit(Ud.ChatMessage,i),i}))}editChatMessage(e,t){return hc(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Ra({value:{case:"chatMessage",value:new La(Object.assign(Object.assign({},i),{timestamp:zs.parse(i.timestamp),editTimestamp:zs.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,xa.RELIABLE),this.emit(Ud.ChatMessage,i),i}))}sendText(e,t){return hc(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),a=new Array(r?r.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;const s=a.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map(((e,i)=>hc(this,void 0,void 0,(function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))))),c.info}))}streamText(e){return hc(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new Xa({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:Xl(s.timestamp),totalLength:Xl(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Qa({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Ja.UPDATE:Ja.CREATE})}}),a=null==e?void 0:e.destinationIdentities,o=new Ra({destinationIdentities:a,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(o,xa.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return hc(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow(xa.RELIABLE);const e=new eo({content:t,streamId:n,chunkIndex:Xl(c)}),i=new Ra({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,xa.RELIABLE),c+=1}}))},close(){return hc(this,void 0,void 0,(function*(){const e=new to({streamId:n}),t=new Ra({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,xa.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>hc(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(Fd.Closing,u);const h=new Hh(l,s,(()=>this.engine.off(Fd.Closing,u)));return h}))}sendFile(e,t){return hc(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return hc(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return hc(this,void 0,void 0,(function*(){var t,i,n,s,r;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new Xa({totalLength:Xl(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:Xl(Date.now()),contentHeader:{case:"byteHeader",value:new Ya({name:c.name})}}),l=new Ra({destinationIdentities:o,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,xa.RELIABLE);let u=0;const h=new _s,p=this.engine,m=this.log,g=new WritableStream({write(e){return hc(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow(xa.RELIABLE);const n=new Ra({destinationIdentities:o,value:{case:"streamChunk",value:new eo({content:t,streamId:a,chunkIndex:Xl(u)})}});yield p.sendDataPacket(n,xa.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return hc(this,void 0,void 0,(function*(){const e=new to({streamId:a}),t=new Ra({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,xa.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new Gh(g,c)}))}performRpc(e){return hc(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,a)=>hc(t,void 0,void 0,(function*(){var t,o,c,d;if(rh(s)>15360)return void a(sh.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(o=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===o?void 0:o.version)&&jl(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void a(sh.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),a(sh.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),a(sh.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?a(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return hc(this,void 0,void 0,(function*(){const r=new Ra({destinationIdentities:[e],kind:xa.RELIABLE,value:{case:"rpcRequest",value:new Ua({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,xa.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,sh.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),fu(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(su(n)||nu(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return hc(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield wl(20)}}))}}class ap extends tp{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ol.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit($d.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new yo({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $a({participantSid:"",trackSids:[this.trackSid]})]});this.emit($d.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?tp.SubscriptionStatus.Unsubscribed:super.isSubscribed?tp.SubscriptionStatus.Subscribed:tp.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?tp.PermissionStatus.Allowed:tp.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}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,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(ou(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ou(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off($d.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off($d.VisibilityChanged,this.handleVisibilityChange),n.off($d.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit($d.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on($d.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on($d.VisibilityChanged,this.handleVisibilityChange),e.on($d.Ended,this.handleEnded),this.emit($d.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit($d.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?$d.Muted:$d.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit($d.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit($d.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===dl.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ou(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new bo({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)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=ol.HIGH,this.emit($d.UpdateSettings,e)}}class op extends sp{static fromParticipantInfo(e,t,i){return new op(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,a){super(t,i||"",n,s,r,a,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Sa.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on($d.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),fu(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on($d.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on($d.SubscriptionPermissionChanged,(t=>{this.emit(Ud.TrackSubscriptionPermissionChanged,e,t)})),e.on($d.SubscriptionStatusChanged,(t=>{this.emit(Ud.TrackSubscriptionStatusChanged,e,t)})),e.on($d.Subscribed,(t=>{this.emit(Ud.TrackSubscribed,t,e)})),e.on($d.Unsubscribed,(t=>{this.emit(Ud.TrackUnsubscribed,t,e)})),e.on($d.SubscriptionFailed,(t=>{this.emit(Ud.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dl.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dl.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let a,o=this.getTrackPublicationBySid(t);return o||t.startsWith("TR")||this.trackPublications.forEach((t=>{o||e.kind!==t.kind.toString()||(o=t)})),o?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),fu(o))),void this.emit(Ud.TrackSubscriptionFailed,t)):(a="video"===e.kind?new Qh(e,t,n,s):new Jh(e,t,n,this.audioContext,this.audioOutput),a.source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&ru(a)&&tu(a)&&a.setVolume(this.volumeMap.get(o.source)),o):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(Ud.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=dl.kindFromProto(e.type);if(!t)return;r=new ap(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));a&&r.source!==dl.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:fu(a),newTrack:fu(r)})),this.addTrackPublication(r)}t.set(e.sid,r)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),fu(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Ud.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case dl.Kind.Audio:this.audioTrackPublications.delete(e);break;case dl.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(Ud.TrackUnpublished,i)}setAudioOutput(e){return hc(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;tu(i.track)&&ru(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(Uh=Lh||(Lh={})).Disconnected="disconnected",Uh.Connecting="connecting",Uh.Connected="connected",Uh.Reconnecting="reconnecting",Uh.SignalReconnecting="signalReconnecting";class cp extends fc.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=Lh.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=oc,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>hc(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!El()&&!_l())throw Nl()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===Lh.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Lh.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Dl(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Vh(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,a,o)=>hc(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=o?o:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof Kd&&u.reason!==xd.Cancelled&&u.reason!==xd.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof Kd&&(401===h.status||h.reason===xd.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,a,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ql(u)),a(u))}else{let e=pa.UNKNOWN_REASON;u instanceof Kd&&(e=Ql(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(u)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Gl(((e,t)=>{r(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>hc(this,void 0,void 0,(function*(){var a,o,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(a=d.room)||void 0===a?void 0:a.name,roomSid:null===(o=d.room)||void 0===o?void 0:o.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Gd("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>hc(this,void 0,void 0,(function*(){var s,r;this.state===Lh.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},eh),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Md.SignalConnected)}catch(a){yield this.engine.close(),this.recreateEngine();const e=new Kd("could not establish signal connection",xd.ServerUnreachable);throw a instanceof Error&&(e.message="".concat(e.message,": ").concat(a.message)),a instanceof Kd&&(e.reason=a.reason,e.status=a.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:a})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Kd("Connection attempt aborted",xd.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(o){throw yield this.engine.close(),this.recreateEngine(),o}Al()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Al()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Lh.Connected),this.emit(Md.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return hc(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const a=yield e.disconnectLock.lock();try{if(e.state===Lh.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===Lh.Connecting||e.state===Lh.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Kd("Client initiated disconnect",xd.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,pa.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>hc(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>hc(this,void 0,void 0,(function*(){const e=[],t=tl();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Hl();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(Md.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>hc(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Lh.Reconnecting)&&this.emit(Md.Reconnecting)},this.handleSignalRestarted=e=>hc(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(Lh.Connected),this.emit(Md.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Ta.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Md.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Md.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=dl.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(Ud.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Md.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(Md.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(Ud.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(Md.SipDTMFReceived,t,e),null==e||e.emit(Ud.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:a,final:o}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(a.toString()),final:o,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit($d.TranscriptionReceived,s),null==i||i.emit(Ud.TranscriptionReceived,s,n),this.emit(Md.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Md.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Md.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Md.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Md.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Md.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Md.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>hc(this,void 0,void 0,(function*(){var e,t,i;const n=ku.getInstance().previousDevices,s=yield ku.getInstance().getDevices(void 0,!1),r=tl();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let o of s){const e=n.find((e=>e.deviceId===o.deviceId));e&&""!==e.label&&e.kind===o.kind&&e.label!==o.label&&"default"===this.getActiveDevice(o.kind)&&this.emit(Md.ActiveDeviceChanged,o.kind,o.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let o of a){const r=hu(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===o)),d=this.getActiveDevice(o);d===(null===(t=n.filter((e=>e.kind===o))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!Il()||"videoinput"===o||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(o)))&&(yield this.switchActiveDevice(o,c[0].deviceId))}this.emit(Md.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Md.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Md.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Md.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Md.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Md.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Md.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Md.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>hc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;null===(t=e.track)||void 0===t||t.on($d.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on($d.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Md.LocalTrackPublished,e,this.localParticipant),su(e.track)&&(yield e.track.checkForSilence())&&this.emit(Md.LocalAudioSilenceDetected,e);const o=yield null===(a=e.track)||void 0===a?void 0:a.getDeviceId(!1),c=pu(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(Md.ActiveDeviceChanged,c,o))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off($d.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off($d.Restarted,this.onLocalTrackRestarted),this.emit(Md.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>hc(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=pu(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(Md.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(Md.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Md.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Md.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Md.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Xu),e),this.log=cc(null!==(i=this.options.loggerName)&&void 0!==i?i:nc.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Qu),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Yu),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ju),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new _s,this.localParticipant=new rp("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Wl(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Wl(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Wl(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),Al()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),cp.cleanupRegistry&&cp.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,r){return hc(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,sh.builtIn("UNSUPPORTED_VERSION")));const a=this.rpcHandlers.get(i);if(!a)return void(yield this.engine.publishRpcResponse(e,t,null,sh.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{const r=yield a({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});rh(r)>15360?(o=sh.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof sh?o=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),o=sh.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)}))}setE2EEEnabled(e){return hc(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new yu(this.options.e2ee),this.e2eeManager.on(_d.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Md.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(_d.EncryptionError,(e=>this.emit(Md.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return hc(this,void 0,void 0,(function*(){return this.state===Lh.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Fd.RoomUpdate,i),e(t.sid))};this.engine.on(Fd.RoomUpdate,i),this.once(Md.Disconnected,(()=>{this.engine.off(Fd.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Bh(this.options),this.engine.on(Fd.ParticipantUpdate,this.handleParticipantUpdates).on(Fd.RoomUpdate,this.handleRoomUpdate).on(Fd.SpeakersChanged,this.handleSpeakersChanged).on(Fd.StreamStateChanged,this.handleStreamStateUpdate).on(Fd.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Fd.SubscriptionError,this.handleSubscriptionError).on(Fd.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Fd.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Fd.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Fd.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Fd.DataPacketReceived,this.handleDataPacket).on(Fd.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Lh.SignalReconnecting)&&this.emit(Md.SignalReconnecting)})).on(Fd.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Lh.Connected)&&this.emit(Md.Reconnected)})).on(Fd.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Lh.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Fd.Restarting,this.handleRestarting).on(Fd.SignalRestarted,this.handleSignalRestarted).on(Fd.Offline,(()=>{this.setAndEmitConnectionState(Lh.Reconnecting)&&this.emit(Md.Reconnecting)})).on(Fd.DCBufferStatusChanged,((e,t)=>{this.emit(Md.DCBufferStatusChanged,e,t)})).on(Fd.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(Ud.LocalTrackSubscribed,t),this.emitWhenConnected(Md.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ku.getInstance().getDevices(e,t)}prepareConnection(e,t){return hc(this,void 0,void 0,(function*(){if(this.state===Lh.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Dl(new URL(e))&&t){this.regionUrlProvider=new Vh(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Lh.Disconnected&&(this.regionUrl=i,yield fetch(Jl(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Jl(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return hc(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new $o({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new $o({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new $o({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new $o({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>hc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new $o({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>hc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new $o({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new $o({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>hc(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new So({reason:pa.CLIENT_INITIATED,action:Co.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new $o({scenario:{case:"subscriberBandwidth",value:Xl(t)}});break;case"leave-full-reconnect":i=new $o({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return hc(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,a,o,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===dl.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===dl.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!Rl()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(a=yield ku.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==a?a:""),null!==(o=(u=i.options).audioOutput)&&void 0!==o||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(Md.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(Ud.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Ud.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Ud.AttributesChanged,this.onLocalAttributesChanged).on(Ud.TrackMuted,this.onLocalTrackMuted).on(Ud.TrackUnmuted,this.onLocalTrackUnmuted).on(Ud.LocalTrackPublished,this.onLocalTrackPublished).on(Ud.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Ud.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Ud.MediaDevicesError,this.onMediaDevicesError).on(Ud.AudioStreamAcquired,this.startAudio).on(Ud.ChatMessage,this.onLocalChatMessageSent).on(Ud.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Lh.Connecting||this.state===Lh.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Md.Reconnected,n),this.off(Md.Connected,n),this.off(Md.Disconnected,s)};return this.once(Md.Reconnected,n),this.once(Md.Connected,n),void this.once(Md.Disconnected,s)}if(this.state===Lh.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],a=e.id;if(r&&r.startsWith("TR")&&(a=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const o=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!o)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),o.addSubscribedMediaTrack(e,a,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Lh.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(Ud.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Ud.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Ud.AttributesChanged,this.onLocalAttributesChanged).off(Ud.TrackMuted,this.onLocalTrackMuted).off(Ud.TrackUnmuted,this.onLocalTrackUnmuted).off(Ud.LocalTrackPublished,this.onLocalTrackPublished).off(Ud.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Ud.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Ud.MediaDevicesError,this.onMediaDevicesError).off(Ud.AudioStreamAcquired,this.startAudio).off(Ud.ChatMessage,this.onLocalChatMessageSent).off(Ud.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Al()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Lh.Disconnected),this.emit(Md.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Md.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return hc(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Yl(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new Zh(r,a,Yl(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new Kh(s,r,Yl(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return hc(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=uu())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),wl(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Md.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?op.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new op(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Md.ParticipantConnected,i),i.on(Ud.TrackPublished,(e=>{this.emitWhenConnected(Md.TrackPublished,e,i)})).on(Ud.TrackSubscribed,((e,t)=>{e.kind===dl.Kind.Audio?(e.on($d.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on($d.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===dl.Kind.Video&&(e.on($d.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on($d.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Md.TrackSubscribed,e,t,i)})).on(Ud.TrackUnpublished,(e=>{this.emit(Md.TrackUnpublished,e,i)})).on(Ud.TrackUnsubscribed,((e,t)=>{this.emit(Md.TrackUnsubscribed,e,t,i)})).on(Ud.TrackMuted,(e=>{this.emitWhenConnected(Md.TrackMuted,e,i)})).on(Ud.TrackUnmuted,(e=>{this.emitWhenConnected(Md.TrackUnmuted,e,i)})).on(Ud.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Md.ParticipantMetadataChanged,e,i)})).on(Ud.ParticipantNameChanged,(e=>{this.emitWhenConnected(Md.ParticipantNameChanged,e,i)})).on(Ud.AttributesChanged,(e=>{this.emitWhenConnected(Md.ParticipantAttributesChanged,e,i)})).on(Ud.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Md.ConnectionQualityChanged,e,i)})).on(Ud.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Md.ParticipantPermissionsChanged,e,i)})).on(Ud.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Md.TrackSubscriptionStatusChanged,e,t,i)})).on(Ud.TrackSubscriptionFailed,((e,t)=>{this.emit(Md.TrackSubscriptionFailed,e,i,t)})).on(Ud.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Md.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&au(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=rl.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,pa.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&rl.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Md.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Lh.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Lh.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return hc(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new va({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:zs.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ka({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Md.SignalConnected),this.emit(Md.Connected),this.setAndEmitConnectionState(Lh.Connected),n.video){const e=new ip(dl.Kind.Video,new _a({source:da.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ca.AUDIO,name:"video-dummy"}),new Sh(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kl(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Ud.LocalTrackPublished,e)}if(n.audio){const e=new ip(dl.Kind.Audio,new _a({source:da.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ca.AUDIO}),new lh(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Hl(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Ud.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new ka({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Ta.ACTIVE,tracks:[],joinedAt:zs.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Kl(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),a=new _a({source:da.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ca.AUDIO});n.addSubscribedMediaTrack(r,a.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){const e=Hl(),i=new _a({source:da.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ca.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Md.ActiveSpeakersChanged&&e!==Md.TranscriptionReceived){const t=dp(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function dp(e){return e.map((e=>{if(e)return Array.isArray(e)?dp(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}cp.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(Fh=jh||(jh={}))[Fh.IDLE=0]="IDLE",Fh[Fh.RUNNING=1]="RUNNING",Fh[Fh.SKIPPED=2]="SKIPPED",Fh[Fh.SUCCESS=3]="SUCCESS",Fh[Fh.FAILED=4]="FAILED",fc.EventEmitter,fc.EventEmitter;const lp=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:class{constructor(e={}){this.currentState=Rn.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Ss(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token)return console.error("No token found"),void this.emitter.emit("error",{session:this,error:new Error("No session token provided")});await this.requestMicrophone();try{this.room=new cp({adaptiveStream:!0,dynacast:!0}),this.room.on(Md.LocalTrackUnpublished,(e=>{console.log("Local track unpublished",e.source),e.source===dl.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(Md.Disconnected,(()=>{console.log("LiveKit room disconnected"),this.disconnect()})),this.room.on(Md.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(Md.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===dl.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(Md.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===Rn.RESEARCHING||this.currentState===Rn.PAUSED)return;const t=Ge(e["lk.agent.state"]).with("listening",(()=>Rn.USER_SPEAKING)).with("speaking",(()=>Rn.AGENT_SPEAKING)).with("thinking",(()=>Rn.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(Md.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));Ge(t.status||t.request).with("using_tool",(()=>{const e=this.currentState;this.currentState=Rn.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("using_tool_ended",(()=>{const e=this.currentState;this.currentState=Rn.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{session:this})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}}));const e=`${this.apiBaseUrl}/join-token?token=${this.token}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:dl.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(Rn.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(Rn.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(Rn.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===Rn.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===Rn.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to LiveKit room")}}},Symbol.toStringTag,{value:"Module"}));return e.EventType=Pn,e.ObiAssistant=class{static init(e){customElements.get("obi-widget")||customElements.define("obi-widget",Ts);const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}},e.ObiSDK=class{constructor(e={}){this.state=Rn.READY,this.emitter=Ss(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=_n.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(Rn.READY),this.emitter.emit(Pn.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(Pn.STATE_CHANGE,e)}handleError(e){this.setState(Rn.ERROR),this.emitter.emit(Pn.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(this.voiceEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}else this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"})}async stopVoiceRecording(){if(this.state===Rn.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(Rn.READY),this.emitter.emit(Pn.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(this.screenCaptureEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}else this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"})}async stopScreenCapture(){if(this.state===Rn.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(Rn.READY),this.emitter.emit(Pn.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}},e.ObiWidget=Ts,e.SDKState=Rn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
557
+ `,up([he()],hp.prototype,"apiKey",2),up([he()],hp.prototype,"isActive",2),up([he()],hp.prototype,"position",2),up([he()],hp.prototype,"user",2),up([he()],hp.prototype,"state",2),up([he()],hp.prototype,"storedActiveState",2),up([he()],hp.prototype,"showCourseModal",2),up([he()],hp.prototype,"isHovering",2),up([he()],hp.prototype,"navVisible",2),up([he()],hp.prototype,"activeSession",2),up([he()],hp.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",hp),customElements.get("obi-widget")||customElements.define("obi-widget",hp),function(){if(!document.querySelector("obi-widget")){const e=document.createElement("obi-widget");document.body.appendChild(e),console.log("Obi Widget mounted")}}(),function(){const e=window;e.ObiSDK&&Array.isArray(e.ObiSDK.q)&&(e.ObiSDK.q.forEach((t=>{const[i,n]=t;"update"===i&&n&&(e.obiWidgetConfig={...e.obiWidgetConfig,...n})})),e.ObiSDK.q=[])}(),e.EventType=gh,e.ObiWidget=hp,e.SDKState=fh,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
531
558
  //# sourceMappingURL=obi-sdk.standalone.iife.js.map