hanc-webrtc-widgets 2.1.1 → 2.1.2

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,34 +1,34 @@
1
- (function(ot,Ri){typeof exports=="object"&&typeof module<"u"?Ri(exports):typeof define=="function"&&define.amd?define(["exports"],Ri):(ot=typeof globalThis<"u"?globalThis:ot||self,Ri(ot.HancWebrtcWidgets={}))})(this,(function(ot){"use strict";/**
1
+ (function(_t,Ri){typeof exports=="object"&&typeof module<"u"?Ri(exports):typeof define=="function"&&define.amd?define(["exports"],Ri):(_t=typeof globalThis<"u"?globalThis:_t||self,Ri(_t.HancWebrtcWidgets={}))})(this,(function(_t){"use strict";/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
- */var Um;const Ri=globalThis,Mo=Ri.ShadowRoot&&(Ri.ShadyCSS===void 0||Ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,wo=Symbol(),zd=new WeakMap;let Gd=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==wo)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(Mo&&e===void 0){const n=t!==void 0&&t.length===1;n&&(e=zd.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&zd.set(t,e))}return e}toString(){return this.cssText}};const jm=i=>new Gd(typeof i=="string"?i:i+"",void 0,wo),Hd=(i,...e)=>{const t=i.length===1?i[0]:e.reduce((n,s,r)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+i[r+1],i[0]);return new Gd(t,i,wo)},Xm=(i,e)=>{if(Mo)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),s=Ri.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=t.cssText,i.appendChild(n)}},Wd=Mo?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return jm(t)})(i):i;/**
5
+ */var Um;const Ri=globalThis,Co=Ri.ShadowRoot&&(Ri.ShadyCSS===void 0||Ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Mo=Symbol(),zd=new WeakMap;let Gd=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Mo)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(Co&&e===void 0){const n=t!==void 0&&t.length===1;n&&(e=zd.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&zd.set(t,e))}return e}toString(){return this.cssText}};const jm=i=>new Gd(typeof i=="string"?i:i+"",void 0,Mo),Hd=(i,...e)=>{const t=i.length===1?i[0]:e.reduce((n,s,r)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+i[r+1],i[0]);return new Gd(t,i,Mo)},Xm=(i,e)=>{if(Co)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),s=Ri.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=t.cssText,i.appendChild(n)}},Wd=Co?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return jm(t)})(i):i;/**
6
6
  * @license
7
7
  * Copyright 2017 Google LLC
8
8
  * SPDX-License-Identifier: BSD-3-Clause
9
- */const{is:$m,defineProperty:Km,getOwnPropertyDescriptor:Ym,getOwnPropertyNames:Jm,getOwnPropertySymbols:Zm,getPrototypeOf:Qm}=Object,Pi=globalThis,qd=Pi.trustedTypes,eg=qd?qd.emptyScript:"",Ao=Pi.reactiveElementPolyfillSupport,fr=(i,e)=>i,ia={toAttribute(i,e){switch(e){case Boolean:i=i?eg:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},Ro=(i,e)=>!$m(i,e),jd={attribute:!0,type:String,converter:ia,reflect:!1,useDefault:!1,hasChanged:Ro};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Pi.litPropertyMetadata??(Pi.litPropertyMetadata=new WeakMap);let Es=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=jd){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 n=Symbol(),s=this.getPropertyDescriptor(e,n,t);s!==void 0&&Km(this.prototype,e,s)}}static getPropertyDescriptor(e,t,n){const{get:s,set:r}=Ym(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){const a=s==null?void 0:s.call(this);r==null||r.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??jd}static _$Ei(){if(this.hasOwnProperty(fr("elementProperties")))return;const e=Qm(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(fr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(fr("properties"))){const t=this.properties,n=[...Jm(t),...Zm(t)];for(const s of n)this.createProperty(s,t[s])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,s]of t)this.elementProperties.set(n,s)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const s=this._$Eu(t,n);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const s of n)t.unshift(Wd(s))}else e!==void 0&&t.push(Wd(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Xm(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostConnected)==null?void 0:n.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostDisconnected)==null?void 0:n.call(t)})}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){var r;const n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){const o=(((r=n.converter)==null?void 0:r.toAttribute)!==void 0?n.converter:ia).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(s):this.setAttribute(s,o),this._$Em=null}}_$AK(e,t){var r,o;const n=this.constructor,s=n._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const a=n.getPropertyOptions(s),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((r=a.converter)==null?void 0:r.fromAttribute)!==void 0?a.converter:ia;this._$Em=s;const l=c.fromAttribute(t,a.type);this[s]=l??((o=this._$Ej)==null?void 0:o.get(s))??l,this._$Em=null}}requestUpdate(e,t,n,s=!1,r){var o;if(e!==void 0){const a=this.constructor;if(s===!1&&(r=this[e]),n??(n=a.getPropertyOptions(e)),!((n.hasChanged??Ro)(r,t)||n.useDefault&&n.reflect&&r===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:s,wrapped:r},o){n&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??t??this[e]),r!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),s===!0&&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 e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:a}=o,c=this[r];a!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,o,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(n=this._$EO)==null||n.forEach(s=>{var r;return(r=s.hostUpdate)==null?void 0:r.call(s)}),this.update(t)):this._$EM()}catch(s){throw e=!1,this._$EM(),s}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(n=>{var s;return(s=n.hostUpdated)==null?void 0:s.call(n)}),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(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};Es.elementStyles=[],Es.shadowRootOptions={mode:"open"},Es[fr("elementProperties")]=new Map,Es[fr("finalized")]=new Map,Ao==null||Ao({ReactiveElement:Es}),(Pi.reactiveElementVersions??(Pi.reactiveElementVersions=[])).push("2.1.2");/**
9
+ */const{is:$m,defineProperty:Km,getOwnPropertyDescriptor:Ym,getOwnPropertyNames:Jm,getOwnPropertySymbols:Zm,getPrototypeOf:Qm}=Object,Pi=globalThis,qd=Pi.trustedTypes,eg=qd?qd.emptyScript:"",wo=Pi.reactiveElementPolyfillSupport,fr=(i,e)=>i,ia={toAttribute(i,e){switch(e){case Boolean:i=i?eg:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},Ao=(i,e)=>!$m(i,e),jd={attribute:!0,type:String,converter:ia,reflect:!1,useDefault:!1,hasChanged:Ao};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Pi.litPropertyMetadata??(Pi.litPropertyMetadata=new WeakMap);let Ts=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=jd){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 n=Symbol(),s=this.getPropertyDescriptor(e,n,t);s!==void 0&&Km(this.prototype,e,s)}}static getPropertyDescriptor(e,t,n){const{get:s,set:r}=Ym(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){const a=s==null?void 0:s.call(this);r==null||r.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??jd}static _$Ei(){if(this.hasOwnProperty(fr("elementProperties")))return;const e=Qm(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(fr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(fr("properties"))){const t=this.properties,n=[...Jm(t),...Zm(t)];for(const s of n)this.createProperty(s,t[s])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,s]of t)this.elementProperties.set(n,s)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const s=this._$Eu(t,n);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const s of n)t.unshift(Wd(s))}else e!==void 0&&t.push(Wd(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Xm(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostConnected)==null?void 0:n.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostDisconnected)==null?void 0:n.call(t)})}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){var r;const n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){const o=(((r=n.converter)==null?void 0:r.toAttribute)!==void 0?n.converter:ia).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(s):this.setAttribute(s,o),this._$Em=null}}_$AK(e,t){var r,o;const n=this.constructor,s=n._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const a=n.getPropertyOptions(s),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((r=a.converter)==null?void 0:r.fromAttribute)!==void 0?a.converter:ia;this._$Em=s;const l=c.fromAttribute(t,a.type);this[s]=l??((o=this._$Ej)==null?void 0:o.get(s))??l,this._$Em=null}}requestUpdate(e,t,n,s=!1,r){var o;if(e!==void 0){const a=this.constructor;if(s===!1&&(r=this[e]),n??(n=a.getPropertyOptions(e)),!((n.hasChanged??Ao)(r,t)||n.useDefault&&n.reflect&&r===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:s,wrapped:r},o){n&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??t??this[e]),r!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),s===!0&&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 e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:a}=o,c=this[r];a!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,o,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(n=this._$EO)==null||n.forEach(s=>{var r;return(r=s.hostUpdate)==null?void 0:r.call(s)}),this.update(t)):this._$EM()}catch(s){throw e=!1,this._$EM(),s}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(n=>{var s;return(s=n.hostUpdated)==null?void 0:s.call(n)}),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(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};Ts.elementStyles=[],Ts.shadowRootOptions={mode:"open"},Ts[fr("elementProperties")]=new Map,Ts[fr("finalized")]=new Map,wo==null||wo({ReactiveElement:Ts}),(Pi.reactiveElementVersions??(Pi.reactiveElementVersions=[])).push("2.1.2");/**
10
10
  * @license
11
11
  * Copyright 2017 Google LLC
12
12
  * SPDX-License-Identifier: BSD-3-Clause
13
- */const pr=globalThis,Xd=i=>i,sa=pr.trustedTypes,$d=sa?sa.createPolicy("lit-html",{createHTML:i=>i}):void 0,Kd="$lit$",ki=`lit$${Math.random().toFixed(9).slice(2)}$`,Yd="?"+ki,tg=`<${Yd}>`,Zi=document,mr=()=>Zi.createComment(""),gr=i=>i===null||typeof i!="object"&&typeof i!="function",Po=Array.isArray,ng=i=>Po(i)||typeof(i==null?void 0:i[Symbol.iterator])=="function",ko=`[
14
- \f\r]`,vr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Jd=/-->/g,Zd=/>/g,Qi=RegExp(`>|${ko}(?:([^\\s"'>=/]+)(${ko}*=${ko}*(?:[^
15
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Qd=/'/g,eu=/"/g,tu=/^(?:script|style|textarea|title)$/i,ig=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),sg=ig(1),Cs=Symbol.for("lit-noChange"),Ht=Symbol.for("lit-nothing"),nu=new WeakMap,es=Zi.createTreeWalker(Zi,129);function iu(i,e){if(!Po(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return $d!==void 0?$d.createHTML(e):e}const rg=(i,e)=>{const t=i.length-1,n=[];let s,r=e===2?"<svg>":e===3?"<math>":"",o=vr;for(let a=0;a<t;a++){const c=i[a];let l,d,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,d=o.exec(c),d!==null);)h=o.lastIndex,o===vr?d[1]==="!--"?o=Jd:d[1]!==void 0?o=Zd:d[2]!==void 0?(tu.test(d[2])&&(s=RegExp("</"+d[2],"g")),o=Qi):d[3]!==void 0&&(o=Qi):o===Qi?d[0]===">"?(o=s??vr,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?Qi:d[3]==='"'?eu:Qd):o===eu||o===Qd?o=Qi:o===Jd||o===Zd?o=vr:(o=Qi,s=void 0);const f=o===Qi&&i[a+1].startsWith("/>")?" ":"";r+=o===vr?c+tg:u>=0?(n.push(l),c.slice(0,u)+Kd+c.slice(u)+ki+f):c+ki+(u===-2?a:f)}return[iu(i,r+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class _r{constructor({strings:e,_$litType$:t},n){let s;this.parts=[];let r=0,o=0;const a=e.length-1,c=this.parts,[l,d]=rg(e,t);if(this.el=_r.createElement(l,n),es.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=es.nextNode())!==null&&c.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Kd)){const h=d[o++],f=s.getAttribute(u).split(ki),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?og:g[1]==="?"?cg:g[1]==="@"?lg:ra}),s.removeAttribute(u)}else u.startsWith(ki)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(tu.test(s.tagName)){const u=s.textContent.split(ki),h=u.length-1;if(h>0){s.textContent=sa?sa.emptyScript:"";for(let f=0;f<h;f++)s.append(u[f],mr()),es.nextNode(),c.push({type:2,index:++r});s.append(u[h],mr())}}}else if(s.nodeType===8)if(s.data===Yd)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(ki,u+1))!==-1;)c.push({type:7,index:r}),u+=ki.length-1}r++}}static createElement(e,t){const n=Zi.createElement("template");return n.innerHTML=e,n}}function Ms(i,e,t=i,n){var o,a;if(e===Cs)return e;let s=n!==void 0?(o=t._$Co)==null?void 0:o[n]:t._$Cl;const r=gr(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),r===void 0?s=void 0:(s=new r(i),s._$AT(i,t,n)),n!==void 0?(t._$Co??(t._$Co=[]))[n]=s:t._$Cl=s),s!==void 0&&(e=Ms(i,s._$AS(i,e.values),s,n)),e}class ag{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:n}=this._$AD,s=((e==null?void 0:e.creationScope)??Zi).importNode(t,!0);es.currentNode=s;let r=es.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new br(r,r.nextSibling,this,e):c.type===1?l=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(l=new dg(r,this,e)),this._$AV.push(l),c=n[++a]}o!==(c==null?void 0:c.index)&&(r=es.nextNode(),o++)}return es.currentNode=Zi,s}p(e){let t=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}}class br{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,n,s){this.type=2,this._$AH=Ht,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Ms(this,e,t),gr(e)?e===Ht||e==null||e===""?(this._$AH!==Ht&&this._$AR(),this._$AH=Ht):e!==this._$AH&&e!==Cs&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):ng(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!==Ht&&gr(this._$AH)?this._$AA.nextSibling.data=e:this.T(Zi.createTextNode(e)),this._$AH=e}$(e){var r;const{values:t,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=_r.createElement(iu(n.h,n.h[0]),this.options)),n);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const o=new ag(s,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=nu.get(e.strings);return t===void 0&&nu.set(e.strings,t=new _r(e)),t}k(e){Po(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let n,s=0;for(const r of e)s===t.length?t.push(n=new br(this.O(mr()),this.O(mr()),this,this.options)):n=t[s],n._$AI(r),s++;s<t.length&&(this._$AR(n&&n._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,t);e!==this._$AB;){const s=Xd(e).nextSibling;Xd(e).remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class ra{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,s,r){this.type=1,this._$AH=Ht,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ht}_$AI(e,t=this,n,s){const r=this.strings;let o=!1;if(r===void 0)e=Ms(this,e,t,0),o=!gr(e)||e!==this._$AH&&e!==Cs,o&&(this._$AH=e);else{const a=e;let c,l;for(e=r[0],c=0;c<r.length-1;c++)l=Ms(this,a[n+c],t,c),l===Cs&&(l=this._$AH[c]),o||(o=!gr(l)||l!==this._$AH[c]),l===Ht?e=Ht:e!==Ht&&(e+=(l??"")+r[c+1]),this._$AH[c]=l}o&&!s&&this.j(e)}j(e){e===Ht?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class og extends ra{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ht?void 0:e}}class cg extends ra{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ht)}}class lg extends ra{constructor(e,t,n,s,r){super(e,t,n,s,r),this.type=5}_$AI(e,t=this){if((e=Ms(this,e,t,0)??Ht)===Cs)return;const n=this._$AH,s=e===Ht&&n!==Ht||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,r=e!==Ht&&(n===Ht||s);s&&this.element.removeEventListener(this.name,this,n),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class dg{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){Ms(this,e)}}const Io=pr.litHtmlPolyfillSupport;Io==null||Io(_r,br),(pr.litHtmlVersions??(pr.litHtmlVersions=[])).push("3.3.2");const ug=(i,e,t)=>{const n=(t==null?void 0:t.renderBefore)??e;let s=n._$litPart$;if(s===void 0){const r=(t==null?void 0:t.renderBefore)??null;n._$litPart$=s=new br(e.insertBefore(mr(),r),r,void 0,t??{})}return s._$AI(i),s};/**
13
+ */const pr=globalThis,Xd=i=>i,sa=pr.trustedTypes,$d=sa?sa.createPolicy("lit-html",{createHTML:i=>i}):void 0,Kd="$lit$",ki=`lit$${Math.random().toFixed(9).slice(2)}$`,Yd="?"+ki,tg=`<${Yd}>`,Zi=document,mr=()=>Zi.createComment(""),gr=i=>i===null||typeof i!="object"&&typeof i!="function",Ro=Array.isArray,ng=i=>Ro(i)||typeof(i==null?void 0:i[Symbol.iterator])=="function",Po=`[
14
+ \f\r]`,vr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Jd=/-->/g,Zd=/>/g,Qi=RegExp(`>|${Po}(?:([^\\s"'>=/]+)(${Po}*=${Po}*(?:[^
15
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Qd=/'/g,eu=/"/g,tu=/^(?:script|style|textarea|title)$/i,ig=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),sg=ig(1),Es=Symbol.for("lit-noChange"),Ht=Symbol.for("lit-nothing"),nu=new WeakMap,es=Zi.createTreeWalker(Zi,129);function iu(i,e){if(!Ro(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return $d!==void 0?$d.createHTML(e):e}const rg=(i,e)=>{const t=i.length-1,n=[];let s,r=e===2?"<svg>":e===3?"<math>":"",o=vr;for(let a=0;a<t;a++){const c=i[a];let l,d,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,d=o.exec(c),d!==null);)h=o.lastIndex,o===vr?d[1]==="!--"?o=Jd:d[1]!==void 0?o=Zd:d[2]!==void 0?(tu.test(d[2])&&(s=RegExp("</"+d[2],"g")),o=Qi):d[3]!==void 0&&(o=Qi):o===Qi?d[0]===">"?(o=s??vr,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?Qi:d[3]==='"'?eu:Qd):o===eu||o===Qd?o=Qi:o===Jd||o===Zd?o=vr:(o=Qi,s=void 0);const f=o===Qi&&i[a+1].startsWith("/>")?" ":"";r+=o===vr?c+tg:u>=0?(n.push(l),c.slice(0,u)+Kd+c.slice(u)+ki+f):c+ki+(u===-2?a:f)}return[iu(i,r+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class _r{constructor({strings:e,_$litType$:t},n){let s;this.parts=[];let r=0,o=0;const a=e.length-1,c=this.parts,[l,d]=rg(e,t);if(this.el=_r.createElement(l,n),es.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=es.nextNode())!==null&&c.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(Kd)){const h=d[o++],f=s.getAttribute(u).split(ki),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?og:g[1]==="?"?cg:g[1]==="@"?lg:ra}),s.removeAttribute(u)}else u.startsWith(ki)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(tu.test(s.tagName)){const u=s.textContent.split(ki),h=u.length-1;if(h>0){s.textContent=sa?sa.emptyScript:"";for(let f=0;f<h;f++)s.append(u[f],mr()),es.nextNode(),c.push({type:2,index:++r});s.append(u[h],mr())}}}else if(s.nodeType===8)if(s.data===Yd)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(ki,u+1))!==-1;)c.push({type:7,index:r}),u+=ki.length-1}r++}}static createElement(e,t){const n=Zi.createElement("template");return n.innerHTML=e,n}}function Cs(i,e,t=i,n){var o,a;if(e===Es)return e;let s=n!==void 0?(o=t._$Co)==null?void 0:o[n]:t._$Cl;const r=gr(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((a=s==null?void 0:s._$AO)==null||a.call(s,!1),r===void 0?s=void 0:(s=new r(i),s._$AT(i,t,n)),n!==void 0?(t._$Co??(t._$Co=[]))[n]=s:t._$Cl=s),s!==void 0&&(e=Cs(i,s._$AS(i,e.values),s,n)),e}class ag{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:n}=this._$AD,s=((e==null?void 0:e.creationScope)??Zi).importNode(t,!0);es.currentNode=s;let r=es.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new br(r,r.nextSibling,this,e):c.type===1?l=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(l=new dg(r,this,e)),this._$AV.push(l),c=n[++a]}o!==(c==null?void 0:c.index)&&(r=es.nextNode(),o++)}return es.currentNode=Zi,s}p(e){let t=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}}class br{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,n,s){this.type=2,this._$AH=Ht,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Cs(this,e,t),gr(e)?e===Ht||e==null||e===""?(this._$AH!==Ht&&this._$AR(),this._$AH=Ht):e!==this._$AH&&e!==Es&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):ng(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!==Ht&&gr(this._$AH)?this._$AA.nextSibling.data=e:this.T(Zi.createTextNode(e)),this._$AH=e}$(e){var r;const{values:t,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=_r.createElement(iu(n.h,n.h[0]),this.options)),n);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const o=new ag(s,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=nu.get(e.strings);return t===void 0&&nu.set(e.strings,t=new _r(e)),t}k(e){Ro(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let n,s=0;for(const r of e)s===t.length?t.push(n=new br(this.O(mr()),this.O(mr()),this,this.options)):n=t[s],n._$AI(r),s++;s<t.length&&(this._$AR(n&&n._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,t);e!==this._$AB;){const s=Xd(e).nextSibling;Xd(e).remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class ra{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,s,r){this.type=1,this._$AH=Ht,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ht}_$AI(e,t=this,n,s){const r=this.strings;let o=!1;if(r===void 0)e=Cs(this,e,t,0),o=!gr(e)||e!==this._$AH&&e!==Es,o&&(this._$AH=e);else{const a=e;let c,l;for(e=r[0],c=0;c<r.length-1;c++)l=Cs(this,a[n+c],t,c),l===Es&&(l=this._$AH[c]),o||(o=!gr(l)||l!==this._$AH[c]),l===Ht?e=Ht:e!==Ht&&(e+=(l??"")+r[c+1]),this._$AH[c]=l}o&&!s&&this.j(e)}j(e){e===Ht?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class og extends ra{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ht?void 0:e}}class cg extends ra{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ht)}}class lg extends ra{constructor(e,t,n,s,r){super(e,t,n,s,r),this.type=5}_$AI(e,t=this){if((e=Cs(this,e,t,0)??Ht)===Es)return;const n=this._$AH,s=e===Ht&&n!==Ht||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,r=e!==Ht&&(n===Ht||s);s&&this.element.removeEventListener(this.name,this,n),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class dg{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){Cs(this,e)}}const ko=pr.litHtmlPolyfillSupport;ko==null||ko(_r,br),(pr.litHtmlVersions??(pr.litHtmlVersions=[])).push("3.3.2");const ug=(i,e,t)=>{const n=(t==null?void 0:t.renderBefore)??e;let s=n._$litPart$;if(s===void 0){const r=(t==null?void 0:t.renderBefore)??null;n._$litPart$=s=new br(e.insertBefore(mr(),r),r,void 0,t??{})}return s._$AI(i),s};/**
16
16
  * @license
17
17
  * Copyright 2017 Google LLC
18
18
  * SPDX-License-Identifier: BSD-3-Clause
19
- */const ts=globalThis;class yr extends Es{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=ug(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Cs}}yr._$litElement$=!0,yr.finalized=!0,(Um=ts.litElementHydrateSupport)==null||Um.call(ts,{LitElement:yr});const Do=ts.litElementPolyfillSupport;Do==null||Do({LitElement:yr}),(ts.litElementVersions??(ts.litElementVersions=[])).push("4.2.2");/**
19
+ */const ts=globalThis;class yr extends Ts{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=ug(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Es}}yr._$litElement$=!0,yr.finalized=!0,(Um=ts.litElementHydrateSupport)==null||Um.call(ts,{LitElement:yr});const Io=ts.litElementPolyfillSupport;Io==null||Io({LitElement:yr}),(ts.litElementVersions??(ts.litElementVersions=[])).push("4.2.2");/**
20
20
  * @license
21
21
  * Copyright 2017 Google LLC
22
22
  * SPDX-License-Identifier: BSD-3-Clause
23
- */const aa=i=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(i,e)}):customElements.define(i,e)};/**
23
+ */const Do=i=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(i,e)}):customElements.define(i,e)};/**
24
24
  * @license
25
25
  * Copyright 2017 Google LLC
26
26
  * SPDX-License-Identifier: BSD-3-Clause
27
- */const hg={attribute:!0,type:String,converter:ia,reflect:!1,hasChanged:Ro},fg=(i=hg,e,t)=>{const{kind:n,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),n==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(t.name,i),n==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(n==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+n)};function Bt(i){return(e,t)=>typeof t=="object"?fg(i,e,t):((n,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,n),o?Object.getOwnPropertyDescriptor(s,r):void 0})(i,e,t)}/**
27
+ */const hg={attribute:!0,type:String,converter:ia,reflect:!1,hasChanged:Ao},fg=(i=hg,e,t)=>{const{kind:n,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),n==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(t.name,i),n==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(n==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+n)};function Ft(i){return(e,t)=>typeof t=="object"?fg(i,e,t):((n,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,n),o?Object.getOwnPropertyDescriptor(s,r):void 0})(i,e,t)}/**
28
28
  * @license
29
29
  * Copyright 2017 Google LLC
30
30
  * SPDX-License-Identifier: BSD-3-Clause
31
- */function pg(i){return Bt({...i,state:!0,attribute:!1})}/**
31
+ */function pg(i){return Ft({...i,state:!0,attribute:!1})}/**
32
32
  * @license
33
33
  * Copyright 2017 Google LLC
34
34
  * SPDX-License-Identifier: BSD-3-Clause
@@ -40,11 +40,11 @@
40
40
  * @license
41
41
  * Copyright 2010-2025 Three.js Authors
42
42
  * SPDX-License-Identifier: MIT
43
- */const Lo="182",vg=0,su=1,_g=2,oa=1,bg=2,Sr=3,ci=0,en=1,li=2,di=0,ws=1,No=2,ru=3,au=4,yg=5,ns=100,Sg=101,xg=102,Tg=103,Eg=104,Cg=200,Mg=201,wg=202,Ag=203,Oo=204,Uo=205,Rg=206,Pg=207,kg=208,Ig=209,Dg=210,Lg=211,Ng=212,Og=213,Ug=214,Fo=0,Bo=1,Vo=2,As=3,zo=4,Go=5,Ho=6,Wo=7,ou=0,Fg=1,Bg=2,jn=0,cu=1,lu=2,du=3,uu=4,hu=5,fu=6,pu=7,mu=300,is=301,Rs=302,qo=303,jo=304,ca=306,Xo=1e3,ui=1001,$o=1002,$t=1003,Vg=1004,la=1005,Jt=1006,Ko=1007,ss=1008,Tn=1009,gu=1010,vu=1011,xr=1012,Yo=1013,Xn=1014,$n=1015,hi=1016,Jo=1017,Zo=1018,Tr=1020,_u=35902,bu=35899,yu=1021,Su=1022,In=1023,fi=1026,rs=1027,xu=1028,Qo=1029,Ps=1030,ec=1031,tc=1033,da=33776,ua=33777,ha=33778,fa=33779,nc=35840,ic=35841,sc=35842,rc=35843,ac=36196,oc=37492,cc=37496,lc=37488,dc=37489,uc=37490,hc=37491,fc=37808,pc=37809,mc=37810,gc=37811,vc=37812,_c=37813,bc=37814,yc=37815,Sc=37816,xc=37817,Tc=37818,Ec=37819,Cc=37820,Mc=37821,wc=36492,Ac=36494,Rc=36495,Pc=36283,kc=36284,Ic=36285,Dc=36286,zg=3200,Gg=0,Hg=1,Ii="",En="srgb",ks="srgb-linear",pa="linear",ct="srgb",Is=7680,Tu=519,Wg=512,qg=513,jg=514,Lc=515,Xg=516,$g=517,Nc=518,Kg=519,Eu=35044,Cu="300 es",Kn=2e3,ma=2001;function Mu(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function ga(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Yg(){const i=ga("canvas");return i.style.display="block",i}const wu={};function Au(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function tt(...i){const e="THREE."+i.shift();console.error(e,...i)}function Er(...i){const e=i.join(" ");e in wu||(wu[e]=!0,Oe(...i))}function Jg(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class Ds{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,o=s.length;r<o;r++)s[r].call(this,e);e.target=null}}}const Zt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Oc=Math.PI/180,Uc=180/Math.PI;function Cr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Zt[i&255]+Zt[i>>8&255]+Zt[i>>16&255]+Zt[i>>24&255]+"-"+Zt[e&255]+Zt[e>>8&255]+"-"+Zt[e>>16&15|64]+Zt[e>>24&255]+"-"+Zt[t&63|128]+Zt[t>>8&255]+"-"+Zt[t>>16&255]+Zt[t>>24&255]+Zt[n&255]+Zt[n>>8&255]+Zt[n>>16&255]+Zt[n>>24&255]).toLowerCase()}function Ye(i,e,t){return Math.max(e,Math.min(t,i))}function Zg(i,e){return(i%e+e)%e}function Fc(i,e,t){return(1-t)*i+t*e}function Mr(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function dn(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class st{constructor(e=0,t=0){st.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ye(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*s+e.x,this.y=r*s+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class wr{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,o,a){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[o+0],f=r[o+1],g=r[o+2],v=r[o+3];if(a<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(a>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-a;if(m<.9995){const T=Math.acos(m),C=Math.sin(T);p=Math.sin(p*T)/C,a=Math.sin(a*T)/C,c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a}else{c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a;const T=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=T,l*=T,d*=T,u*=T}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,o){const a=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[o],h=r[o+1],f=r[o+2],g=r[o+3];return e[t]=a*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-a*f,e[t+2]=l*g+d*f+a*h-c*u,e[t+3]=d*g-a*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),d=a(s/2),u=a(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(o){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Oe("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+a+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(o-s)*f}else if(n>a&&n>u){const f=2*Math.sqrt(1+n-a-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+o)/f,this._z=(r+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-n-u);this._w=(r-l)/f,this._x=(s+o)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-a);this._w=(o-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ye(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+o*a+s*l-r*c,this._y=s*d+o*c+r*a-n*l,this._z=r*d+o*l+n*c-s*a,this._w=o*d-n*a-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let c=1-t;if(a<.9995){const l=Math.acos(a),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class V{constructor(e=0,t=0,n=0){V.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ru.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ru.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*s-a*n),d=2*(a*t-r*s),u=2*(r*n-o*t);return this.x=t+c*l+o*u-a*d,this.y=n+c*d+a*l-r*u,this.z=s+c*u+r*d-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=s*c-r*a,this.y=r*o-n*c,this.z=n*a-s*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Bc.copy(this).projectOnVector(e),this.sub(Bc)}reflect(e){return this.sub(Bc.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ye(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Bc=new V,Ru=new wr;class Ve{constructor(e,t,n,s,r,o,a,c,l){Ve.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l)}set(e,t,n,s,r,o,a,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=a,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=o,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],T=s[1],C=s[4],_=s[7],S=s[2],E=s[5],w=s[8];return r[0]=o*v+a*T+c*S,r[3]=o*m+a*C+c*E,r[6]=o*p+a*_+c*w,r[1]=l*v+d*T+u*S,r[4]=l*m+d*C+u*E,r[7]=l*p+d*_+u*w,r[2]=h*v+f*T+g*S,r[5]=h*m+f*C+g*E,r[8]=h*p+f*_+g*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8];return t*o*d-t*a*l-n*r*d+n*a*c+s*r*l-s*o*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=d*o-a*l,h=a*c-d*r,f=l*r-o*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(a*n-s*o)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-a*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(o*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,o,a){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-s*l,s*c,-s*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Vc.makeScale(e,t)),this}rotate(e){return this.premultiply(Vc.makeRotation(-e)),this}translate(e,t){return this.premultiply(Vc.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Vc=new Ve,Pu=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ku=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Qg(){const i={enabled:!0,workingColorSpace:ks,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===ct&&(s.r=pi(s.r),s.g=pi(s.g),s.b=pi(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===ct&&(s.r=Ls(s.r),s.g=Ls(s.g),s.b=Ls(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ii?pa:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Er("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Er("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[ks]:{primaries:e,whitePoint:n,transfer:pa,toXYZ:Pu,fromXYZ:ku,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:En},outputColorSpaceConfig:{drawingBufferColorSpace:En}},[En]:{primaries:e,whitePoint:n,transfer:ct,toXYZ:Pu,fromXYZ:ku,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:En}}}),i}const Ze=Qg();function pi(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Ls(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Ns;class ev{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Ns===void 0&&(Ns=ga("canvas")),Ns.width=e.width,Ns.height=e.height;const s=Ns.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Ns}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=ga("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let o=0;o<r.length;o++)r[o]=pi(r[o]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(pi(t[n]/255)*255):t[n]=pi(t[n]);return{data:t,width:e.width,height:e.height}}else return Oe("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let tv=0;class zc{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:tv++}),this.uuid=Cr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let o=0,a=s.length;o<a;o++)s[o].isDataTexture?r.push(Gc(s[o].image)):r.push(Gc(s[o]))}else r=Gc(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Gc(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?ev.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Oe("Texture: Unable to serialize Texture."),{})}let nv=0;const Hc=new V;class tn extends Ds{constructor(e=tn.DEFAULT_IMAGE,t=tn.DEFAULT_MAPPING,n=ui,s=ui,r=Jt,o=ss,a=In,c=Tn,l=tn.DEFAULT_ANISOTROPY,d=Ii){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nv++}),this.uuid=Cr(),this.name="",this.source=new zc(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new st(0,0),this.repeat=new st(1,1),this.center=new st(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Hc).x}get height(){return this.source.getSize(Hc).y}get depth(){return this.source.getSize(Hc).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Oe(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==mu)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Xo:e.x=e.x-Math.floor(e.x);break;case ui:e.x=e.x<0?0:1;break;case $o:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Xo:e.y=e.y-Math.floor(e.y);break;case ui:e.y=e.y<0?0:1;break;case $o:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=mu,tn.DEFAULT_ANISOTROPY=1;class Pt{constructor(e=0,t=0,n=0,s=1){Pt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*s+o[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const C=(l+1)/2,_=(f+1)/2,S=(p+1)/2,E=(d+h)/4,w=(u+v)/4,k=(g+m)/4;return C>_&&C>S?C<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(C),s=E/n,r=w/n):_>S?_<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(_),n=E/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=w/r,s=k/r),this.set(n,s,r,t),this}let T=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(T)<.001&&(T=1),this.x=(m-g)/T,this.y=(u-v)/T,this.z=(h-d)/T,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this.w=Ye(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this.w=Ye(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class iv extends Ds{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Jt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new tn(s);this.textures=[];const o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:Jt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new zc(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Yn extends iv{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Iu extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=$t,this.minFilter=$t,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class sv extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=$t,this.minFilter=$t,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Ar{constructor(e=new V(1/0,1/0,1/0),t=new V(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Dn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Dn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Dn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,Dn):Dn.fromBufferAttribute(r,o),Dn.applyMatrix4(e.matrixWorld),this.expandByPoint(Dn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),va.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),va.copy(n.boundingBox)),va.applyMatrix4(e.matrixWorld),this.union(va)}const s=e.children;for(let r=0,o=s.length;r<o;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Dn),Dn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Rr),_a.subVectors(this.max,Rr),Os.subVectors(e.a,Rr),Us.subVectors(e.b,Rr),Fs.subVectors(e.c,Rr),Di.subVectors(Us,Os),Li.subVectors(Fs,Us),as.subVectors(Os,Fs);let t=[0,-Di.z,Di.y,0,-Li.z,Li.y,0,-as.z,as.y,Di.z,0,-Di.x,Li.z,0,-Li.x,as.z,0,-as.x,-Di.y,Di.x,0,-Li.y,Li.x,0,-as.y,as.x,0];return!Wc(t,Os,Us,Fs,_a)||(t=[1,0,0,0,1,0,0,0,1],!Wc(t,Os,Us,Fs,_a))?!1:(ba.crossVectors(Di,Li),t=[ba.x,ba.y,ba.z],Wc(t,Os,Us,Fs,_a))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Dn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Dn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(mi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),mi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),mi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),mi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),mi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),mi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),mi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),mi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(mi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const mi=[new V,new V,new V,new V,new V,new V,new V,new V],Dn=new V,va=new Ar,Os=new V,Us=new V,Fs=new V,Di=new V,Li=new V,as=new V,Rr=new V,_a=new V,ba=new V,os=new V;function Wc(i,e,t,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){os.fromArray(i,r);const a=s.x*Math.abs(os.x)+s.y*Math.abs(os.y)+s.z*Math.abs(os.z),c=e.dot(os),l=t.dot(os),d=n.dot(os);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>a)return!1}return!0}const rv=new Ar,Pr=new V,qc=new V;class jc{constructor(e=new V,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):rv.setFromPoints(e).getCenter(n);let s=0;for(let r=0,o=e.length;r<o;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Pr.subVectors(e,this.center);const t=Pr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(Pr,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(qc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Pr.copy(e.center).add(qc)),this.expandByPoint(Pr.copy(e.center).sub(qc))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const gi=new V,Xc=new V,ya=new V,Ni=new V,$c=new V,Sa=new V,Kc=new V;class av{constructor(e=new V,t=new V(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,gi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=gi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(gi.copy(this.origin).addScaledVector(this.direction,t),gi.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Xc.copy(e).add(t).multiplyScalar(.5),ya.copy(t).sub(e).normalize(),Ni.copy(this.origin).sub(Xc);const r=e.distanceTo(t)*.5,o=-this.direction.dot(ya),a=Ni.dot(this.direction),c=-Ni.dot(ya),l=Ni.lengthSq(),d=Math.abs(1-o*o);let u,h,f,g;if(d>0)if(u=o*c-a,h=o*a-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+o*h+2*a)+h*(o*u+h+2*c)+l}else h=r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-o*r+a)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(o*r+a)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=o>0?-r:r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Xc).addScaledVector(ya,h),f}intersectSphere(e,t){gi.subVectors(e.center,this.origin);const n=gi.dot(this.direction),s=gi.dot(gi)-n*n,r=e.radius*e.radius;if(s>r)return null;const o=Math.sqrt(r-s),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,o,a,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,o=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,o=(e.min.y-h.y)*d),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o<s||isNaN(s))&&(s=o),u>=0?(a=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||a>s)||((a>n||n!==n)&&(n=a),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,gi)!==null}intersectTriangle(e,t,n,s,r){$c.subVectors(t,e),Sa.subVectors(n,e),Kc.crossVectors($c,Sa);let o=this.direction.dot(Kc),a;if(o>0){if(s)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Ni.subVectors(this.origin,e);const c=a*this.direction.dot(Sa.crossVectors(Ni,Sa));if(c<0)return null;const l=a*this.direction.dot($c.cross(Ni));if(l<0||c+l>o)return null;const d=-a*Ni.dot(Kc);return d<0?null:this.at(d/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Dt{constructor(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){Dt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=o,p[9]=a,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Dt().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/Bs.setFromMatrixColumn(e,0).length(),r=1/Bs.setFromMatrixColumn(e,1).length(),o=1/Bs.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-a*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=o*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*a,t[4]=g*a-f,t[8]=o*l,t[1]=o*u,t[5]=o*d,t[9]=-a,t[2]=f*a-g,t[6]=v+h*a,t[10]=o*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*a,t[4]=-o*u,t[8]=g+f*a,t[1]=f+g*a,t[5]=o*d,t[9]=v-h*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=o*d,t[9]=-a*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=o*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=a*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ov,e,cv)}lookAt(e,t,n){const s=this.elements;return vn.subVectors(e,t),vn.lengthSq()===0&&(vn.z=1),vn.normalize(),Oi.crossVectors(n,vn),Oi.lengthSq()===0&&(Math.abs(n.z)===1?vn.x+=1e-4:vn.z+=1e-4,vn.normalize(),Oi.crossVectors(n,vn)),Oi.normalize(),xa.crossVectors(vn,Oi),s[0]=Oi.x,s[4]=xa.x,s[8]=vn.x,s[1]=Oi.y,s[5]=xa.y,s[9]=vn.y,s[2]=Oi.z,s[6]=xa.z,s[10]=vn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],T=n[3],C=n[7],_=n[11],S=n[15],E=s[0],w=s[4],k=s[8],y=s[12],x=s[1],R=s[5],O=s[9],U=s[13],q=s[2],$=s[6],G=s[10],W=s[14],ee=s[3],ge=s[7],le=s[11],_e=s[15];return r[0]=o*E+a*x+c*q+l*ee,r[4]=o*w+a*R+c*$+l*ge,r[8]=o*k+a*O+c*G+l*le,r[12]=o*y+a*U+c*W+l*_e,r[1]=d*E+u*x+h*q+f*ee,r[5]=d*w+u*R+h*$+f*ge,r[9]=d*k+u*O+h*G+f*le,r[13]=d*y+u*U+h*W+f*_e,r[2]=g*E+v*x+m*q+p*ee,r[6]=g*w+v*R+m*$+p*ge,r[10]=g*k+v*O+m*G+p*le,r[14]=g*y+v*U+m*W+p*_e,r[3]=T*E+C*x+_*q+S*ee,r[7]=T*w+C*R+_*$+S*ge,r[11]=T*k+C*O+_*G+S*le,r[15]=T*y+C*U+_*W+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],T=c*f-l*h,C=a*f-l*u,_=a*h-c*u,S=o*f-l*d,E=o*h-c*d,w=o*u-a*d;return t*(v*T-m*C+p*_)-n*(g*T-m*S+p*E)+s*(g*C-v*S+p*w)-r*(g*_-v*E+m*w)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],T=u*m*l-v*h*l+v*c*f-a*m*f-u*c*p+a*h*p,C=g*h*l-d*m*l-g*c*f+o*m*f+d*c*p-o*h*p,_=d*v*l-g*u*l+g*a*f-o*v*f-d*a*p+o*u*p,S=g*u*c-d*v*c-g*a*h+o*v*h+d*a*m-o*u*m,E=t*T+n*C+s*_+r*S;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/E;return e[0]=T*w,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*w,e[2]=(a*m*r-v*c*r+v*s*l-n*m*l-a*s*p+n*c*p)*w,e[3]=(u*c*r-a*h*r-u*s*l+n*h*l+a*s*f-n*c*f)*w,e[4]=C*w,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*w,e[6]=(g*c*r-o*m*r-g*s*l+t*m*l+o*s*p-t*c*p)*w,e[7]=(o*h*r-d*c*r+d*s*l-t*h*l-o*s*f+t*c*f)*w,e[8]=_*w,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*w,e[10]=(o*v*r-g*a*r+g*n*l-t*v*l-o*n*p+t*a*p)*w,e[11]=(d*a*r-o*u*r-d*n*l+t*u*l+o*n*f-t*a*f)*w,e[12]=S*w,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*w,e[14]=(g*a*s-o*v*s-g*n*c+t*v*c+o*n*m-t*a*m)*w,e[15]=(o*u*s-d*a*s+d*n*c-t*u*c-o*n*h+t*a*h)*w,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,d=r*a;return this.set(l*o+n,l*a-s*c,l*c+s*a,0,l*a+s*c,d*a+n,d*c-s*o,0,l*c-s*a,d*c+s*o,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,o){return this.set(1,n,r,0,e,1,o,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,d=o+o,u=a+a,h=r*l,f=r*d,g=r*u,v=o*d,m=o*u,p=a*u,T=c*l,C=c*d,_=c*u,S=n.x,E=n.y,w=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+_)*S,s[2]=(g-C)*S,s[3]=0,s[4]=(f-_)*E,s[5]=(1-(h+p))*E,s[6]=(m+T)*E,s[7]=0,s[8]=(g+C)*w,s[9]=(m-T)*w,s[10]=(1-(h+v))*w,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=Bs.set(s[0],s[1],s[2]).length();const o=Bs.set(s[4],s[5],s[6]).length(),a=Bs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),Ln.copy(this);const l=1/r,d=1/o,u=1/a;return Ln.elements[0]*=l,Ln.elements[1]*=l,Ln.elements[2]*=l,Ln.elements[4]*=d,Ln.elements[5]*=d,Ln.elements[6]*=d,Ln.elements[8]*=u,Ln.elements[9]*=u,Ln.elements[10]*=u,t.setFromRotationMatrix(Ln),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,s,r,o,a=Kn,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(o-r),v=o*r/(o-r);else if(a===Kn)g=-(o+r)/(o-r),v=-2*o*r/(o-r);else if(a===ma)g=-o/(o-r),v=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,o,a=Kn,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(o-r),v=o/(o-r);else if(a===Kn)g=-2/(o-r),v=-(o+r)/(o-r);else if(a===ma)g=-1/(o-r),v=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const Bs=new V,Ln=new Dt,ov=new V(0,0,0),cv=new V(1,1,1),Oi=new V,xa=new V,vn=new V,Du=new Dt,Lu=new wr;class vi{constructor(e=0,t=0,n=0,s=vi.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],o=s[4],a=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ye(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ye(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ye(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Ye(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Ye(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-Ye(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Oe("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Du.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Du,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Lu.setFromEuler(this),this.setFromQuaternion(Lu,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}vi.DEFAULT_ORDER="XYZ";class Nu{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let lv=0;const Ou=new V,Vs=new wr,_i=new Dt,Ta=new V,kr=new V,dv=new V,uv=new wr,Uu=new V(1,0,0),Fu=new V(0,1,0),Bu=new V(0,0,1),Vu={type:"added"},hv={type:"removed"},zs={type:"childadded",child:null},Yc={type:"childremoved",child:null};class _n extends Ds{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:lv++}),this.uuid=Cr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=_n.DEFAULT_UP.clone();const e=new V,t=new vi,n=new wr,s=new V(1,1,1);function r(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Dt},normalMatrix:{value:new Ve}}),this.matrix=new Dt,this.matrixWorld=new Dt,this.matrixAutoUpdate=_n.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=_n.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Nu,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Vs.setFromAxisAngle(e,t),this.quaternion.multiply(Vs),this}rotateOnWorldAxis(e,t){return Vs.setFromAxisAngle(e,t),this.quaternion.premultiply(Vs),this}rotateX(e){return this.rotateOnAxis(Uu,e)}rotateY(e){return this.rotateOnAxis(Fu,e)}rotateZ(e){return this.rotateOnAxis(Bu,e)}translateOnAxis(e,t){return Ou.copy(e).applyQuaternion(this.quaternion),this.position.add(Ou.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Uu,e)}translateY(e){return this.translateOnAxis(Fu,e)}translateZ(e){return this.translateOnAxis(Bu,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(_i.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Ta.copy(e):Ta.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),kr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?_i.lookAt(kr,Ta,this.up):_i.lookAt(Ta,kr,this.up),this.quaternion.setFromRotationMatrix(_i),s&&(_i.extractRotation(s.matrixWorld),Vs.setFromRotationMatrix(_i),this.quaternion.premultiply(Vs.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(tt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Vu),zs.child=e,this.dispatchEvent(zs),zs.child=null):tt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(hv),Yc.child=e,this.dispatchEvent(Yc),Yc.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),_i.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),_i.multiply(e.parent.matrixWorld)),e.applyMatrix4(_i),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Vu),zs.child=e,this.dispatchEvent(zs),zs.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(kr,e,dv),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(kr,uv,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(e.materials,this.material[c]));s.material=a}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];s.animations.push(r(e.animations,c))}}if(t){const a=o(e.geometries),c=o(e.materials),l=o(e.textures),d=o(e.images),u=o(e.shapes),h=o(e.skeletons),f=o(e.animations),g=o(e.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){const c=[];for(const l in a){const d=a[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}_n.DEFAULT_UP=new V(0,1,0),_n.DEFAULT_MATRIX_AUTO_UPDATE=!0,_n.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Nn=new V,bi=new V,Jc=new V,yi=new V,Gs=new V,Hs=new V,zu=new V,Zc=new V,Qc=new V,el=new V,tl=new Pt,nl=new Pt,il=new Pt;class On{constructor(e=new V,t=new V,n=new V){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Nn.subVectors(e,t),s.cross(Nn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Nn.subVectors(s,t),bi.subVectors(n,t),Jc.subVectors(e,t);const o=Nn.dot(Nn),a=Nn.dot(bi),c=Nn.dot(Jc),l=bi.dot(bi),d=bi.dot(Jc),u=o*l-a*a;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-a*d)*h,g=(o*d-a*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,yi)===null?!1:yi.x>=0&&yi.y>=0&&yi.x+yi.y<=1}static getInterpolation(e,t,n,s,r,o,a,c){return this.getBarycoord(e,t,n,s,yi)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,yi.x),c.addScaledVector(o,yi.y),c.addScaledVector(a,yi.z),c)}static getInterpolatedAttribute(e,t,n,s,r,o){return tl.setScalar(0),nl.setScalar(0),il.setScalar(0),tl.fromBufferAttribute(e,t),nl.fromBufferAttribute(e,n),il.fromBufferAttribute(e,s),o.setScalar(0),o.addScaledVector(tl,r.x),o.addScaledVector(nl,r.y),o.addScaledVector(il,r.z),o}static isFrontFacing(e,t,n,s){return Nn.subVectors(n,t),bi.subVectors(e,t),Nn.cross(bi).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Nn.subVectors(this.c,this.b),bi.subVectors(this.a,this.b),Nn.cross(bi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return On.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return On.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return On.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return On.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return On.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let o,a;Gs.subVectors(s,n),Hs.subVectors(r,n),Zc.subVectors(e,n);const c=Gs.dot(Zc),l=Hs.dot(Zc);if(c<=0&&l<=0)return t.copy(n);Qc.subVectors(e,s);const d=Gs.dot(Qc),u=Hs.dot(Qc);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(Gs,o);el.subVectors(e,r);const f=Gs.dot(el),g=Hs.dot(el);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(Hs,a);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return zu.subVectors(r,s),a=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(zu,a);const p=1/(m+v+h);return o=v*p,a=h*p,t.copy(n).addScaledVector(Gs,o).addScaledVector(Hs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Gu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ui={h:0,s:0,l:0},Ea={h:0,s:0,l:0};function sl(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Je{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=En){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ze.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=Ze.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ze.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=Ze.workingColorSpace){if(e=Zg(e,1),t=Ye(t,0,1),n=Ye(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=sl(o,r,e+1/3),this.g=sl(o,r,e),this.b=sl(o,r,e-1/3)}return Ze.colorSpaceToWorking(this,s),this}setStyle(e,t=En){function n(r){r!==void 0&&parseFloat(r)<1&&Oe("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Oe("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);Oe("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=En){const n=Gu[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Oe("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=pi(e.r),this.g=pi(e.g),this.b=pi(e.b),this}copyLinearToSRGB(e){return this.r=Ls(e.r),this.g=Ls(e.g),this.b=Ls(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=En){return Ze.workingToColorSpace(Qt.copy(this),e),Math.round(Ye(Qt.r*255,0,255))*65536+Math.round(Ye(Qt.g*255,0,255))*256+Math.round(Ye(Qt.b*255,0,255))}getHexString(e=En){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ze.workingColorSpace){Ze.workingToColorSpace(Qt.copy(this),t);const n=Qt.r,s=Qt.g,r=Qt.b,o=Math.max(n,s,r),a=Math.min(n,s,r);let c,l;const d=(a+o)/2;if(a===o)c=0,l=0;else{const u=o-a;switch(l=d<=.5?u/(o+a):u/(2-o-a),o){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=Ze.workingColorSpace){return Ze.workingToColorSpace(Qt.copy(this),t),e.r=Qt.r,e.g=Qt.g,e.b=Qt.b,e}getStyle(e=En){Ze.workingToColorSpace(Qt.copy(this),e);const t=Qt.r,n=Qt.g,s=Qt.b;return e!==En?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Ui),this.setHSL(Ui.h+e,Ui.s+t,Ui.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ui),e.getHSL(Ea);const n=Fc(Ui.h,Ea.h,t),s=Fc(Ui.s,Ea.s,t),r=Fc(Ui.l,Ea.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Qt=new Je;Je.NAMES=Gu;let fv=0;class Ca extends Ds{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:fv++}),this.uuid=Cr(),this.name="",this.type="Material",this.blending=ws,this.side=ci,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Oo,this.blendDst=Uo,this.blendEquation=ns,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Je(0,0,0),this.blendAlpha=0,this.depthFunc=As,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Tu,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Is,this.stencilZFail=Is,this.stencilZPass=Is,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Oe(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==ws&&(n.blending=this.blending),this.side!==ci&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Oo&&(n.blendSrc=this.blendSrc),this.blendDst!==Uo&&(n.blendDst=this.blendDst),this.blendEquation!==ns&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==As&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Tu&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Is&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Is&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Is&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const o=[];for(const a in r){const c=r[a];delete c.metadata,o.push(c)}return o}if(t){const r=s(e.textures),o=s(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Hu extends Ca{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Je(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new vi,this.combine=ou,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Lt=new V,Ma=new st;let pv=0;class Jn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:pv++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Eu,this.updateRanges=[],this.gpuType=$n,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Ma.fromBufferAttribute(this,t),Ma.applyMatrix3(e),this.setXY(t,Ma.x,Ma.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyMatrix3(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyMatrix4(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyNormalMatrix(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.transformDirection(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Mr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=dn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Mr(t,this.array)),t}setX(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Mr(t,this.array)),t}setY(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Mr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Mr(t,this.array)),t}setW(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array),s=dn(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array),s=dn(s,this.array),r=dn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Eu&&(e.usage=this.usage),e}}class Wu extends Jn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class qu extends Jn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class nn extends Jn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let mv=0;const Cn=new Dt,rl=new _n,Ws=new V,bn=new Ar,Ir=new Ar,Wt=new V;class Un extends Ds{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:mv++}),this.uuid=Cr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Mu(e)?qu:Wu)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new Ve().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Cn.makeRotationFromQuaternion(e),this.applyMatrix4(Cn),this}rotateX(e){return Cn.makeRotationX(e),this.applyMatrix4(Cn),this}rotateY(e){return Cn.makeRotationY(e),this.applyMatrix4(Cn),this}rotateZ(e){return Cn.makeRotationZ(e),this.applyMatrix4(Cn),this}translate(e,t,n){return Cn.makeTranslation(e,t,n),this.applyMatrix4(Cn),this}scale(e,t,n){return Cn.makeScale(e,t,n),this.applyMatrix4(Cn),this}lookAt(e){return rl.lookAt(e),rl.updateMatrix(),this.applyMatrix4(rl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Ws).negate(),this.translate(Ws.x,Ws.y,Ws.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const o=e[s];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new nn(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Oe("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ar);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new V(-1/0,-1/0,-1/0),new V(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];bn.setFromBufferAttribute(r),this.morphTargetsRelative?(Wt.addVectors(this.boundingBox.min,bn.min),this.boundingBox.expandByPoint(Wt),Wt.addVectors(this.boundingBox.max,bn.max),this.boundingBox.expandByPoint(Wt)):(this.boundingBox.expandByPoint(bn.min),this.boundingBox.expandByPoint(bn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&tt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new jc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new V,1/0);return}if(e){const n=this.boundingSphere.center;if(bn.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){const a=t[r];Ir.setFromBufferAttribute(a),this.morphTargetsRelative?(Wt.addVectors(bn.min,Ir.min),bn.expandByPoint(Wt),Wt.addVectors(bn.max,Ir.max),bn.expandByPoint(Wt)):(bn.expandByPoint(Ir.min),bn.expandByPoint(Ir.max))}bn.getCenter(n);let s=0;for(let r=0,o=e.count;r<o;r++)Wt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(Wt));if(t)for(let r=0,o=t.length;r<o;r++){const a=t[r],c=this.morphTargetsRelative;for(let l=0,d=a.count;l<d;l++)Wt.fromBufferAttribute(a,l),c&&(Ws.fromBufferAttribute(e,l),Wt.add(Ws)),s=Math.max(s,n.distanceToSquared(Wt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&tt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){tt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Jn(new Float32Array(4*n.count),4));const o=this.getAttribute("tangent"),a=[],c=[];for(let k=0;k<n.count;k++)a[k]=new V,c[k]=new V;const l=new V,d=new V,u=new V,h=new st,f=new st,g=new st,v=new V,m=new V;function p(k,y,x){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,y),u.fromBufferAttribute(n,x),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,y),g.fromBufferAttribute(r,x),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),a[k].add(v),a[y].add(v),a[x].add(v),c[k].add(m),c[y].add(m),c[x].add(m))}let T=this.groups;T.length===0&&(T=[{start:0,count:e.count}]);for(let k=0,y=T.length;k<y;++k){const x=T[k],R=x.start,O=x.count;for(let U=R,q=R+O;U<q;U+=3)p(e.getX(U+0),e.getX(U+1),e.getX(U+2))}const C=new V,_=new V,S=new V,E=new V;function w(k){S.fromBufferAttribute(s,k),E.copy(S);const y=a[k];C.copy(y),C.sub(S.multiplyScalar(S.dot(y))).normalize(),_.crossVectors(E,y);const R=_.dot(c[k])<0?-1:1;o.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,y=T.length;k<y;++k){const x=T[k],R=x.start,O=x.count;for(let U=R,q=R+O;U<q;U+=3)w(e.getX(U+0)),w(e.getX(U+1)),w(e.getX(U+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Jn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new V,r=new V,o=new V,a=new V,c=new V,l=new V,d=new V,u=new V;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),o.fromBufferAttribute(t,m),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),a.add(d),c.add(d),l.add(d),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),o.fromBufferAttribute(t,h+2),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Wt.fromBufferAttribute(e,t),Wt.normalize(),e.setXYZ(t,Wt.x,Wt.y,Wt.z)}toNonIndexed(){function e(a,c){const l=a.array,d=a.itemSize,u=a.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){a.isInterleavedBufferAttribute?f=c[v]*a.data.stride+a.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new Jn(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Un,n=this.index.array,s=this.attributes;for(const a in s){const c=s[a],l=e(c,n);t.setAttribute(a,l)}const r=this.morphAttributes;for(const a in r){const c=[],l=r[a];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,c=o.length;a<c;a++){const l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let l=0,d=o.length;l<d;l++){const u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const ju=new Dt,cs=new av,wa=new jc,Xu=new V,Aa=new V,Ra=new V,Pa=new V,al=new V,ka=new V,$u=new V,Ia=new V;class Fn extends _n{constructor(e=new Un,t=new Hu){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const a=this.morphTargetInfluences;if(r&&a){ka.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=a[c],u=r[c];d!==0&&(al.fromBufferAttribute(u,e),o?ka.addScaledVector(al,d):ka.addScaledVector(al.sub(t),d))}t.add(ka)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),wa.copy(n.boundingSphere),wa.applyMatrix4(r),cs.copy(e.ray).recast(e.near),!(wa.containsPoint(cs.origin)===!1&&(cs.intersectSphere(wa,Xu)===null||cs.origin.distanceToSquared(Xu)>(e.far-e.near)**2))&&(ju.copy(r).invert(),cs.copy(e.ray).applyMatrix4(ju),!(n.boundingBox!==null&&cs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,cs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),C=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let _=T,S=C;_<S;_+=3){const E=a.getX(_),w=a.getX(_+1),k=a.getX(_+2);s=Da(this,p,e,n,l,d,u,E,w,k),s&&(s.faceIndex=Math.floor(_/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(a.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=a.getX(m),C=a.getX(m+1),_=a.getX(m+2);s=Da(this,o,e,n,l,d,u,T,C,_),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),C=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let _=T,S=C;_<S;_+=3){const E=_,w=_+1,k=_+2;s=Da(this,p,e,n,l,d,u,E,w,k),s&&(s.faceIndex=Math.floor(_/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=m,C=m+1,_=m+2;s=Da(this,o,e,n,l,d,u,T,C,_),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function gv(i,e,t,n,s,r,o,a){let c;if(e.side===en?c=n.intersectTriangle(o,r,s,!0,a):c=n.intersectTriangle(s,r,o,e.side===ci,a),c===null)return null;Ia.copy(a),Ia.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(Ia);return l<t.near||l>t.far?null:{distance:l,point:Ia.clone(),object:i}}function Da(i,e,t,n,s,r,o,a,c,l){i.getVertexPosition(a,Aa),i.getVertexPosition(c,Ra),i.getVertexPosition(l,Pa);const d=gv(i,e,t,n,Aa,Ra,Pa,$u);if(d){const u=new V;On.getBarycoord($u,Aa,Ra,Pa,u),s&&(d.uv=On.getInterpolatedAttribute(s,a,c,l,u,new st)),r&&(d.uv1=On.getInterpolatedAttribute(r,a,c,l,u,new st)),o&&(d.normal=On.getInterpolatedAttribute(o,a,c,l,u,new V),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a,b:c,c:l,normal:new V,materialIndex:0};On.getNormal(Aa,Ra,Pa,h.normal),d.face=h,d.barycoord=u}return d}class Dr extends Un{constructor(e=1,t=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};const a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,s,o,2),g("x","z","y",1,-1,e,n,-t,s,o,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new nn(l,3)),this.setAttribute("normal",new nn(d,3)),this.setAttribute("uv",new nn(u,2));function g(v,m,p,T,C,_,S,E,w,k,y){const x=_/w,R=S/k,O=_/2,U=S/2,q=E/2,$=w+1,G=k+1;let W=0,ee=0;const ge=new V;for(let le=0;le<G;le++){const _e=le*R-U;for(let Be=0;Be<$;Be++){const Fe=Be*x-O;ge[v]=Fe*T,ge[m]=_e*C,ge[p]=q,l.push(ge.x,ge.y,ge.z),ge[v]=0,ge[m]=0,ge[p]=E>0?1:-1,d.push(ge.x,ge.y,ge.z),u.push(Be/w),u.push(1-le/k),W+=1}}for(let le=0;le<k;le++)for(let _e=0;_e<w;_e++){const Be=h+_e+$*le,Fe=h+_e+$*(le+1),Tt=h+(_e+1)+$*(le+1),ft=h+(_e+1)+$*le;c.push(Be,Fe,ft),c.push(Fe,Tt,ft),ee+=6}a.addGroup(f,ee,y),f+=ee,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Dr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function qs(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Oe("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function sn(i){const e={};for(let t=0;t<i.length;t++){const n=qs(i[t]);for(const s in n)e[s]=n[s]}return e}function vv(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Ku(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Ze.workingColorSpace}const _v={clone:qs,merge:sn};var bv=`void main() {
43
+ */const Lo="182",vg=0,su=1,_g=2,aa=1,bg=2,Sr=3,ci=0,en=1,li=2,di=0,Ms=1,No=2,ru=3,au=4,yg=5,ns=100,Sg=101,xg=102,Tg=103,Eg=104,Cg=200,Mg=201,wg=202,Ag=203,Oo=204,Uo=205,Rg=206,Pg=207,kg=208,Ig=209,Dg=210,Lg=211,Ng=212,Og=213,Ug=214,Fo=0,Bo=1,Vo=2,ws=3,zo=4,Go=5,Ho=6,Wo=7,ou=0,Fg=1,Bg=2,jn=0,cu=1,lu=2,du=3,uu=4,hu=5,fu=6,pu=7,mu=300,is=301,As=302,qo=303,jo=304,oa=306,Xo=1e3,ui=1001,$o=1002,$t=1003,Vg=1004,ca=1005,Jt=1006,Ko=1007,ss=1008,Tn=1009,gu=1010,vu=1011,xr=1012,Yo=1013,Xn=1014,$n=1015,hi=1016,Jo=1017,Zo=1018,Tr=1020,_u=35902,bu=35899,yu=1021,Su=1022,In=1023,fi=1026,rs=1027,xu=1028,Qo=1029,Rs=1030,ec=1031,tc=1033,la=33776,da=33777,ua=33778,ha=33779,nc=35840,ic=35841,sc=35842,rc=35843,ac=36196,oc=37492,cc=37496,lc=37488,dc=37489,uc=37490,hc=37491,fc=37808,pc=37809,mc=37810,gc=37811,vc=37812,_c=37813,bc=37814,yc=37815,Sc=37816,xc=37817,Tc=37818,Ec=37819,Cc=37820,Mc=37821,wc=36492,Ac=36494,Rc=36495,Pc=36283,kc=36284,Ic=36285,Dc=36286,zg=3200,Gg=0,Hg=1,Ii="",En="srgb",Ps="srgb-linear",fa="linear",ot="srgb",ks=7680,Tu=519,Wg=512,qg=513,jg=514,Lc=515,Xg=516,$g=517,Nc=518,Kg=519,Eu=35044,Cu="300 es",Kn=2e3,pa=2001;function Mu(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function ma(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Yg(){const i=ma("canvas");return i.style.display="block",i}const wu={};function Au(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function tt(...i){const e="THREE."+i.shift();console.error(e,...i)}function Er(...i){const e=i.join(" ");e in wu||(wu[e]=!0,Oe(...i))}function Jg(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class Is{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,o=s.length;r<o;r++)s[r].call(this,e);e.target=null}}}const Zt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Oc=Math.PI/180,Uc=180/Math.PI;function Cr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Zt[i&255]+Zt[i>>8&255]+Zt[i>>16&255]+Zt[i>>24&255]+"-"+Zt[e&255]+Zt[e>>8&255]+"-"+Zt[e>>16&15|64]+Zt[e>>24&255]+"-"+Zt[t&63|128]+Zt[t>>8&255]+"-"+Zt[t>>16&255]+Zt[t>>24&255]+Zt[n&255]+Zt[n>>8&255]+Zt[n>>16&255]+Zt[n>>24&255]).toLowerCase()}function Ye(i,e,t){return Math.max(e,Math.min(t,i))}function Zg(i,e){return(i%e+e)%e}function Fc(i,e,t){return(1-t)*i+t*e}function Mr(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function dn(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class st{constructor(e=0,t=0){st.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ye(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*s+e.x,this.y=r*s+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class wr{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,o,a){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[o+0],f=r[o+1],g=r[o+2],v=r[o+3];if(a<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(a>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-a;if(m<.9995){const T=Math.acos(m),C=Math.sin(T);p=Math.sin(p*T)/C,a=Math.sin(a*T)/C,c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a}else{c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a;const T=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=T,l*=T,d*=T,u*=T}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,o){const a=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[o],h=r[o+1],f=r[o+2],g=r[o+3];return e[t]=a*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-a*f,e[t+2]=l*g+d*f+a*h-c*u,e[t+3]=d*g-a*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),d=a(s/2),u=a(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(o){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Oe("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+a+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(o-s)*f}else if(n>a&&n>u){const f=2*Math.sqrt(1+n-a-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+o)/f,this._z=(r+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-n-u);this._w=(r-l)/f,this._x=(s+o)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-a);this._w=(o-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ye(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+o*a+s*l-r*c,this._y=s*d+o*c+r*a-n*l,this._z=r*d+o*l+n*c-s*a,this._w=o*d-n*a-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let c=1-t;if(a<.9995){const l=Math.acos(a),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class V{constructor(e=0,t=0,n=0){V.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Ru.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ru.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*s-a*n),d=2*(a*t-r*s),u=2*(r*n-o*t);return this.x=t+c*l+o*u-a*d,this.y=n+c*d+a*l-r*u,this.z=s+c*u+r*d-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=s*c-r*a,this.y=r*o-n*c,this.z=n*a-s*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Bc.copy(this).projectOnVector(e),this.sub(Bc)}reflect(e){return this.sub(Bc.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ye(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Bc=new V,Ru=new wr;class Ve{constructor(e,t,n,s,r,o,a,c,l){Ve.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l)}set(e,t,n,s,r,o,a,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=a,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=o,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],T=s[1],C=s[4],_=s[7],S=s[2],E=s[5],w=s[8];return r[0]=o*v+a*T+c*S,r[3]=o*m+a*C+c*E,r[6]=o*p+a*_+c*w,r[1]=l*v+d*T+u*S,r[4]=l*m+d*C+u*E,r[7]=l*p+d*_+u*w,r[2]=h*v+f*T+g*S,r[5]=h*m+f*C+g*E,r[8]=h*p+f*_+g*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8];return t*o*d-t*a*l-n*r*d+n*a*c+s*r*l-s*o*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=d*o-a*l,h=a*c-d*r,f=l*r-o*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(a*n-s*o)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-a*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(o*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,o,a){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-s*l,s*c,-s*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Vc.makeScale(e,t)),this}rotate(e){return this.premultiply(Vc.makeRotation(-e)),this}translate(e,t){return this.premultiply(Vc.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Vc=new Ve,Pu=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ku=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Qg(){const i={enabled:!0,workingColorSpace:Ps,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===ot&&(s.r=pi(s.r),s.g=pi(s.g),s.b=pi(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===ot&&(s.r=Ds(s.r),s.g=Ds(s.g),s.b=Ds(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ii?fa:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Er("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Er("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Ps]:{primaries:e,whitePoint:n,transfer:fa,toXYZ:Pu,fromXYZ:ku,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:En},outputColorSpaceConfig:{drawingBufferColorSpace:En}},[En]:{primaries:e,whitePoint:n,transfer:ot,toXYZ:Pu,fromXYZ:ku,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:En}}}),i}const Ze=Qg();function pi(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Ds(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Ls;class ev{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Ls===void 0&&(Ls=ma("canvas")),Ls.width=e.width,Ls.height=e.height;const s=Ls.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Ls}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=ma("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let o=0;o<r.length;o++)r[o]=pi(r[o]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(pi(t[n]/255)*255):t[n]=pi(t[n]);return{data:t,width:e.width,height:e.height}}else return Oe("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let tv=0;class zc{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:tv++}),this.uuid=Cr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let o=0,a=s.length;o<a;o++)s[o].isDataTexture?r.push(Gc(s[o].image)):r.push(Gc(s[o]))}else r=Gc(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Gc(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?ev.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Oe("Texture: Unable to serialize Texture."),{})}let nv=0;const Hc=new V;class tn extends Is{constructor(e=tn.DEFAULT_IMAGE,t=tn.DEFAULT_MAPPING,n=ui,s=ui,r=Jt,o=ss,a=In,c=Tn,l=tn.DEFAULT_ANISOTROPY,d=Ii){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nv++}),this.uuid=Cr(),this.name="",this.source=new zc(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new st(0,0),this.repeat=new st(1,1),this.center=new st(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Hc).x}get height(){return this.source.getSize(Hc).y}get depth(){return this.source.getSize(Hc).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Oe(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==mu)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Xo:e.x=e.x-Math.floor(e.x);break;case ui:e.x=e.x<0?0:1;break;case $o:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Xo:e.y=e.y-Math.floor(e.y);break;case ui:e.y=e.y<0?0:1;break;case $o:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=mu,tn.DEFAULT_ANISOTROPY=1;class Pt{constructor(e=0,t=0,n=0,s=1){Pt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*s+o[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const C=(l+1)/2,_=(f+1)/2,S=(p+1)/2,E=(d+h)/4,w=(u+v)/4,k=(g+m)/4;return C>_&&C>S?C<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(C),s=E/n,r=w/n):_>S?_<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(_),n=E/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=w/r,s=k/r),this.set(n,s,r,t),this}let T=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(T)<.001&&(T=1),this.x=(m-g)/T,this.y=(u-v)/T,this.z=(h-d)/T,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this.w=Ye(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this.w=Ye(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class iv extends Is{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Jt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new tn(s);this.textures=[];const o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:Jt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new zc(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Yn extends iv{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Iu extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=$t,this.minFilter=$t,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class sv extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=$t,this.minFilter=$t,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Ar{constructor(e=new V(1/0,1/0,1/0),t=new V(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Dn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Dn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Dn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,Dn):Dn.fromBufferAttribute(r,o),Dn.applyMatrix4(e.matrixWorld),this.expandByPoint(Dn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),ga.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),ga.copy(n.boundingBox)),ga.applyMatrix4(e.matrixWorld),this.union(ga)}const s=e.children;for(let r=0,o=s.length;r<o;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Dn),Dn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Rr),va.subVectors(this.max,Rr),Ns.subVectors(e.a,Rr),Os.subVectors(e.b,Rr),Us.subVectors(e.c,Rr),Di.subVectors(Os,Ns),Li.subVectors(Us,Os),as.subVectors(Ns,Us);let t=[0,-Di.z,Di.y,0,-Li.z,Li.y,0,-as.z,as.y,Di.z,0,-Di.x,Li.z,0,-Li.x,as.z,0,-as.x,-Di.y,Di.x,0,-Li.y,Li.x,0,-as.y,as.x,0];return!Wc(t,Ns,Os,Us,va)||(t=[1,0,0,0,1,0,0,0,1],!Wc(t,Ns,Os,Us,va))?!1:(_a.crossVectors(Di,Li),t=[_a.x,_a.y,_a.z],Wc(t,Ns,Os,Us,va))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Dn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Dn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(mi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),mi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),mi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),mi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),mi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),mi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),mi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),mi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(mi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const mi=[new V,new V,new V,new V,new V,new V,new V,new V],Dn=new V,ga=new Ar,Ns=new V,Os=new V,Us=new V,Di=new V,Li=new V,as=new V,Rr=new V,va=new V,_a=new V,os=new V;function Wc(i,e,t,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){os.fromArray(i,r);const a=s.x*Math.abs(os.x)+s.y*Math.abs(os.y)+s.z*Math.abs(os.z),c=e.dot(os),l=t.dot(os),d=n.dot(os);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>a)return!1}return!0}const rv=new Ar,Pr=new V,qc=new V;class jc{constructor(e=new V,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):rv.setFromPoints(e).getCenter(n);let s=0;for(let r=0,o=e.length;r<o;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Pr.subVectors(e,this.center);const t=Pr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(Pr,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(qc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Pr.copy(e.center).add(qc)),this.expandByPoint(Pr.copy(e.center).sub(qc))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const gi=new V,Xc=new V,ba=new V,Ni=new V,$c=new V,ya=new V,Kc=new V;class av{constructor(e=new V,t=new V(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,gi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=gi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(gi.copy(this.origin).addScaledVector(this.direction,t),gi.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Xc.copy(e).add(t).multiplyScalar(.5),ba.copy(t).sub(e).normalize(),Ni.copy(this.origin).sub(Xc);const r=e.distanceTo(t)*.5,o=-this.direction.dot(ba),a=Ni.dot(this.direction),c=-Ni.dot(ba),l=Ni.lengthSq(),d=Math.abs(1-o*o);let u,h,f,g;if(d>0)if(u=o*c-a,h=o*a-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+o*h+2*a)+h*(o*u+h+2*c)+l}else h=r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-o*r+a)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(o*r+a)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=o>0?-r:r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Xc).addScaledVector(ba,h),f}intersectSphere(e,t){gi.subVectors(e.center,this.origin);const n=gi.dot(this.direction),s=gi.dot(gi)-n*n,r=e.radius*e.radius;if(s>r)return null;const o=Math.sqrt(r-s),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,o,a,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,o=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,o=(e.min.y-h.y)*d),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o<s||isNaN(s))&&(s=o),u>=0?(a=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||a>s)||((a>n||n!==n)&&(n=a),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,gi)!==null}intersectTriangle(e,t,n,s,r){$c.subVectors(t,e),ya.subVectors(n,e),Kc.crossVectors($c,ya);let o=this.direction.dot(Kc),a;if(o>0){if(s)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Ni.subVectors(this.origin,e);const c=a*this.direction.dot(ya.crossVectors(Ni,ya));if(c<0)return null;const l=a*this.direction.dot($c.cross(Ni));if(l<0||c+l>o)return null;const d=-a*Ni.dot(Kc);return d<0?null:this.at(d/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Dt{constructor(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){Dt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=o,p[9]=a,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Dt().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/Fs.setFromMatrixColumn(e,0).length(),r=1/Fs.setFromMatrixColumn(e,1).length(),o=1/Fs.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-a*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=o*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*a,t[4]=g*a-f,t[8]=o*l,t[1]=o*u,t[5]=o*d,t[9]=-a,t[2]=f*a-g,t[6]=v+h*a,t[10]=o*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*a,t[4]=-o*u,t[8]=g+f*a,t[1]=f+g*a,t[5]=o*d,t[9]=v-h*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=o*d,t[9]=-a*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=o*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=a*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ov,e,cv)}lookAt(e,t,n){const s=this.elements;return vn.subVectors(e,t),vn.lengthSq()===0&&(vn.z=1),vn.normalize(),Oi.crossVectors(n,vn),Oi.lengthSq()===0&&(Math.abs(n.z)===1?vn.x+=1e-4:vn.z+=1e-4,vn.normalize(),Oi.crossVectors(n,vn)),Oi.normalize(),Sa.crossVectors(vn,Oi),s[0]=Oi.x,s[4]=Sa.x,s[8]=vn.x,s[1]=Oi.y,s[5]=Sa.y,s[9]=vn.y,s[2]=Oi.z,s[6]=Sa.z,s[10]=vn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],T=n[3],C=n[7],_=n[11],S=n[15],E=s[0],w=s[4],k=s[8],y=s[12],x=s[1],R=s[5],O=s[9],U=s[13],q=s[2],$=s[6],G=s[10],W=s[14],ee=s[3],ge=s[7],le=s[11],_e=s[15];return r[0]=o*E+a*x+c*q+l*ee,r[4]=o*w+a*R+c*$+l*ge,r[8]=o*k+a*O+c*G+l*le,r[12]=o*y+a*U+c*W+l*_e,r[1]=d*E+u*x+h*q+f*ee,r[5]=d*w+u*R+h*$+f*ge,r[9]=d*k+u*O+h*G+f*le,r[13]=d*y+u*U+h*W+f*_e,r[2]=g*E+v*x+m*q+p*ee,r[6]=g*w+v*R+m*$+p*ge,r[10]=g*k+v*O+m*G+p*le,r[14]=g*y+v*U+m*W+p*_e,r[3]=T*E+C*x+_*q+S*ee,r[7]=T*w+C*R+_*$+S*ge,r[11]=T*k+C*O+_*G+S*le,r[15]=T*y+C*U+_*W+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],T=c*f-l*h,C=a*f-l*u,_=a*h-c*u,S=o*f-l*d,E=o*h-c*d,w=o*u-a*d;return t*(v*T-m*C+p*_)-n*(g*T-m*S+p*E)+s*(g*C-v*S+p*w)-r*(g*_-v*E+m*w)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],T=u*m*l-v*h*l+v*c*f-a*m*f-u*c*p+a*h*p,C=g*h*l-d*m*l-g*c*f+o*m*f+d*c*p-o*h*p,_=d*v*l-g*u*l+g*a*f-o*v*f-d*a*p+o*u*p,S=g*u*c-d*v*c-g*a*h+o*v*h+d*a*m-o*u*m,E=t*T+n*C+s*_+r*S;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/E;return e[0]=T*w,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*w,e[2]=(a*m*r-v*c*r+v*s*l-n*m*l-a*s*p+n*c*p)*w,e[3]=(u*c*r-a*h*r-u*s*l+n*h*l+a*s*f-n*c*f)*w,e[4]=C*w,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*w,e[6]=(g*c*r-o*m*r-g*s*l+t*m*l+o*s*p-t*c*p)*w,e[7]=(o*h*r-d*c*r+d*s*l-t*h*l-o*s*f+t*c*f)*w,e[8]=_*w,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*w,e[10]=(o*v*r-g*a*r+g*n*l-t*v*l-o*n*p+t*a*p)*w,e[11]=(d*a*r-o*u*r-d*n*l+t*u*l+o*n*f-t*a*f)*w,e[12]=S*w,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*w,e[14]=(g*a*s-o*v*s-g*n*c+t*v*c+o*n*m-t*a*m)*w,e[15]=(o*u*s-d*a*s+d*n*c-t*u*c-o*n*h+t*a*h)*w,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,d=r*a;return this.set(l*o+n,l*a-s*c,l*c+s*a,0,l*a+s*c,d*a+n,d*c-s*o,0,l*c-s*a,d*c+s*o,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,o){return this.set(1,n,r,0,e,1,o,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,d=o+o,u=a+a,h=r*l,f=r*d,g=r*u,v=o*d,m=o*u,p=a*u,T=c*l,C=c*d,_=c*u,S=n.x,E=n.y,w=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+_)*S,s[2]=(g-C)*S,s[3]=0,s[4]=(f-_)*E,s[5]=(1-(h+p))*E,s[6]=(m+T)*E,s[7]=0,s[8]=(g+C)*w,s[9]=(m-T)*w,s[10]=(1-(h+v))*w,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=Fs.set(s[0],s[1],s[2]).length();const o=Fs.set(s[4],s[5],s[6]).length(),a=Fs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),Ln.copy(this);const l=1/r,d=1/o,u=1/a;return Ln.elements[0]*=l,Ln.elements[1]*=l,Ln.elements[2]*=l,Ln.elements[4]*=d,Ln.elements[5]*=d,Ln.elements[6]*=d,Ln.elements[8]*=u,Ln.elements[9]*=u,Ln.elements[10]*=u,t.setFromRotationMatrix(Ln),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,s,r,o,a=Kn,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(o-r),v=o*r/(o-r);else if(a===Kn)g=-(o+r)/(o-r),v=-2*o*r/(o-r);else if(a===pa)g=-o/(o-r),v=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,o,a=Kn,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(o-r),v=o/(o-r);else if(a===Kn)g=-2/(o-r),v=-(o+r)/(o-r);else if(a===pa)g=-1/(o-r),v=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const Fs=new V,Ln=new Dt,ov=new V(0,0,0),cv=new V(1,1,1),Oi=new V,Sa=new V,vn=new V,Du=new Dt,Lu=new wr;class vi{constructor(e=0,t=0,n=0,s=vi.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],o=s[4],a=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ye(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ye(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ye(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Ye(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Ye(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-Ye(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Oe("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Du.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Du,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Lu.setFromEuler(this),this.setFromQuaternion(Lu,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}vi.DEFAULT_ORDER="XYZ";class Nu{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let lv=0;const Ou=new V,Bs=new wr,_i=new Dt,xa=new V,kr=new V,dv=new V,uv=new wr,Uu=new V(1,0,0),Fu=new V(0,1,0),Bu=new V(0,0,1),Vu={type:"added"},hv={type:"removed"},Vs={type:"childadded",child:null},Yc={type:"childremoved",child:null};class _n extends Is{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:lv++}),this.uuid=Cr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=_n.DEFAULT_UP.clone();const e=new V,t=new vi,n=new wr,s=new V(1,1,1);function r(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Dt},normalMatrix:{value:new Ve}}),this.matrix=new Dt,this.matrixWorld=new Dt,this.matrixAutoUpdate=_n.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=_n.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Nu,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Bs.setFromAxisAngle(e,t),this.quaternion.multiply(Bs),this}rotateOnWorldAxis(e,t){return Bs.setFromAxisAngle(e,t),this.quaternion.premultiply(Bs),this}rotateX(e){return this.rotateOnAxis(Uu,e)}rotateY(e){return this.rotateOnAxis(Fu,e)}rotateZ(e){return this.rotateOnAxis(Bu,e)}translateOnAxis(e,t){return Ou.copy(e).applyQuaternion(this.quaternion),this.position.add(Ou.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Uu,e)}translateY(e){return this.translateOnAxis(Fu,e)}translateZ(e){return this.translateOnAxis(Bu,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(_i.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?xa.copy(e):xa.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),kr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?_i.lookAt(kr,xa,this.up):_i.lookAt(xa,kr,this.up),this.quaternion.setFromRotationMatrix(_i),s&&(_i.extractRotation(s.matrixWorld),Bs.setFromRotationMatrix(_i),this.quaternion.premultiply(Bs.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(tt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Vu),Vs.child=e,this.dispatchEvent(Vs),Vs.child=null):tt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(hv),Yc.child=e,this.dispatchEvent(Yc),Yc.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),_i.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),_i.multiply(e.parent.matrixWorld)),e.applyMatrix4(_i),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Vu),Vs.child=e,this.dispatchEvent(Vs),Vs.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(kr,e,dv),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(kr,uv,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(e.materials,this.material[c]));s.material=a}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];s.animations.push(r(e.animations,c))}}if(t){const a=o(e.geometries),c=o(e.materials),l=o(e.textures),d=o(e.images),u=o(e.shapes),h=o(e.skeletons),f=o(e.animations),g=o(e.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){const c=[];for(const l in a){const d=a[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}_n.DEFAULT_UP=new V(0,1,0),_n.DEFAULT_MATRIX_AUTO_UPDATE=!0,_n.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Nn=new V,bi=new V,Jc=new V,yi=new V,zs=new V,Gs=new V,zu=new V,Zc=new V,Qc=new V,el=new V,tl=new Pt,nl=new Pt,il=new Pt;class On{constructor(e=new V,t=new V,n=new V){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Nn.subVectors(e,t),s.cross(Nn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Nn.subVectors(s,t),bi.subVectors(n,t),Jc.subVectors(e,t);const o=Nn.dot(Nn),a=Nn.dot(bi),c=Nn.dot(Jc),l=bi.dot(bi),d=bi.dot(Jc),u=o*l-a*a;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-a*d)*h,g=(o*d-a*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,yi)===null?!1:yi.x>=0&&yi.y>=0&&yi.x+yi.y<=1}static getInterpolation(e,t,n,s,r,o,a,c){return this.getBarycoord(e,t,n,s,yi)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,yi.x),c.addScaledVector(o,yi.y),c.addScaledVector(a,yi.z),c)}static getInterpolatedAttribute(e,t,n,s,r,o){return tl.setScalar(0),nl.setScalar(0),il.setScalar(0),tl.fromBufferAttribute(e,t),nl.fromBufferAttribute(e,n),il.fromBufferAttribute(e,s),o.setScalar(0),o.addScaledVector(tl,r.x),o.addScaledVector(nl,r.y),o.addScaledVector(il,r.z),o}static isFrontFacing(e,t,n,s){return Nn.subVectors(n,t),bi.subVectors(e,t),Nn.cross(bi).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Nn.subVectors(this.c,this.b),bi.subVectors(this.a,this.b),Nn.cross(bi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return On.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return On.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return On.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return On.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return On.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let o,a;zs.subVectors(s,n),Gs.subVectors(r,n),Zc.subVectors(e,n);const c=zs.dot(Zc),l=Gs.dot(Zc);if(c<=0&&l<=0)return t.copy(n);Qc.subVectors(e,s);const d=zs.dot(Qc),u=Gs.dot(Qc);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(zs,o);el.subVectors(e,r);const f=zs.dot(el),g=Gs.dot(el);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(Gs,a);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return zu.subVectors(r,s),a=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(zu,a);const p=1/(m+v+h);return o=v*p,a=h*p,t.copy(n).addScaledVector(zs,o).addScaledVector(Gs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Gu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ui={h:0,s:0,l:0},Ta={h:0,s:0,l:0};function sl(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Je{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=En){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ze.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=Ze.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ze.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=Ze.workingColorSpace){if(e=Zg(e,1),t=Ye(t,0,1),n=Ye(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=sl(o,r,e+1/3),this.g=sl(o,r,e),this.b=sl(o,r,e-1/3)}return Ze.colorSpaceToWorking(this,s),this}setStyle(e,t=En){function n(r){r!==void 0&&parseFloat(r)<1&&Oe("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Oe("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);Oe("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=En){const n=Gu[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Oe("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=pi(e.r),this.g=pi(e.g),this.b=pi(e.b),this}copyLinearToSRGB(e){return this.r=Ds(e.r),this.g=Ds(e.g),this.b=Ds(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=En){return Ze.workingToColorSpace(Qt.copy(this),e),Math.round(Ye(Qt.r*255,0,255))*65536+Math.round(Ye(Qt.g*255,0,255))*256+Math.round(Ye(Qt.b*255,0,255))}getHexString(e=En){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ze.workingColorSpace){Ze.workingToColorSpace(Qt.copy(this),t);const n=Qt.r,s=Qt.g,r=Qt.b,o=Math.max(n,s,r),a=Math.min(n,s,r);let c,l;const d=(a+o)/2;if(a===o)c=0,l=0;else{const u=o-a;switch(l=d<=.5?u/(o+a):u/(2-o-a),o){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=Ze.workingColorSpace){return Ze.workingToColorSpace(Qt.copy(this),t),e.r=Qt.r,e.g=Qt.g,e.b=Qt.b,e}getStyle(e=En){Ze.workingToColorSpace(Qt.copy(this),e);const t=Qt.r,n=Qt.g,s=Qt.b;return e!==En?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Ui),this.setHSL(Ui.h+e,Ui.s+t,Ui.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ui),e.getHSL(Ta);const n=Fc(Ui.h,Ta.h,t),s=Fc(Ui.s,Ta.s,t),r=Fc(Ui.l,Ta.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Qt=new Je;Je.NAMES=Gu;let fv=0;class Ea extends Is{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:fv++}),this.uuid=Cr(),this.name="",this.type="Material",this.blending=Ms,this.side=ci,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Oo,this.blendDst=Uo,this.blendEquation=ns,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Je(0,0,0),this.blendAlpha=0,this.depthFunc=ws,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Tu,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ks,this.stencilZFail=ks,this.stencilZPass=ks,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Oe(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Ms&&(n.blending=this.blending),this.side!==ci&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Oo&&(n.blendSrc=this.blendSrc),this.blendDst!==Uo&&(n.blendDst=this.blendDst),this.blendEquation!==ns&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==ws&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Tu&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ks&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ks&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ks&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const o=[];for(const a in r){const c=r[a];delete c.metadata,o.push(c)}return o}if(t){const r=s(e.textures),o=s(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Hu extends Ea{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Je(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new vi,this.combine=ou,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Lt=new V,Ca=new st;let pv=0;class Jn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:pv++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Eu,this.updateRanges=[],this.gpuType=$n,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Ca.fromBufferAttribute(this,t),Ca.applyMatrix3(e),this.setXY(t,Ca.x,Ca.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyMatrix3(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyMatrix4(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.applyNormalMatrix(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Lt.fromBufferAttribute(this,t),Lt.transformDirection(e),this.setXYZ(t,Lt.x,Lt.y,Lt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Mr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=dn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Mr(t,this.array)),t}setX(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Mr(t,this.array)),t}setY(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Mr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Mr(t,this.array)),t}setW(e,t){return this.normalized&&(t=dn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array),s=dn(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=dn(t,this.array),n=dn(n,this.array),s=dn(s,this.array),r=dn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Eu&&(e.usage=this.usage),e}}class Wu extends Jn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class qu extends Jn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class nn extends Jn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let mv=0;const Cn=new Dt,rl=new _n,Hs=new V,bn=new Ar,Ir=new Ar,Wt=new V;class Un extends Is{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:mv++}),this.uuid=Cr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Mu(e)?qu:Wu)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new Ve().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Cn.makeRotationFromQuaternion(e),this.applyMatrix4(Cn),this}rotateX(e){return Cn.makeRotationX(e),this.applyMatrix4(Cn),this}rotateY(e){return Cn.makeRotationY(e),this.applyMatrix4(Cn),this}rotateZ(e){return Cn.makeRotationZ(e),this.applyMatrix4(Cn),this}translate(e,t,n){return Cn.makeTranslation(e,t,n),this.applyMatrix4(Cn),this}scale(e,t,n){return Cn.makeScale(e,t,n),this.applyMatrix4(Cn),this}lookAt(e){return rl.lookAt(e),rl.updateMatrix(),this.applyMatrix4(rl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Hs).negate(),this.translate(Hs.x,Hs.y,Hs.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const o=e[s];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new nn(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Oe("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ar);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new V(-1/0,-1/0,-1/0),new V(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];bn.setFromBufferAttribute(r),this.morphTargetsRelative?(Wt.addVectors(this.boundingBox.min,bn.min),this.boundingBox.expandByPoint(Wt),Wt.addVectors(this.boundingBox.max,bn.max),this.boundingBox.expandByPoint(Wt)):(this.boundingBox.expandByPoint(bn.min),this.boundingBox.expandByPoint(bn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&tt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new jc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new V,1/0);return}if(e){const n=this.boundingSphere.center;if(bn.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){const a=t[r];Ir.setFromBufferAttribute(a),this.morphTargetsRelative?(Wt.addVectors(bn.min,Ir.min),bn.expandByPoint(Wt),Wt.addVectors(bn.max,Ir.max),bn.expandByPoint(Wt)):(bn.expandByPoint(Ir.min),bn.expandByPoint(Ir.max))}bn.getCenter(n);let s=0;for(let r=0,o=e.count;r<o;r++)Wt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(Wt));if(t)for(let r=0,o=t.length;r<o;r++){const a=t[r],c=this.morphTargetsRelative;for(let l=0,d=a.count;l<d;l++)Wt.fromBufferAttribute(a,l),c&&(Hs.fromBufferAttribute(e,l),Wt.add(Hs)),s=Math.max(s,n.distanceToSquared(Wt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&tt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){tt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Jn(new Float32Array(4*n.count),4));const o=this.getAttribute("tangent"),a=[],c=[];for(let k=0;k<n.count;k++)a[k]=new V,c[k]=new V;const l=new V,d=new V,u=new V,h=new st,f=new st,g=new st,v=new V,m=new V;function p(k,y,x){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,y),u.fromBufferAttribute(n,x),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,y),g.fromBufferAttribute(r,x),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),a[k].add(v),a[y].add(v),a[x].add(v),c[k].add(m),c[y].add(m),c[x].add(m))}let T=this.groups;T.length===0&&(T=[{start:0,count:e.count}]);for(let k=0,y=T.length;k<y;++k){const x=T[k],R=x.start,O=x.count;for(let U=R,q=R+O;U<q;U+=3)p(e.getX(U+0),e.getX(U+1),e.getX(U+2))}const C=new V,_=new V,S=new V,E=new V;function w(k){S.fromBufferAttribute(s,k),E.copy(S);const y=a[k];C.copy(y),C.sub(S.multiplyScalar(S.dot(y))).normalize(),_.crossVectors(E,y);const R=_.dot(c[k])<0?-1:1;o.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,y=T.length;k<y;++k){const x=T[k],R=x.start,O=x.count;for(let U=R,q=R+O;U<q;U+=3)w(e.getX(U+0)),w(e.getX(U+1)),w(e.getX(U+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Jn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new V,r=new V,o=new V,a=new V,c=new V,l=new V,d=new V,u=new V;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),o.fromBufferAttribute(t,m),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),a.add(d),c.add(d),l.add(d),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),o.fromBufferAttribute(t,h+2),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Wt.fromBufferAttribute(e,t),Wt.normalize(),e.setXYZ(t,Wt.x,Wt.y,Wt.z)}toNonIndexed(){function e(a,c){const l=a.array,d=a.itemSize,u=a.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){a.isInterleavedBufferAttribute?f=c[v]*a.data.stride+a.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new Jn(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Un,n=this.index.array,s=this.attributes;for(const a in s){const c=s[a],l=e(c,n);t.setAttribute(a,l)}const r=this.morphAttributes;for(const a in r){const c=[],l=r[a];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,c=o.length;a<c;a++){const l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let l=0,d=o.length;l<d;l++){const u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const ju=new Dt,cs=new av,Ma=new jc,Xu=new V,wa=new V,Aa=new V,Ra=new V,al=new V,Pa=new V,$u=new V,ka=new V;class Fn extends _n{constructor(e=new Un,t=new Hu){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const a=this.morphTargetInfluences;if(r&&a){Pa.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=a[c],u=r[c];d!==0&&(al.fromBufferAttribute(u,e),o?Pa.addScaledVector(al,d):Pa.addScaledVector(al.sub(t),d))}t.add(Pa)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Ma.copy(n.boundingSphere),Ma.applyMatrix4(r),cs.copy(e.ray).recast(e.near),!(Ma.containsPoint(cs.origin)===!1&&(cs.intersectSphere(Ma,Xu)===null||cs.origin.distanceToSquared(Xu)>(e.far-e.near)**2))&&(ju.copy(r).invert(),cs.copy(e.ray).applyMatrix4(ju),!(n.boundingBox!==null&&cs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,cs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),C=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let _=T,S=C;_<S;_+=3){const E=a.getX(_),w=a.getX(_+1),k=a.getX(_+2);s=Ia(this,p,e,n,l,d,u,E,w,k),s&&(s.faceIndex=Math.floor(_/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(a.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=a.getX(m),C=a.getX(m+1),_=a.getX(m+2);s=Ia(this,o,e,n,l,d,u,T,C,_),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),C=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let _=T,S=C;_<S;_+=3){const E=_,w=_+1,k=_+2;s=Ia(this,p,e,n,l,d,u,E,w,k),s&&(s.faceIndex=Math.floor(_/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=m,C=m+1,_=m+2;s=Ia(this,o,e,n,l,d,u,T,C,_),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function gv(i,e,t,n,s,r,o,a){let c;if(e.side===en?c=n.intersectTriangle(o,r,s,!0,a):c=n.intersectTriangle(s,r,o,e.side===ci,a),c===null)return null;ka.copy(a),ka.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(ka);return l<t.near||l>t.far?null:{distance:l,point:ka.clone(),object:i}}function Ia(i,e,t,n,s,r,o,a,c,l){i.getVertexPosition(a,wa),i.getVertexPosition(c,Aa),i.getVertexPosition(l,Ra);const d=gv(i,e,t,n,wa,Aa,Ra,$u);if(d){const u=new V;On.getBarycoord($u,wa,Aa,Ra,u),s&&(d.uv=On.getInterpolatedAttribute(s,a,c,l,u,new st)),r&&(d.uv1=On.getInterpolatedAttribute(r,a,c,l,u,new st)),o&&(d.normal=On.getInterpolatedAttribute(o,a,c,l,u,new V),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a,b:c,c:l,normal:new V,materialIndex:0};On.getNormal(wa,Aa,Ra,h.normal),d.face=h,d.barycoord=u}return d}class Dr extends Un{constructor(e=1,t=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};const a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,s,o,2),g("x","z","y",1,-1,e,n,-t,s,o,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new nn(l,3)),this.setAttribute("normal",new nn(d,3)),this.setAttribute("uv",new nn(u,2));function g(v,m,p,T,C,_,S,E,w,k,y){const x=_/w,R=S/k,O=_/2,U=S/2,q=E/2,$=w+1,G=k+1;let W=0,ee=0;const ge=new V;for(let le=0;le<G;le++){const _e=le*R-U;for(let Be=0;Be<$;Be++){const Fe=Be*x-O;ge[v]=Fe*T,ge[m]=_e*C,ge[p]=q,l.push(ge.x,ge.y,ge.z),ge[v]=0,ge[m]=0,ge[p]=E>0?1:-1,d.push(ge.x,ge.y,ge.z),u.push(Be/w),u.push(1-le/k),W+=1}}for(let le=0;le<k;le++)for(let _e=0;_e<w;_e++){const Be=h+_e+$*le,Fe=h+_e+$*(le+1),Tt=h+(_e+1)+$*(le+1),ht=h+(_e+1)+$*le;c.push(Be,Fe,ht),c.push(Fe,Tt,ht),ee+=6}a.addGroup(f,ee,y),f+=ee,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Dr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Ws(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Oe("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function sn(i){const e={};for(let t=0;t<i.length;t++){const n=Ws(i[t]);for(const s in n)e[s]=n[s]}return e}function vv(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Ku(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Ze.workingColorSpace}const _v={clone:Ws,merge:sn};var bv=`void main() {
44
44
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
45
45
  }`,yv=`void main() {
46
46
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
47
- }`;class Mn extends Ca{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=bv,this.fragmentShader=yv,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=qs(e.uniforms),this.uniformsGroups=vv(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Yu extends _n{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Dt,this.projectionMatrix=new Dt,this.projectionMatrixInverse=new Dt,this.coordinateSystem=Kn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Fi=new V,Ju=new st,Zu=new st;class wn extends Yu{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Uc*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Oc*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Uc*2*Math.atan(Math.tan(Oc*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Fi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Fi.x,Fi.y).multiplyScalar(-e/Fi.z),Fi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Fi.x,Fi.y).multiplyScalar(-e/Fi.z)}getViewSize(e,t){return this.getViewBounds(e,Ju,Zu),t.subVectors(Zu,Ju)}setViewOffset(e,t,n,s,r,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Oc*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*s/c,t-=o.offsetY*n/l,s*=o.width/c,n*=o.height/l}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const js=-90,Xs=1;class Sv extends _n{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new wn(js,Xs,e,t);s.layers=this.layers,this.add(s);const r=new wn(js,Xs,e,t);r.layers=this.layers,this.add(r);const o=new wn(js,Xs,e,t);o.layers=this.layers,this.add(o);const a=new wn(js,Xs,e,t);a.layers=this.layers,this.add(a);const c=new wn(js,Xs,e,t);c.layers=this.layers,this.add(c);const l=new wn(js,Xs,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,o,a,c]=t;for(const l of t)this.remove(l);if(e===Kn)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===ma)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,o,a,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,o),e.setRenderTarget(n,2,s),e.render(t,a),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class Qu extends tn{constructor(e=[],t=is,n,s,r,o,a,c,l,d){super(e,t,n,s,r,o,a,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class eh extends Yn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new Qu(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
47
+ }`;class Mn extends Ea{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=bv,this.fragmentShader=yv,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ws(e.uniforms),this.uniformsGroups=vv(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Yu extends _n{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Dt,this.projectionMatrix=new Dt,this.projectionMatrixInverse=new Dt,this.coordinateSystem=Kn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Fi=new V,Ju=new st,Zu=new st;class wn extends Yu{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Uc*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Oc*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Uc*2*Math.atan(Math.tan(Oc*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Fi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Fi.x,Fi.y).multiplyScalar(-e/Fi.z),Fi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Fi.x,Fi.y).multiplyScalar(-e/Fi.z)}getViewSize(e,t){return this.getViewBounds(e,Ju,Zu),t.subVectors(Zu,Ju)}setViewOffset(e,t,n,s,r,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Oc*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*s/c,t-=o.offsetY*n/l,s*=o.width/c,n*=o.height/l}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qs=-90,js=1;class Sv extends _n{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new wn(qs,js,e,t);s.layers=this.layers,this.add(s);const r=new wn(qs,js,e,t);r.layers=this.layers,this.add(r);const o=new wn(qs,js,e,t);o.layers=this.layers,this.add(o);const a=new wn(qs,js,e,t);a.layers=this.layers,this.add(a);const c=new wn(qs,js,e,t);c.layers=this.layers,this.add(c);const l=new wn(qs,js,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,o,a,c]=t;for(const l of t)this.remove(l);if(e===Kn)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===pa)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,o,a,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,o),e.setRenderTarget(n,2,s),e.render(t,a),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class Qu extends tn{constructor(e=[],t=is,n,s,r,o,a,c,l,d){super(e,t,n,s,r,o,a,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class eh extends Yn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new Qu(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
48
48
 
49
49
  varying vec3 vWorldDirection;
50
50
 
@@ -79,7 +79,7 @@
79
79
  gl_FragColor = texture2D( tEquirect, sampleUV );
80
80
 
81
81
  }
82
- `},s=new Dr(5,5,5),r=new Mn({name:"CubemapFromEquirect",uniforms:qs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:en,blending:di});r.uniforms.tEquirect.value=t;const o=new Fn(s,r),a=t.minFilter;return t.minFilter===ss&&(t.minFilter=Jt),new Sv(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}}class La extends _n{constructor(){super(),this.isGroup=!0,this.type="Group"}}const xv={type:"move"};class ol{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new La,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new La,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new V,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new V),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new La,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new V,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new V),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(xv)))}return a!==null&&(a.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new La;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Tv extends _n{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new vi,this.environmentIntensity=1,this.environmentRotation=new vi,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Ev extends tn{constructor(e=null,t=1,n=1,s,r,o,a,c,l=$t,d=$t,u,h){super(null,o,a,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const cl=new V,Cv=new V,Mv=new Ve;class ls{constructor(e=new V(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=cl.subVectors(n,t).cross(Cv.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(cl),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Mv.getNormalMatrix(e),s=this.coplanarPoint(cl).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ds=new jc,wv=new st(.5,.5),Na=new V;class th{constructor(e=new ls,t=new ls,n=new ls,s=new ls,r=new ls,o=new ls){this.planes=[e,t,n,s,r,o]}set(e,t,n,s,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(s),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Kn,n=!1){const s=this.planes,r=e.elements,o=r[0],a=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],T=r[12],C=r[13],_=r[14],S=r[15];if(s[0].setComponents(l-o,f-d,p-g,S-T).normalize(),s[1].setComponents(l+o,f+d,p+g,S+T).normalize(),s[2].setComponents(l+a,f+u,p+v,S+C).normalize(),s[3].setComponents(l-a,f-u,p-v,S-C).normalize(),n)s[4].setComponents(c,h,m,_).normalize(),s[5].setComponents(l-c,f-h,p-m,S-_).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-_).normalize(),t===Kn)s[5].setComponents(l+c,f+h,p+m,S+_).normalize();else if(t===ma)s[5].setComponents(c,h,m,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ds.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ds.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ds)}intersectsSprite(e){ds.center.set(0,0,0);const t=wv.distanceTo(e.center);return ds.radius=.7071067811865476+t,ds.applyMatrix4(e.matrixWorld),this.intersectsSphere(ds)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(Na.x=s.normal.x>0?e.max.x:e.min.x,Na.y=s.normal.y>0?e.max.y:e.min.y,Na.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Na)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Lr extends tn{constructor(e,t,n=Xn,s,r,o,a=$t,c=$t,l,d=fi,u=1){if(d!==fi&&d!==rs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,o,a,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new zc(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Av extends Lr{constructor(e,t=Xn,n=is,s,r,o=$t,a=$t,c,l=fi){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,o,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class nh extends tn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ll extends Un{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],o=[];a(s),l(n),d(),this.setAttribute("position",new nn(r,3)),this.setAttribute("normal",new nn(r.slice(),3)),this.setAttribute("uv",new nn(o,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function a(T){const C=new V,_=new V,S=new V;for(let E=0;E<t.length;E+=3)f(t[E+0],C),f(t[E+1],_),f(t[E+2],S),c(C,_,S,T)}function c(T,C,_,S){const E=S+1,w=[];for(let k=0;k<=E;k++){w[k]=[];const y=T.clone().lerp(_,k/E),x=C.clone().lerp(_,k/E),R=E-k;for(let O=0;O<=R;O++)O===0&&k===E?w[k][O]=y:w[k][O]=y.clone().lerp(x,O/R)}for(let k=0;k<E;k++)for(let y=0;y<2*(E-k)-1;y++){const x=Math.floor(y/2);y%2===0?(h(w[k][x+1]),h(w[k+1][x]),h(w[k][x])):(h(w[k][x+1]),h(w[k+1][x+1]),h(w[k+1][x]))}}function l(T){const C=new V;for(let _=0;_<r.length;_+=3)C.x=r[_+0],C.y=r[_+1],C.z=r[_+2],C.normalize().multiplyScalar(T),r[_+0]=C.x,r[_+1]=C.y,r[_+2]=C.z}function d(){const T=new V;for(let C=0;C<r.length;C+=3){T.x=r[C+0],T.y=r[C+1],T.z=r[C+2];const _=m(T)/2/Math.PI+.5,S=p(T)/Math.PI+.5;o.push(_,1-S)}g(),u()}function u(){for(let T=0;T<o.length;T+=6){const C=o[T+0],_=o[T+2],S=o[T+4],E=Math.max(C,_,S),w=Math.min(C,_,S);E>.9&&w<.1&&(C<.2&&(o[T+0]+=1),_<.2&&(o[T+2]+=1),S<.2&&(o[T+4]+=1))}}function h(T){r.push(T.x,T.y,T.z)}function f(T,C){const _=T*3;C.x=e[_+0],C.y=e[_+1],C.z=e[_+2]}function g(){const T=new V,C=new V,_=new V,S=new V,E=new st,w=new st,k=new st;for(let y=0,x=0;y<r.length;y+=9,x+=6){T.set(r[y+0],r[y+1],r[y+2]),C.set(r[y+3],r[y+4],r[y+5]),_.set(r[y+6],r[y+7],r[y+8]),E.set(o[x+0],o[x+1]),w.set(o[x+2],o[x+3]),k.set(o[x+4],o[x+5]),S.copy(T).add(C).add(_).divideScalar(3);const R=m(S);v(E,x+0,T,R),v(w,x+2,C,R),v(k,x+4,_,R)}}function v(T,C,_,S){S<0&&T.x===1&&(o[C]=T.x-1),_.x===0&&_.z===0&&(o[C]=S/2/Math.PI+.5)}function m(T){return Math.atan2(T.z,-T.x)}function p(T){return Math.atan2(-T.y,Math.sqrt(T.x*T.x+T.z*T.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ll(e.vertices,e.indices,e.radius,e.detail)}}class dl extends ll{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new dl(e.radius,e.detail)}}class Oa extends Un{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,o=t/2,a=Math.floor(n),c=Math.floor(s),l=a+1,d=c+1,u=e/a,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const T=p*h-o;for(let C=0;C<l;C++){const _=C*u-r;g.push(_,-T,0),v.push(0,0,1),m.push(C/a),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let T=0;T<a;T++){const C=T+l*p,_=T+l*(p+1),S=T+1+l*(p+1),E=T+1+l*p;f.push(C,_,E),f.push(_,S,E)}this.setIndex(f),this.setAttribute("position",new nn(g,3)),this.setAttribute("normal",new nn(v,3)),this.setAttribute("uv",new nn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Oa(e.width,e.height,e.widthSegments,e.heightSegments)}}class ul extends Un{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(o+a,Math.PI);let l=0;const d=[],u=new V,h=new V,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const T=[],C=p/n;let _=0;p===0&&o===0?_=.5/t:p===n&&c===Math.PI&&(_=-.5/t);for(let S=0;S<=t;S++){const E=S/t;u.x=-e*Math.cos(s+E*r)*Math.sin(o+C*a),u.y=e*Math.cos(o+C*a),u.z=e*Math.sin(s+E*r)*Math.sin(o+C*a),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(E+_,1-C),T.push(l++)}d.push(T)}for(let p=0;p<n;p++)for(let T=0;T<t;T++){const C=d[p][T+1],_=d[p][T],S=d[p+1][T],E=d[p+1][T+1];(p!==0||o>0)&&f.push(C,_,E),(p!==n-1||c<Math.PI)&&f.push(_,S,E)}this.setIndex(f),this.setAttribute("position",new nn(g,3)),this.setAttribute("normal",new nn(v,3)),this.setAttribute("uv",new nn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ul(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Rv extends Mn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Pv extends Ca{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=zg,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class kv extends Ca{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class ih extends Yu{constructor(e=-1,t=1,n=1,s=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,o=n+e,a=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=d*this.view.offsetY,c=a-d*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class Iv extends wn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Dv{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function sh(i,e,t,n){const s=Lv(n);switch(t){case yu:return i*e;case xu:return i*e/s.components*s.byteLength;case Qo:return i*e/s.components*s.byteLength;case Ps:return i*e*2/s.components*s.byteLength;case ec:return i*e*2/s.components*s.byteLength;case Su:return i*e*3/s.components*s.byteLength;case In:return i*e*4/s.components*s.byteLength;case tc:return i*e*4/s.components*s.byteLength;case da:case ua:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case ha:case fa:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case ic:case rc:return Math.max(i,16)*Math.max(e,8)/4;case nc:case sc:return Math.max(i,8)*Math.max(e,8)/2;case ac:case oc:case lc:case dc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case cc:case uc:case hc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case fc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case pc:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case mc:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case gc:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case vc:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case _c:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case bc:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case yc:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case Sc:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case xc:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case Tc:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case Ec:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Cc:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case Mc:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case wc:case Ac:case Rc:return Math.ceil(i/4)*Math.ceil(e/4)*16;case Pc:case kc:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Ic:case Dc:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Lv(i){switch(i){case Tn:case gu:return{byteLength:1,components:1};case xr:case vu:case hi:return{byteLength:2,components:1};case Jo:case Zo:return{byteLength:2,components:4};case Xn:case Yo:case $n:return{byteLength:4,components:1};case _u:case bu:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Lo}})),typeof window<"u"&&(window.__THREE__?Oe("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Lo);/**
82
+ `},s=new Dr(5,5,5),r=new Mn({name:"CubemapFromEquirect",uniforms:Ws(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:en,blending:di});r.uniforms.tEquirect.value=t;const o=new Fn(s,r),a=t.minFilter;return t.minFilter===ss&&(t.minFilter=Jt),new Sv(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}}class Da extends _n{constructor(){super(),this.isGroup=!0,this.type="Group"}}const xv={type:"move"};class ol{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Da,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Da,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new V,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new V),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Da,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new V,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new V),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(xv)))}return a!==null&&(a.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Da;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Tv extends _n{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new vi,this.environmentIntensity=1,this.environmentRotation=new vi,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Ev extends tn{constructor(e=null,t=1,n=1,s,r,o,a,c,l=$t,d=$t,u,h){super(null,o,a,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const cl=new V,Cv=new V,Mv=new Ve;class ls{constructor(e=new V(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=cl.subVectors(n,t).cross(Cv.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(cl),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Mv.getNormalMatrix(e),s=this.coplanarPoint(cl).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ds=new jc,wv=new st(.5,.5),La=new V;class th{constructor(e=new ls,t=new ls,n=new ls,s=new ls,r=new ls,o=new ls){this.planes=[e,t,n,s,r,o]}set(e,t,n,s,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(s),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Kn,n=!1){const s=this.planes,r=e.elements,o=r[0],a=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],T=r[12],C=r[13],_=r[14],S=r[15];if(s[0].setComponents(l-o,f-d,p-g,S-T).normalize(),s[1].setComponents(l+o,f+d,p+g,S+T).normalize(),s[2].setComponents(l+a,f+u,p+v,S+C).normalize(),s[3].setComponents(l-a,f-u,p-v,S-C).normalize(),n)s[4].setComponents(c,h,m,_).normalize(),s[5].setComponents(l-c,f-h,p-m,S-_).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-_).normalize(),t===Kn)s[5].setComponents(l+c,f+h,p+m,S+_).normalize();else if(t===pa)s[5].setComponents(c,h,m,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ds.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ds.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ds)}intersectsSprite(e){ds.center.set(0,0,0);const t=wv.distanceTo(e.center);return ds.radius=.7071067811865476+t,ds.applyMatrix4(e.matrixWorld),this.intersectsSphere(ds)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(La.x=s.normal.x>0?e.max.x:e.min.x,La.y=s.normal.y>0?e.max.y:e.min.y,La.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(La)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Lr extends tn{constructor(e,t,n=Xn,s,r,o,a=$t,c=$t,l,d=fi,u=1){if(d!==fi&&d!==rs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,o,a,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new zc(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Av extends Lr{constructor(e,t=Xn,n=is,s,r,o=$t,a=$t,c,l=fi){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,o,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class nh extends tn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ll extends Un{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],o=[];a(s),l(n),d(),this.setAttribute("position",new nn(r,3)),this.setAttribute("normal",new nn(r.slice(),3)),this.setAttribute("uv",new nn(o,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function a(T){const C=new V,_=new V,S=new V;for(let E=0;E<t.length;E+=3)f(t[E+0],C),f(t[E+1],_),f(t[E+2],S),c(C,_,S,T)}function c(T,C,_,S){const E=S+1,w=[];for(let k=0;k<=E;k++){w[k]=[];const y=T.clone().lerp(_,k/E),x=C.clone().lerp(_,k/E),R=E-k;for(let O=0;O<=R;O++)O===0&&k===E?w[k][O]=y:w[k][O]=y.clone().lerp(x,O/R)}for(let k=0;k<E;k++)for(let y=0;y<2*(E-k)-1;y++){const x=Math.floor(y/2);y%2===0?(h(w[k][x+1]),h(w[k+1][x]),h(w[k][x])):(h(w[k][x+1]),h(w[k+1][x+1]),h(w[k+1][x]))}}function l(T){const C=new V;for(let _=0;_<r.length;_+=3)C.x=r[_+0],C.y=r[_+1],C.z=r[_+2],C.normalize().multiplyScalar(T),r[_+0]=C.x,r[_+1]=C.y,r[_+2]=C.z}function d(){const T=new V;for(let C=0;C<r.length;C+=3){T.x=r[C+0],T.y=r[C+1],T.z=r[C+2];const _=m(T)/2/Math.PI+.5,S=p(T)/Math.PI+.5;o.push(_,1-S)}g(),u()}function u(){for(let T=0;T<o.length;T+=6){const C=o[T+0],_=o[T+2],S=o[T+4],E=Math.max(C,_,S),w=Math.min(C,_,S);E>.9&&w<.1&&(C<.2&&(o[T+0]+=1),_<.2&&(o[T+2]+=1),S<.2&&(o[T+4]+=1))}}function h(T){r.push(T.x,T.y,T.z)}function f(T,C){const _=T*3;C.x=e[_+0],C.y=e[_+1],C.z=e[_+2]}function g(){const T=new V,C=new V,_=new V,S=new V,E=new st,w=new st,k=new st;for(let y=0,x=0;y<r.length;y+=9,x+=6){T.set(r[y+0],r[y+1],r[y+2]),C.set(r[y+3],r[y+4],r[y+5]),_.set(r[y+6],r[y+7],r[y+8]),E.set(o[x+0],o[x+1]),w.set(o[x+2],o[x+3]),k.set(o[x+4],o[x+5]),S.copy(T).add(C).add(_).divideScalar(3);const R=m(S);v(E,x+0,T,R),v(w,x+2,C,R),v(k,x+4,_,R)}}function v(T,C,_,S){S<0&&T.x===1&&(o[C]=T.x-1),_.x===0&&_.z===0&&(o[C]=S/2/Math.PI+.5)}function m(T){return Math.atan2(T.z,-T.x)}function p(T){return Math.atan2(-T.y,Math.sqrt(T.x*T.x+T.z*T.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ll(e.vertices,e.indices,e.radius,e.detail)}}class dl extends ll{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new dl(e.radius,e.detail)}}class Na extends Un{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,o=t/2,a=Math.floor(n),c=Math.floor(s),l=a+1,d=c+1,u=e/a,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const T=p*h-o;for(let C=0;C<l;C++){const _=C*u-r;g.push(_,-T,0),v.push(0,0,1),m.push(C/a),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let T=0;T<a;T++){const C=T+l*p,_=T+l*(p+1),S=T+1+l*(p+1),E=T+1+l*p;f.push(C,_,E),f.push(_,S,E)}this.setIndex(f),this.setAttribute("position",new nn(g,3)),this.setAttribute("normal",new nn(v,3)),this.setAttribute("uv",new nn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Na(e.width,e.height,e.widthSegments,e.heightSegments)}}class ul extends Un{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(o+a,Math.PI);let l=0;const d=[],u=new V,h=new V,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const T=[],C=p/n;let _=0;p===0&&o===0?_=.5/t:p===n&&c===Math.PI&&(_=-.5/t);for(let S=0;S<=t;S++){const E=S/t;u.x=-e*Math.cos(s+E*r)*Math.sin(o+C*a),u.y=e*Math.cos(o+C*a),u.z=e*Math.sin(s+E*r)*Math.sin(o+C*a),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(E+_,1-C),T.push(l++)}d.push(T)}for(let p=0;p<n;p++)for(let T=0;T<t;T++){const C=d[p][T+1],_=d[p][T],S=d[p+1][T],E=d[p+1][T+1];(p!==0||o>0)&&f.push(C,_,E),(p!==n-1||c<Math.PI)&&f.push(_,S,E)}this.setIndex(f),this.setAttribute("position",new nn(g,3)),this.setAttribute("normal",new nn(v,3)),this.setAttribute("uv",new nn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ul(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Rv extends Mn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Pv extends Ea{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=zg,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class kv extends Ea{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class ih extends Yu{constructor(e=-1,t=1,n=1,s=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,o=n+e,a=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=d*this.view.offsetY,c=a-d*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class Iv extends wn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Dv{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function sh(i,e,t,n){const s=Lv(n);switch(t){case yu:return i*e;case xu:return i*e/s.components*s.byteLength;case Qo:return i*e/s.components*s.byteLength;case Rs:return i*e*2/s.components*s.byteLength;case ec:return i*e*2/s.components*s.byteLength;case Su:return i*e*3/s.components*s.byteLength;case In:return i*e*4/s.components*s.byteLength;case tc:return i*e*4/s.components*s.byteLength;case la:case da:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case ua:case ha:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case ic:case rc:return Math.max(i,16)*Math.max(e,8)/4;case nc:case sc:return Math.max(i,8)*Math.max(e,8)/2;case ac:case oc:case lc:case dc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case cc:case uc:case hc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case fc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case pc:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case mc:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case gc:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case vc:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case _c:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case bc:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case yc:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case Sc:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case xc:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case Tc:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case Ec:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Cc:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case Mc:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case wc:case Ac:case Rc:return Math.ceil(i/4)*Math.ceil(e/4)*16;case Pc:case kc:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Ic:case Dc:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Lv(i){switch(i){case Tn:case gu:return{byteLength:1,components:1};case xr:case vu:case hi:return{byteLength:2,components:1};case Jo:case Zo:return{byteLength:2,components:4};case Xn:case Yo:case $n:return{byteLength:4,components:1};case _u:case bu:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Lo}})),typeof window<"u"&&(window.__THREE__?Oe("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Lo);/**
83
83
  * @license
84
84
  * Copyright 2010-2025 Three.js Authors
85
85
  * SPDX-License-Identifier: MIT
@@ -3648,7 +3648,7 @@ void main() {
3648
3648
  #include <tonemapping_fragment>
3649
3649
  #include <colorspace_fragment>
3650
3650
  #include <fog_fragment>
3651
- }`},me={common:{diffuse:{value:new Je(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ve}},envmap:{envMap:{value:null},envMapRotation:{value:new Ve},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ve}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ve}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ve},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ve},normalScale:{value:new st(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ve},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ve}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ve}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ve}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Je(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Je(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0},uvTransform:{value:new Ve}},sprite:{diffuse:{value:new Je(16777215)},opacity:{value:1},center:{value:new st(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}}},Zn={basic:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.fog,me.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.fog,me.lights,{emissive:{value:new Je(0)},specular:{value:new Je(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:sn([me.common,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.roughnessmap,me.metalnessmap,me.fog,me.lights,{emissive:{value:new Je(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:sn([me.common,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.gradientmap,me.fog,me.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:sn([me.common,me.bumpmap,me.normalmap,me.displacementmap,me.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:sn([me.points,me.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:sn([me.common,me.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:sn([me.common,me.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:sn([me.common,me.bumpmap,me.normalmap,me.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:sn([me.sprite,me.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Ve},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ve}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:sn([me.common,me.displacementmap,{referencePosition:{value:new V},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:sn([me.lights,me.fog,{color:{value:new Je(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};Zn.physical={uniforms:sn([Zn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ve},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ve},clearcoatNormalScale:{value:new st(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ve},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ve},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ve},sheen:{value:0},sheenColor:{value:new Je(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ve},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ve},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ve},transmissionSamplerSize:{value:new st},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ve},attenuationDistance:{value:0},attenuationColor:{value:new Je(0)},specularColor:{value:new Je(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ve},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ve},anisotropyVector:{value:new st},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ve}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const Ua={r:0,b:0,g:0},us=new vi,N_=new Dt;function O_(i,e,t,n,s,r,o){const a=new Je(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(C){let _=C.isScene===!0?C.background:null;return _&&_.isTexture&&(_=(C.backgroundBlurriness>0?t:e).get(_)),_}function v(C){let _=!1;const S=g(C);S===null?p(a,c):S&&S.isColor&&(p(S,1),_=!0);const E=i.xr.getEnvironmentBlendMode();E==="additive"?n.buffers.color.setClear(0,0,0,1,o):E==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(i.autoClear||_)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(C,_){const S=g(_);S&&(S.isCubeTexture||S.mapping===ca)?(d===void 0&&(d=new Fn(new Dr(1,1,1),new Mn({name:"BackgroundCubeMaterial",uniforms:qs(Zn.backgroundCube.uniforms),vertexShader:Zn.backgroundCube.vertexShader,fragmentShader:Zn.backgroundCube.fragmentShader,side:en,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(E,w,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),us.copy(_.backgroundRotation),us.x*=-1,us.y*=-1,us.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(us.y*=-1,us.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(N_.makeRotationFromEuler(us)),d.material.toneMapped=Ze.getTransfer(S.colorSpace)!==ct,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),C.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Fn(new Oa(2,2),new Mn({name:"BackgroundMaterial",uniforms:qs(Zn.background.uniforms),vertexShader:Zn.background.vertexShader,fragmentShader:Zn.background.fragmentShader,side:ci,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.toneMapped=Ze.getTransfer(S.colorSpace)!==ct,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),C.unshift(l,l.geometry,l.material,0,0,null))}function p(C,_){C.getRGB(Ua,Ku(i)),n.buffers.color.setClear(Ua.r,Ua.g,Ua.b,_,o)}function T(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(C,_=1){a.set(C),c=_,p(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(C){c=C,p(a,c)},render:v,addToRenderList:m,dispose:T}}function U_(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,o=!1;function a(x,R,O,U,q){let $=!1;const G=u(U,O,R);r!==G&&(r=G,l(r.object)),$=f(x,U,O,q),$&&g(x,U,O,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),($||o)&&(o=!1,_(x,R,O,U),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(x){return i.bindVertexArray(x)}function d(x){return i.deleteVertexArray(x)}function u(x,R,O){const U=O.wireframe===!0;let q=n[x.id];q===void 0&&(q={},n[x.id]=q);let $=q[R.id];$===void 0&&($={},q[R.id]=$);let G=$[U];return G===void 0&&(G=h(c()),$[U]=G),G}function h(x){const R=[],O=[],U=[];for(let q=0;q<t;q++)R[q]=0,O[q]=0,U[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:O,attributeDivisors:U,object:x,attributes:{},index:null}}function f(x,R,O,U){const q=r.attributes,$=R.attributes;let G=0;const W=O.getAttributes();for(const ee in W)if(W[ee].location>=0){const le=q[ee];let _e=$[ee];if(_e===void 0&&(ee==="instanceMatrix"&&x.instanceMatrix&&(_e=x.instanceMatrix),ee==="instanceColor"&&x.instanceColor&&(_e=x.instanceColor)),le===void 0||le.attribute!==_e||_e&&le.data!==_e.data)return!0;G++}return r.attributesNum!==G||r.index!==U}function g(x,R,O,U){const q={},$=R.attributes;let G=0;const W=O.getAttributes();for(const ee in W)if(W[ee].location>=0){let le=$[ee];le===void 0&&(ee==="instanceMatrix"&&x.instanceMatrix&&(le=x.instanceMatrix),ee==="instanceColor"&&x.instanceColor&&(le=x.instanceColor));const _e={};_e.attribute=le,le&&le.data&&(_e.data=le.data),q[ee]=_e,G++}r.attributes=q,r.attributesNum=G,r.index=U}function v(){const x=r.newAttributes;for(let R=0,O=x.length;R<O;R++)x[R]=0}function m(x){p(x,0)}function p(x,R){const O=r.newAttributes,U=r.enabledAttributes,q=r.attributeDivisors;O[x]=1,U[x]===0&&(i.enableVertexAttribArray(x),U[x]=1),q[x]!==R&&(i.vertexAttribDivisor(x,R),q[x]=R)}function T(){const x=r.newAttributes,R=r.enabledAttributes;for(let O=0,U=R.length;O<U;O++)R[O]!==x[O]&&(i.disableVertexAttribArray(O),R[O]=0)}function C(x,R,O,U,q,$,G){G===!0?i.vertexAttribIPointer(x,R,O,q,$):i.vertexAttribPointer(x,R,O,U,q,$)}function _(x,R,O,U){v();const q=U.attributes,$=O.getAttributes(),G=R.defaultAttributeValues;for(const W in $){const ee=$[W];if(ee.location>=0){let ge=q[W];if(ge===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(ge=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(ge=x.instanceColor)),ge!==void 0){const le=ge.normalized,_e=ge.itemSize,Be=e.get(ge);if(Be===void 0)continue;const Fe=Be.buffer,Tt=Be.type,ft=Be.bytesPerElement,K=Tt===i.INT||Tt===i.UNSIGNED_INT||ge.gpuType===Yo;if(ge.isInterleavedBufferAttribute){const ne=ge.data,xe=ne.stride,Ge=ge.offset;if(ne.isInstancedInterleavedBuffer){for(let Ce=0;Ce<ee.locationSize;Ce++)p(ee.location+Ce,ne.meshPerAttribute);x.isInstancedMesh!==!0&&U._maxInstanceCount===void 0&&(U._maxInstanceCount=ne.meshPerAttribute*ne.count)}else for(let Ce=0;Ce<ee.locationSize;Ce++)m(ee.location+Ce);i.bindBuffer(i.ARRAY_BUFFER,Fe);for(let Ce=0;Ce<ee.locationSize;Ce++)C(ee.location+Ce,_e/ee.locationSize,Tt,le,xe*ft,(Ge+_e/ee.locationSize*Ce)*ft,K)}else{if(ge.isInstancedBufferAttribute){for(let ne=0;ne<ee.locationSize;ne++)p(ee.location+ne,ge.meshPerAttribute);x.isInstancedMesh!==!0&&U._maxInstanceCount===void 0&&(U._maxInstanceCount=ge.meshPerAttribute*ge.count)}else for(let ne=0;ne<ee.locationSize;ne++)m(ee.location+ne);i.bindBuffer(i.ARRAY_BUFFER,Fe);for(let ne=0;ne<ee.locationSize;ne++)C(ee.location+ne,_e/ee.locationSize,Tt,le,_e*ft,_e/ee.locationSize*ne*ft,K)}}else if(G!==void 0){const le=G[W];if(le!==void 0)switch(le.length){case 2:i.vertexAttrib2fv(ee.location,le);break;case 3:i.vertexAttrib3fv(ee.location,le);break;case 4:i.vertexAttrib4fv(ee.location,le);break;default:i.vertexAttrib1fv(ee.location,le)}}}}T()}function S(){k();for(const x in n){const R=n[x];for(const O in R){const U=R[O];for(const q in U)d(U[q].object),delete U[q];delete R[O]}delete n[x]}}function E(x){if(n[x.id]===void 0)return;const R=n[x.id];for(const O in R){const U=R[O];for(const q in U)d(U[q].object),delete U[q];delete R[O]}delete n[x.id]}function w(x){for(const R in n){const O=n[R];if(O[x.id]===void 0)continue;const U=O[x.id];for(const q in U)d(U[q].object),delete U[q];delete O[x.id]}}function k(){y(),o=!0,r!==s&&(r=s,l(r.object))}function y(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:a,reset:k,resetDefaultState:y,dispose:S,releaseStatesOfGeometry:E,releaseStatesOfProgram:w,initAttributes:v,enableAttribute:m,disableUnusedAttributes:T}}function F_(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function o(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function a(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)o(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function B_(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const w=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function o(w){return!(w!==In&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(w){const k=w===hi&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(w!==Tn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&w!==$n&&!k)}function c(w){if(w==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Oe("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),C=i.getParameter(i.MAX_VARYING_VECTORS),_=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),E=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:T,maxVaryings:C,maxFragmentUniforms:_,maxSamples:S,samples:E}}function V_(i){const e=this;let t=null,n=0,s=!1,r=!1;const o=new ls,a=new Ve,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const T=r?0:n,C=T*4;let _=p.clippingState||null;c.value=_,_=d(g,h,C,f);for(let S=0;S!==C;++S)_[S]=t[S];p.clippingState=_,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=T}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,T=h.matrixWorldInverse;a.getNormalMatrix(T),(m===null||m.length<p)&&(m=new Float32Array(p));for(let C=0,_=f;C!==v;++C,_+=4)o.copy(u[C]).applyMatrix4(T,a),o.normal.toArray(m,_),m[_+3]=o.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function z_(i){let e=new WeakMap;function t(o,a){return a===qo?o.mapping=is:a===jo&&(o.mapping=Rs),o}function n(o){if(o&&o.isTexture){const a=o.mapping;if(a===qo||a===jo)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new eh(c.height);return l.fromEquirectangularTexture(i,o),e.set(o,l),o.addEventListener("dispose",s),t(l.texture,o.mapping)}else return null}}return o}function s(o){const a=o.target;a.removeEventListener("dispose",s);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const Bi=4,ah=[.125,.215,.35,.446,.526,.582],hs=20,G_=256,Nr=new ih,oh=new Je;let hl=null,fl=0,pl=0,ml=!1;const H_=new V;class ch{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:o=256,position:a=H_}=r;hl=this._renderer.getRenderTarget(),fl=this._renderer.getActiveCubeFace(),pl=this._renderer.getActiveMipmapLevel(),ml=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=uh(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=dh(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(hl,fl,pl),this._renderer.xr.enabled=ml,e.scissorTest=!1,$s(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===is||e.mapping===Rs?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),hl=this._renderer.getRenderTarget(),fl=this._renderer.getActiveCubeFace(),pl=this._renderer.getActiveMipmapLevel(),ml=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Jt,minFilter:Jt,generateMipmaps:!1,type:hi,format:In,colorSpace:ks,depthBuffer:!1},s=lh(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=lh(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=W_(r)),this._blurMaterial=j_(r,e,t),this._ggxMaterial=q_(r,e,t)}return s}_compileMaterial(e){const t=new Fn(new Un,e);this._renderer.compile(t,Nr)}_sceneToCubeUV(e,t,n,s,r){const c=new wn(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(oh),u.toneMapping=jn,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Fn(new Dr,new Hu({name:"PMREM.Background",side:en,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const T=e.background;T?T.isColor&&(m.color.copy(T),e.background=null,p=!0):(m.color.copy(oh),p=!0);for(let C=0;C<6;C++){const _=C%3;_===0?(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[C],r.y,r.z)):_===1?(c.up.set(0,0,l[C]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[C],r.z)):(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[C]));const S=this._cubeSize;$s(s,_*S,C>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=T}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===is||e.mapping===Rs;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=uh()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=dh());const r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;const a=r.uniforms;a.envMap.value=e;const c=this._cubeSize;$s(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,Nr)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const c=o.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-Bi?n-g+Bi:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,$s(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(a,Nr),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,$s(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(a,Nr)}_blur(e,t,n,s,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,s,"latitudinal",r),this._halfBlur(o,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,o,a){const c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&tt("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*hs-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):hs;m>hs&&Oe(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${hs}`);const p=[];let T=0;for(let w=0;w<hs;++w){const k=w/v,y=Math.exp(-k*k/2);p.push(y),w===0?T+=y:w<m&&(T+=2*y)}for(let w=0;w<p.length;w++)p[w]=p[w]/T;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=o==="latitudinal",a&&(h.poleAxis.value=a);const{_lodMax:C}=this;h.dTheta.value=g,h.mipInt.value=C-n;const _=this._sizeLods[s],S=3*_*(s>C-Bi?s-C+Bi:0),E=4*(this._cubeSize-_);$s(t,S,E,3*_,2*_),c.setRenderTarget(t),c.render(u,Nr)}}function W_(i){const e=[],t=[],n=[];let s=i;const r=i-Bi+1+ah.length;for(let o=0;o<r;o++){const a=Math.pow(2,s);e.push(a);let c=1/a;o>i-Bi?c=ah[o-i+Bi-1]:o===0&&(c=0),t.push(c);const l=1/(a-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,T=new Float32Array(v*g*f),C=new Float32Array(m*g*f),_=new Float32Array(p*g*f);for(let E=0;E<f;E++){const w=E%3*2/3-1,k=E>2?0:-1,y=[w,k,0,w+2/3,k,0,w+2/3,k+1,0,w,k,0,w+2/3,k+1,0,w,k+1,0];T.set(y,v*g*E),C.set(h,m*g*E);const x=[E,E,E,E,E,E];_.set(x,p*g*E)}const S=new Un;S.setAttribute("position",new Jn(T,v)),S.setAttribute("uv",new Jn(C,m)),S.setAttribute("faceIndex",new Jn(_,p)),n.push(new Fn(S,null)),s>Bi&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function lh(i,e,t){const n=new Yn(i,e,t);return n.texture.mapping=ca,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function $s(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function q_(i,e,t){return new Mn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:G_,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Fa(),fragmentShader:`
3651
+ }`},me={common:{diffuse:{value:new Je(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ve}},envmap:{envMap:{value:null},envMapRotation:{value:new Ve},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ve}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ve}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ve},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ve},normalScale:{value:new st(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ve},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ve}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ve}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ve}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Je(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Je(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0},uvTransform:{value:new Ve}},sprite:{diffuse:{value:new Je(16777215)},opacity:{value:1},center:{value:new st(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}}},Zn={basic:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.fog,me.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:sn([me.common,me.specularmap,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.fog,me.lights,{emissive:{value:new Je(0)},specular:{value:new Je(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:sn([me.common,me.envmap,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.roughnessmap,me.metalnessmap,me.fog,me.lights,{emissive:{value:new Je(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:sn([me.common,me.aomap,me.lightmap,me.emissivemap,me.bumpmap,me.normalmap,me.displacementmap,me.gradientmap,me.fog,me.lights,{emissive:{value:new Je(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:sn([me.common,me.bumpmap,me.normalmap,me.displacementmap,me.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:sn([me.points,me.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:sn([me.common,me.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:sn([me.common,me.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:sn([me.common,me.bumpmap,me.normalmap,me.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:sn([me.sprite,me.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Ve},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ve}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:sn([me.common,me.displacementmap,{referencePosition:{value:new V},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:sn([me.lights,me.fog,{color:{value:new Je(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};Zn.physical={uniforms:sn([Zn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ve},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ve},clearcoatNormalScale:{value:new st(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ve},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ve},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ve},sheen:{value:0},sheenColor:{value:new Je(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ve},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ve},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ve},transmissionSamplerSize:{value:new st},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ve},attenuationDistance:{value:0},attenuationColor:{value:new Je(0)},specularColor:{value:new Je(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ve},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ve},anisotropyVector:{value:new st},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ve}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const Oa={r:0,b:0,g:0},us=new vi,N_=new Dt;function O_(i,e,t,n,s,r,o){const a=new Je(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(C){let _=C.isScene===!0?C.background:null;return _&&_.isTexture&&(_=(C.backgroundBlurriness>0?t:e).get(_)),_}function v(C){let _=!1;const S=g(C);S===null?p(a,c):S&&S.isColor&&(p(S,1),_=!0);const E=i.xr.getEnvironmentBlendMode();E==="additive"?n.buffers.color.setClear(0,0,0,1,o):E==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(i.autoClear||_)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(C,_){const S=g(_);S&&(S.isCubeTexture||S.mapping===oa)?(d===void 0&&(d=new Fn(new Dr(1,1,1),new Mn({name:"BackgroundCubeMaterial",uniforms:Ws(Zn.backgroundCube.uniforms),vertexShader:Zn.backgroundCube.vertexShader,fragmentShader:Zn.backgroundCube.fragmentShader,side:en,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(E,w,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),us.copy(_.backgroundRotation),us.x*=-1,us.y*=-1,us.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(us.y*=-1,us.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(N_.makeRotationFromEuler(us)),d.material.toneMapped=Ze.getTransfer(S.colorSpace)!==ot,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),C.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Fn(new Na(2,2),new Mn({name:"BackgroundMaterial",uniforms:Ws(Zn.background.uniforms),vertexShader:Zn.background.vertexShader,fragmentShader:Zn.background.fragmentShader,side:ci,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.toneMapped=Ze.getTransfer(S.colorSpace)!==ot,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),C.unshift(l,l.geometry,l.material,0,0,null))}function p(C,_){C.getRGB(Oa,Ku(i)),n.buffers.color.setClear(Oa.r,Oa.g,Oa.b,_,o)}function T(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(C,_=1){a.set(C),c=_,p(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(C){c=C,p(a,c)},render:v,addToRenderList:m,dispose:T}}function U_(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,o=!1;function a(x,R,O,U,q){let $=!1;const G=u(U,O,R);r!==G&&(r=G,l(r.object)),$=f(x,U,O,q),$&&g(x,U,O,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),($||o)&&(o=!1,_(x,R,O,U),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(x){return i.bindVertexArray(x)}function d(x){return i.deleteVertexArray(x)}function u(x,R,O){const U=O.wireframe===!0;let q=n[x.id];q===void 0&&(q={},n[x.id]=q);let $=q[R.id];$===void 0&&($={},q[R.id]=$);let G=$[U];return G===void 0&&(G=h(c()),$[U]=G),G}function h(x){const R=[],O=[],U=[];for(let q=0;q<t;q++)R[q]=0,O[q]=0,U[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:O,attributeDivisors:U,object:x,attributes:{},index:null}}function f(x,R,O,U){const q=r.attributes,$=R.attributes;let G=0;const W=O.getAttributes();for(const ee in W)if(W[ee].location>=0){const le=q[ee];let _e=$[ee];if(_e===void 0&&(ee==="instanceMatrix"&&x.instanceMatrix&&(_e=x.instanceMatrix),ee==="instanceColor"&&x.instanceColor&&(_e=x.instanceColor)),le===void 0||le.attribute!==_e||_e&&le.data!==_e.data)return!0;G++}return r.attributesNum!==G||r.index!==U}function g(x,R,O,U){const q={},$=R.attributes;let G=0;const W=O.getAttributes();for(const ee in W)if(W[ee].location>=0){let le=$[ee];le===void 0&&(ee==="instanceMatrix"&&x.instanceMatrix&&(le=x.instanceMatrix),ee==="instanceColor"&&x.instanceColor&&(le=x.instanceColor));const _e={};_e.attribute=le,le&&le.data&&(_e.data=le.data),q[ee]=_e,G++}r.attributes=q,r.attributesNum=G,r.index=U}function v(){const x=r.newAttributes;for(let R=0,O=x.length;R<O;R++)x[R]=0}function m(x){p(x,0)}function p(x,R){const O=r.newAttributes,U=r.enabledAttributes,q=r.attributeDivisors;O[x]=1,U[x]===0&&(i.enableVertexAttribArray(x),U[x]=1),q[x]!==R&&(i.vertexAttribDivisor(x,R),q[x]=R)}function T(){const x=r.newAttributes,R=r.enabledAttributes;for(let O=0,U=R.length;O<U;O++)R[O]!==x[O]&&(i.disableVertexAttribArray(O),R[O]=0)}function C(x,R,O,U,q,$,G){G===!0?i.vertexAttribIPointer(x,R,O,q,$):i.vertexAttribPointer(x,R,O,U,q,$)}function _(x,R,O,U){v();const q=U.attributes,$=O.getAttributes(),G=R.defaultAttributeValues;for(const W in $){const ee=$[W];if(ee.location>=0){let ge=q[W];if(ge===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(ge=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(ge=x.instanceColor)),ge!==void 0){const le=ge.normalized,_e=ge.itemSize,Be=e.get(ge);if(Be===void 0)continue;const Fe=Be.buffer,Tt=Be.type,ht=Be.bytesPerElement,K=Tt===i.INT||Tt===i.UNSIGNED_INT||ge.gpuType===Yo;if(ge.isInterleavedBufferAttribute){const ne=ge.data,xe=ne.stride,Ge=ge.offset;if(ne.isInstancedInterleavedBuffer){for(let Ce=0;Ce<ee.locationSize;Ce++)p(ee.location+Ce,ne.meshPerAttribute);x.isInstancedMesh!==!0&&U._maxInstanceCount===void 0&&(U._maxInstanceCount=ne.meshPerAttribute*ne.count)}else for(let Ce=0;Ce<ee.locationSize;Ce++)m(ee.location+Ce);i.bindBuffer(i.ARRAY_BUFFER,Fe);for(let Ce=0;Ce<ee.locationSize;Ce++)C(ee.location+Ce,_e/ee.locationSize,Tt,le,xe*ht,(Ge+_e/ee.locationSize*Ce)*ht,K)}else{if(ge.isInstancedBufferAttribute){for(let ne=0;ne<ee.locationSize;ne++)p(ee.location+ne,ge.meshPerAttribute);x.isInstancedMesh!==!0&&U._maxInstanceCount===void 0&&(U._maxInstanceCount=ge.meshPerAttribute*ge.count)}else for(let ne=0;ne<ee.locationSize;ne++)m(ee.location+ne);i.bindBuffer(i.ARRAY_BUFFER,Fe);for(let ne=0;ne<ee.locationSize;ne++)C(ee.location+ne,_e/ee.locationSize,Tt,le,_e*ht,_e/ee.locationSize*ne*ht,K)}}else if(G!==void 0){const le=G[W];if(le!==void 0)switch(le.length){case 2:i.vertexAttrib2fv(ee.location,le);break;case 3:i.vertexAttrib3fv(ee.location,le);break;case 4:i.vertexAttrib4fv(ee.location,le);break;default:i.vertexAttrib1fv(ee.location,le)}}}}T()}function S(){k();for(const x in n){const R=n[x];for(const O in R){const U=R[O];for(const q in U)d(U[q].object),delete U[q];delete R[O]}delete n[x]}}function E(x){if(n[x.id]===void 0)return;const R=n[x.id];for(const O in R){const U=R[O];for(const q in U)d(U[q].object),delete U[q];delete R[O]}delete n[x.id]}function w(x){for(const R in n){const O=n[R];if(O[x.id]===void 0)continue;const U=O[x.id];for(const q in U)d(U[q].object),delete U[q];delete O[x.id]}}function k(){y(),o=!0,r!==s&&(r=s,l(r.object))}function y(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:a,reset:k,resetDefaultState:y,dispose:S,releaseStatesOfGeometry:E,releaseStatesOfProgram:w,initAttributes:v,enableAttribute:m,disableUnusedAttributes:T}}function F_(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function o(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function a(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)o(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function B_(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const w=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function o(w){return!(w!==In&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(w){const k=w===hi&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(w!==Tn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&w!==$n&&!k)}function c(w){if(w==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Oe("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),C=i.getParameter(i.MAX_VARYING_VECTORS),_=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),E=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:T,maxVaryings:C,maxFragmentUniforms:_,maxSamples:S,samples:E}}function V_(i){const e=this;let t=null,n=0,s=!1,r=!1;const o=new ls,a=new Ve,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const T=r?0:n,C=T*4;let _=p.clippingState||null;c.value=_,_=d(g,h,C,f);for(let S=0;S!==C;++S)_[S]=t[S];p.clippingState=_,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=T}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,T=h.matrixWorldInverse;a.getNormalMatrix(T),(m===null||m.length<p)&&(m=new Float32Array(p));for(let C=0,_=f;C!==v;++C,_+=4)o.copy(u[C]).applyMatrix4(T,a),o.normal.toArray(m,_),m[_+3]=o.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function z_(i){let e=new WeakMap;function t(o,a){return a===qo?o.mapping=is:a===jo&&(o.mapping=As),o}function n(o){if(o&&o.isTexture){const a=o.mapping;if(a===qo||a===jo)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new eh(c.height);return l.fromEquirectangularTexture(i,o),e.set(o,l),o.addEventListener("dispose",s),t(l.texture,o.mapping)}else return null}}return o}function s(o){const a=o.target;a.removeEventListener("dispose",s);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const Bi=4,ah=[.125,.215,.35,.446,.526,.582],hs=20,G_=256,Nr=new ih,oh=new Je;let hl=null,fl=0,pl=0,ml=!1;const H_=new V;class ch{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:o=256,position:a=H_}=r;hl=this._renderer.getRenderTarget(),fl=this._renderer.getActiveCubeFace(),pl=this._renderer.getActiveMipmapLevel(),ml=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=uh(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=dh(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(hl,fl,pl),this._renderer.xr.enabled=ml,e.scissorTest=!1,Xs(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===is||e.mapping===As?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),hl=this._renderer.getRenderTarget(),fl=this._renderer.getActiveCubeFace(),pl=this._renderer.getActiveMipmapLevel(),ml=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Jt,minFilter:Jt,generateMipmaps:!1,type:hi,format:In,colorSpace:Ps,depthBuffer:!1},s=lh(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=lh(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=W_(r)),this._blurMaterial=j_(r,e,t),this._ggxMaterial=q_(r,e,t)}return s}_compileMaterial(e){const t=new Fn(new Un,e);this._renderer.compile(t,Nr)}_sceneToCubeUV(e,t,n,s,r){const c=new wn(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(oh),u.toneMapping=jn,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Fn(new Dr,new Hu({name:"PMREM.Background",side:en,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const T=e.background;T?T.isColor&&(m.color.copy(T),e.background=null,p=!0):(m.color.copy(oh),p=!0);for(let C=0;C<6;C++){const _=C%3;_===0?(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[C],r.y,r.z)):_===1?(c.up.set(0,0,l[C]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[C],r.z)):(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[C]));const S=this._cubeSize;Xs(s,_*S,C>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=T}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===is||e.mapping===As;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=uh()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=dh());const r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;const a=r.uniforms;a.envMap.value=e;const c=this._cubeSize;Xs(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,Nr)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const c=o.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-Bi?n-g+Bi:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,Xs(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(a,Nr),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,Xs(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(a,Nr)}_blur(e,t,n,s,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,s,"latitudinal",r),this._halfBlur(o,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,o,a){const c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&tt("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*hs-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):hs;m>hs&&Oe(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${hs}`);const p=[];let T=0;for(let w=0;w<hs;++w){const k=w/v,y=Math.exp(-k*k/2);p.push(y),w===0?T+=y:w<m&&(T+=2*y)}for(let w=0;w<p.length;w++)p[w]=p[w]/T;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=o==="latitudinal",a&&(h.poleAxis.value=a);const{_lodMax:C}=this;h.dTheta.value=g,h.mipInt.value=C-n;const _=this._sizeLods[s],S=3*_*(s>C-Bi?s-C+Bi:0),E=4*(this._cubeSize-_);Xs(t,S,E,3*_,2*_),c.setRenderTarget(t),c.render(u,Nr)}}function W_(i){const e=[],t=[],n=[];let s=i;const r=i-Bi+1+ah.length;for(let o=0;o<r;o++){const a=Math.pow(2,s);e.push(a);let c=1/a;o>i-Bi?c=ah[o-i+Bi-1]:o===0&&(c=0),t.push(c);const l=1/(a-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,T=new Float32Array(v*g*f),C=new Float32Array(m*g*f),_=new Float32Array(p*g*f);for(let E=0;E<f;E++){const w=E%3*2/3-1,k=E>2?0:-1,y=[w,k,0,w+2/3,k,0,w+2/3,k+1,0,w,k,0,w+2/3,k+1,0,w,k+1,0];T.set(y,v*g*E),C.set(h,m*g*E);const x=[E,E,E,E,E,E];_.set(x,p*g*E)}const S=new Un;S.setAttribute("position",new Jn(T,v)),S.setAttribute("uv",new Jn(C,m)),S.setAttribute("faceIndex",new Jn(_,p)),n.push(new Fn(S,null)),s>Bi&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function lh(i,e,t){const n=new Yn(i,e,t);return n.texture.mapping=oa,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Xs(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function q_(i,e,t){return new Mn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:G_,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ua(),fragmentShader:`
3652
3652
 
3653
3653
  precision highp float;
3654
3654
  precision highp int;
@@ -3756,7 +3756,7 @@ void main() {
3756
3756
 
3757
3757
  gl_FragColor = vec4(prefilteredColor, 1.0);
3758
3758
  }
3759
- `,blending:di,depthTest:!1,depthWrite:!1})}function j_(i,e,t){const n=new Float32Array(hs),s=new V(0,1,0);return new Mn({name:"SphericalGaussianBlur",defines:{n:hs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Fa(),fragmentShader:`
3759
+ `,blending:di,depthTest:!1,depthWrite:!1})}function j_(i,e,t){const n=new Float32Array(hs),s=new V(0,1,0);return new Mn({name:"SphericalGaussianBlur",defines:{n:hs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Ua(),fragmentShader:`
3760
3760
 
3761
3761
  precision mediump float;
3762
3762
  precision mediump int;
@@ -3816,7 +3816,7 @@ void main() {
3816
3816
  }
3817
3817
 
3818
3818
  }
3819
- `,blending:di,depthTest:!1,depthWrite:!1})}function dh(){return new Mn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Fa(),fragmentShader:`
3819
+ `,blending:di,depthTest:!1,depthWrite:!1})}function dh(){return new Mn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ua(),fragmentShader:`
3820
3820
 
3821
3821
  precision mediump float;
3822
3822
  precision mediump int;
@@ -3835,7 +3835,7 @@ void main() {
3835
3835
  gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
3836
3836
 
3837
3837
  }
3838
- `,blending:di,depthTest:!1,depthWrite:!1})}function uh(){return new Mn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Fa(),fragmentShader:`
3838
+ `,blending:di,depthTest:!1,depthWrite:!1})}function uh(){return new Mn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ua(),fragmentShader:`
3839
3839
 
3840
3840
  precision mediump float;
3841
3841
  precision mediump int;
@@ -3851,7 +3851,7 @@ void main() {
3851
3851
  gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
3852
3852
 
3853
3853
  }
3854
- `,blending:di,depthTest:!1,depthWrite:!1})}function Fa(){return`
3854
+ `,blending:di,depthTest:!1,depthWrite:!1})}function Ua(){return`
3855
3855
 
3856
3856
  precision mediump float;
3857
3857
  precision mediump int;
@@ -3906,7 +3906,7 @@ void main() {
3906
3906
  gl_Position = vec4( position, 1.0 );
3907
3907
 
3908
3908
  }
3909
- `}function X_(i){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){const c=a.mapping,l=c===qo||c===jo,d=c===is||c===Rs;if(l||d){let u=e.get(a);const h=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==h)return t===null&&(t=new ch(i)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{const f=a.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new ch(i)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function s(a){let c=0;const l=6;for(let d=0;d<l;d++)a[d]!==void 0&&c++;return c===l}function r(a){const c=a.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function $_(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Er("WebGLRenderer: "+n+" extension not supported."),s}}}function K_(i,e,t,n){const s={},r=new WeakMap;function o(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function a(u,h){return s[h.id]===!0||(h.addEventListener("dispose",o),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const T=f.array;v=f.version;for(let C=0,_=T.length;C<_;C+=3){const S=T[C+0],E=T[C+1],w=T[C+2];h.push(S,E,E,w,w,S)}}else if(g!==void 0){const T=g.array;v=g.version;for(let C=0,_=T.length/3-1;C<_;C+=3){const S=C+0,E=C+1,w=C+2;h.push(S,E,E,w,w,S)}}else return;const m=new(Mu(h)?qu:Wu)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:a,update:c,getWireframeAttribute:d}}function Y_(i,e,t){let n;function s(h){n=h}let r,o;function a(h){r=h.type,o=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*o),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*o,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/o,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let T=0;T<g;T++)p+=f[T]*v[T];t.update(p,n,1)}}this.setMode=s,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function J_(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:tt("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function Z_(i,e,t){const n=new WeakMap,s=new Pt;function r(o,a,c){const l=o.morphTargetInfluences,d=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(a);if(h===void 0||h.count!==u){let y=function(){w.dispose(),n.delete(a),a.removeEventListener("dispose",y)};h!==void 0&&h.texture.dispose();const f=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],p=a.morphAttributes.normal||[],T=a.morphAttributes.color||[];let C=0;f===!0&&(C=1),g===!0&&(C=2),v===!0&&(C=3);let _=a.attributes.position.count*C,S=1;_>e.maxTextureSize&&(S=Math.ceil(_/e.maxTextureSize),_=e.maxTextureSize);const E=new Float32Array(_*S*4*u),w=new Iu(E,_,S,u);w.type=$n,w.needsUpdate=!0;const k=C*4;for(let x=0;x<u;x++){const R=m[x],O=p[x],U=T[x],q=_*S*4*x;for(let $=0;$<R.count;$++){const G=$*k;f===!0&&(s.fromBufferAttribute(R,$),E[q+G+0]=s.x,E[q+G+1]=s.y,E[q+G+2]=s.z,E[q+G+3]=0),g===!0&&(s.fromBufferAttribute(O,$),E[q+G+4]=s.x,E[q+G+5]=s.y,E[q+G+6]=s.z,E[q+G+7]=0),v===!0&&(s.fromBufferAttribute(U,$),E[q+G+8]=s.x,E[q+G+9]=s.y,E[q+G+10]=s.z,E[q+G+11]=U.itemSize===4?s.w:1)}}h={count:u,texture:w,size:new st(_,S)},n.set(a,h),a.addEventListener("dispose",y)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",o.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=a.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function Q_(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function o(){s=new WeakMap}function a(c){const l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:o}}const eb={[cu]:"LINEAR_TONE_MAPPING",[lu]:"REINHARD_TONE_MAPPING",[du]:"CINEON_TONE_MAPPING",[uu]:"ACES_FILMIC_TONE_MAPPING",[fu]:"AGX_TONE_MAPPING",[pu]:"NEUTRAL_TONE_MAPPING",[hu]:"CUSTOM_TONE_MAPPING"};function tb(i,e,t,n,s){const r=new Yn(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),o=new Yn(e,t,{type:hi,depthBuffer:!1,stencilBuffer:!1}),a=new Un;a.setAttribute("position",new nn([-1,3,0,-1,-1,0,3,-1,0],3)),a.setAttribute("uv",new nn([0,2,0,0,2,0],2));const c=new Rv({uniforms:{tDiffuse:{value:null}},vertexShader:`
3909
+ `}function X_(i){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){const c=a.mapping,l=c===qo||c===jo,d=c===is||c===As;if(l||d){let u=e.get(a);const h=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==h)return t===null&&(t=new ch(i)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{const f=a.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new ch(i)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function s(a){let c=0;const l=6;for(let d=0;d<l;d++)a[d]!==void 0&&c++;return c===l}function r(a){const c=a.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function $_(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Er("WebGLRenderer: "+n+" extension not supported."),s}}}function K_(i,e,t,n){const s={},r=new WeakMap;function o(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function a(u,h){return s[h.id]===!0||(h.addEventListener("dispose",o),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const T=f.array;v=f.version;for(let C=0,_=T.length;C<_;C+=3){const S=T[C+0],E=T[C+1],w=T[C+2];h.push(S,E,E,w,w,S)}}else if(g!==void 0){const T=g.array;v=g.version;for(let C=0,_=T.length/3-1;C<_;C+=3){const S=C+0,E=C+1,w=C+2;h.push(S,E,E,w,w,S)}}else return;const m=new(Mu(h)?qu:Wu)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:a,update:c,getWireframeAttribute:d}}function Y_(i,e,t){let n;function s(h){n=h}let r,o;function a(h){r=h.type,o=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*o),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*o,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/o,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let T=0;T<g;T++)p+=f[T]*v[T];t.update(p,n,1)}}this.setMode=s,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function J_(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:tt("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function Z_(i,e,t){const n=new WeakMap,s=new Pt;function r(o,a,c){const l=o.morphTargetInfluences,d=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(a);if(h===void 0||h.count!==u){let y=function(){w.dispose(),n.delete(a),a.removeEventListener("dispose",y)};h!==void 0&&h.texture.dispose();const f=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],p=a.morphAttributes.normal||[],T=a.morphAttributes.color||[];let C=0;f===!0&&(C=1),g===!0&&(C=2),v===!0&&(C=3);let _=a.attributes.position.count*C,S=1;_>e.maxTextureSize&&(S=Math.ceil(_/e.maxTextureSize),_=e.maxTextureSize);const E=new Float32Array(_*S*4*u),w=new Iu(E,_,S,u);w.type=$n,w.needsUpdate=!0;const k=C*4;for(let x=0;x<u;x++){const R=m[x],O=p[x],U=T[x],q=_*S*4*x;for(let $=0;$<R.count;$++){const G=$*k;f===!0&&(s.fromBufferAttribute(R,$),E[q+G+0]=s.x,E[q+G+1]=s.y,E[q+G+2]=s.z,E[q+G+3]=0),g===!0&&(s.fromBufferAttribute(O,$),E[q+G+4]=s.x,E[q+G+5]=s.y,E[q+G+6]=s.z,E[q+G+7]=0),v===!0&&(s.fromBufferAttribute(U,$),E[q+G+8]=s.x,E[q+G+9]=s.y,E[q+G+10]=s.z,E[q+G+11]=U.itemSize===4?s.w:1)}}h={count:u,texture:w,size:new st(_,S)},n.set(a,h),a.addEventListener("dispose",y)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",o.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=a.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function Q_(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function o(){s=new WeakMap}function a(c){const l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:o}}const eb={[cu]:"LINEAR_TONE_MAPPING",[lu]:"REINHARD_TONE_MAPPING",[du]:"CINEON_TONE_MAPPING",[uu]:"ACES_FILMIC_TONE_MAPPING",[fu]:"AGX_TONE_MAPPING",[pu]:"NEUTRAL_TONE_MAPPING",[hu]:"CUSTOM_TONE_MAPPING"};function tb(i,e,t,n,s){const r=new Yn(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),o=new Yn(e,t,{type:hi,depthBuffer:!1,stencilBuffer:!1}),a=new Un;a.setAttribute("position",new nn([-1,3,0,-1,-1,0,3,-1,0],3)),a.setAttribute("uv",new nn([0,2,0,0,2,0],2));const c=new Rv({uniforms:{tDiffuse:{value:null}},vertexShader:`
3910
3910
  precision highp float;
3911
3911
 
3912
3912
  uniform mat4 modelViewMatrix;
@@ -3952,14 +3952,14 @@ void main() {
3952
3952
  #ifdef SRGB_TRANSFER
3953
3953
  gl_FragColor = sRGBTransferOETF( gl_FragColor );
3954
3954
  #endif
3955
- }`,depthTest:!1,depthWrite:!1}),l=new Fn(a,c),d=new ih(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(T,C){r.setSize(T,C),o.setSize(T,C);for(let _=0;_<m.length;_++){const S=m[_];S.setSize&&S.setSize(T,C)}},this.setEffects=function(T){m=T,p=m.length>0&&m[0].isRenderPass===!0;const C=r.width,_=r.height;for(let S=0;S<m.length;S++){const E=m[S];E.setSize&&E.setSize(C,_)}},this.begin=function(T,C){if(f||T.toneMapping===jn&&m.length===0)return!1;if(v=C,C!==null){const _=C.width,S=C.height;(r.width!==_||r.height!==S)&&this.setSize(_,S)}return p===!1&&T.setRenderTarget(r),g=T.toneMapping,T.toneMapping=jn,!0},this.hasRenderPass=function(){return p},this.end=function(T,C){T.toneMapping=g,f=!0;let _=r,S=o;for(let E=0;E<m.length;E++){const w=m[E];if(w.enabled!==!1&&(w.render(T,S,_,C),w.needsSwap!==!1)){const k=_;_=S,S=k}}if(u!==T.outputColorSpace||h!==T.toneMapping){u=T.outputColorSpace,h=T.toneMapping,c.defines={},Ze.getTransfer(u)===ct&&(c.defines.SRGB_TRANSFER="");const E=eb[h];E&&(c.defines[E]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=_.texture,T.setRenderTarget(v),T.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),o.dispose(),a.dispose(),c.dispose()}}const hh=new tn,gl=new Lr(1,1),fh=new Iu,ph=new sv,mh=new Qu,gh=[],vh=[],_h=new Float32Array(16),bh=new Float32Array(9),yh=new Float32Array(4);function Ks(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=gh[s];if(r===void 0&&(r=new Float32Array(s),gh[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function Vt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function zt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Ba(i,e){let t=vh[e];t===void 0&&(t=new Int32Array(e),vh[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function nb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function ib(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2fv(this.addr,e),zt(t,e)}}function sb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Vt(t,e))return;i.uniform3fv(this.addr,e),zt(t,e)}}function rb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4fv(this.addr,e),zt(t,e)}}function ab(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;yh.set(n),i.uniformMatrix2fv(this.addr,!1,yh),zt(t,n)}}function ob(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;bh.set(n),i.uniformMatrix3fv(this.addr,!1,bh),zt(t,n)}}function cb(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;_h.set(n),i.uniformMatrix4fv(this.addr,!1,_h),zt(t,n)}}function lb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function db(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2iv(this.addr,e),zt(t,e)}}function ub(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3iv(this.addr,e),zt(t,e)}}function hb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4iv(this.addr,e),zt(t,e)}}function fb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function pb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2uiv(this.addr,e),zt(t,e)}}function mb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3uiv(this.addr,e),zt(t,e)}}function gb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4uiv(this.addr,e),zt(t,e)}}function vb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(gl.compareFunction=t.isReversedDepthBuffer()?Nc:Lc,r=gl):r=hh,t.setTexture2D(e||r,s)}function _b(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||ph,s)}function bb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||mh,s)}function yb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||fh,s)}function Sb(i){switch(i){case 5126:return nb;case 35664:return ib;case 35665:return sb;case 35666:return rb;case 35674:return ab;case 35675:return ob;case 35676:return cb;case 5124:case 35670:return lb;case 35667:case 35671:return db;case 35668:case 35672:return ub;case 35669:case 35673:return hb;case 5125:return fb;case 36294:return pb;case 36295:return mb;case 36296:return gb;case 35678:case 36198:case 36298:case 36306:case 35682:return vb;case 35679:case 36299:case 36307:return _b;case 35680:case 36300:case 36308:case 36293:return bb;case 36289:case 36303:case 36311:case 36292:return yb}}function xb(i,e){i.uniform1fv(this.addr,e)}function Tb(i,e){const t=Ks(e,this.size,2);i.uniform2fv(this.addr,t)}function Eb(i,e){const t=Ks(e,this.size,3);i.uniform3fv(this.addr,t)}function Cb(i,e){const t=Ks(e,this.size,4);i.uniform4fv(this.addr,t)}function Mb(i,e){const t=Ks(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function wb(i,e){const t=Ks(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function Ab(i,e){const t=Ks(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function Rb(i,e){i.uniform1iv(this.addr,e)}function Pb(i,e){i.uniform2iv(this.addr,e)}function kb(i,e){i.uniform3iv(this.addr,e)}function Ib(i,e){i.uniform4iv(this.addr,e)}function Db(i,e){i.uniform1uiv(this.addr,e)}function Lb(i,e){i.uniform2uiv(this.addr,e)}function Nb(i,e){i.uniform3uiv(this.addr,e)}function Ob(i,e){i.uniform4uiv(this.addr,e)}function Ub(i,e,t){const n=this.cache,s=e.length,r=Ba(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));let o;this.type===i.SAMPLER_2D_SHADOW?o=gl:o=hh;for(let a=0;a!==s;++a)t.setTexture2D(e[a]||o,r[a])}function Fb(i,e,t){const n=this.cache,s=e.length,r=Ba(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let o=0;o!==s;++o)t.setTexture3D(e[o]||ph,r[o])}function Bb(i,e,t){const n=this.cache,s=e.length,r=Ba(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let o=0;o!==s;++o)t.setTextureCube(e[o]||mh,r[o])}function Vb(i,e,t){const n=this.cache,s=e.length,r=Ba(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let o=0;o!==s;++o)t.setTexture2DArray(e[o]||fh,r[o])}function zb(i){switch(i){case 5126:return xb;case 35664:return Tb;case 35665:return Eb;case 35666:return Cb;case 35674:return Mb;case 35675:return wb;case 35676:return Ab;case 5124:case 35670:return Rb;case 35667:case 35671:return Pb;case 35668:case 35672:return kb;case 35669:case 35673:return Ib;case 5125:return Db;case 36294:return Lb;case 36295:return Nb;case 36296:return Ob;case 35678:case 36198:case 36298:case 36306:case 35682:return Ub;case 35679:case 36299:case 36307:return Fb;case 35680:case 36300:case 36308:case 36293:return Bb;case 36289:case 36303:case 36311:case 36292:return Vb}}class Gb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Sb(t.type)}}class Hb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=zb(t.type)}}class Wb{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,o=s.length;r!==o;++r){const a=s[r];a.setValue(e,t[a.id],n)}}}const vl=/(\w+)(\])?(\[|\.)?/g;function Sh(i,e){i.seq.push(e),i.map[e.id]=e}function qb(i,e,t){const n=i.name,s=n.length;for(vl.lastIndex=0;;){const r=vl.exec(n),o=vl.lastIndex;let a=r[1];const c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===s){Sh(t,l===void 0?new Gb(a,i,e):new Hb(a,i,e));break}else{let u=t.map[a];u===void 0&&(u=new Wb(a),Sh(t,u)),t=u}}}class Va{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){const a=e.getActiveUniform(t,o),c=e.getUniformLocation(t,a.name);qb(a,c,this)}const s=[],r=[];for(const o of this.seq)o.type===e.SAMPLER_2D_SHADOW||o.type===e.SAMPLER_CUBE_SHADOW||o.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(o):r.push(o);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,o=t.length;r!==o;++r){const a=t[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const o=e[s];o.id in t&&n.push(o)}return n}}function xh(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const jb=37297;let Xb=0;function $b(i,e){const t=i.split(`
3955
+ }`,depthTest:!1,depthWrite:!1}),l=new Fn(a,c),d=new ih(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(T,C){r.setSize(T,C),o.setSize(T,C);for(let _=0;_<m.length;_++){const S=m[_];S.setSize&&S.setSize(T,C)}},this.setEffects=function(T){m=T,p=m.length>0&&m[0].isRenderPass===!0;const C=r.width,_=r.height;for(let S=0;S<m.length;S++){const E=m[S];E.setSize&&E.setSize(C,_)}},this.begin=function(T,C){if(f||T.toneMapping===jn&&m.length===0)return!1;if(v=C,C!==null){const _=C.width,S=C.height;(r.width!==_||r.height!==S)&&this.setSize(_,S)}return p===!1&&T.setRenderTarget(r),g=T.toneMapping,T.toneMapping=jn,!0},this.hasRenderPass=function(){return p},this.end=function(T,C){T.toneMapping=g,f=!0;let _=r,S=o;for(let E=0;E<m.length;E++){const w=m[E];if(w.enabled!==!1&&(w.render(T,S,_,C),w.needsSwap!==!1)){const k=_;_=S,S=k}}if(u!==T.outputColorSpace||h!==T.toneMapping){u=T.outputColorSpace,h=T.toneMapping,c.defines={},Ze.getTransfer(u)===ot&&(c.defines.SRGB_TRANSFER="");const E=eb[h];E&&(c.defines[E]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=_.texture,T.setRenderTarget(v),T.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),o.dispose(),a.dispose(),c.dispose()}}const hh=new tn,gl=new Lr(1,1),fh=new Iu,ph=new sv,mh=new Qu,gh=[],vh=[],_h=new Float32Array(16),bh=new Float32Array(9),yh=new Float32Array(4);function $s(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=gh[s];if(r===void 0&&(r=new Float32Array(s),gh[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function Bt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function Vt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Fa(i,e){let t=vh[e];t===void 0&&(t=new Int32Array(e),vh[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function nb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function ib(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Bt(t,e))return;i.uniform2fv(this.addr,e),Vt(t,e)}}function sb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Bt(t,e))return;i.uniform3fv(this.addr,e),Vt(t,e)}}function rb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Bt(t,e))return;i.uniform4fv(this.addr,e),Vt(t,e)}}function ab(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Bt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),Vt(t,e)}else{if(Bt(t,n))return;yh.set(n),i.uniformMatrix2fv(this.addr,!1,yh),Vt(t,n)}}function ob(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Bt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),Vt(t,e)}else{if(Bt(t,n))return;bh.set(n),i.uniformMatrix3fv(this.addr,!1,bh),Vt(t,n)}}function cb(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Bt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),Vt(t,e)}else{if(Bt(t,n))return;_h.set(n),i.uniformMatrix4fv(this.addr,!1,_h),Vt(t,n)}}function lb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function db(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Bt(t,e))return;i.uniform2iv(this.addr,e),Vt(t,e)}}function ub(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Bt(t,e))return;i.uniform3iv(this.addr,e),Vt(t,e)}}function hb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Bt(t,e))return;i.uniform4iv(this.addr,e),Vt(t,e)}}function fb(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function pb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Bt(t,e))return;i.uniform2uiv(this.addr,e),Vt(t,e)}}function mb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Bt(t,e))return;i.uniform3uiv(this.addr,e),Vt(t,e)}}function gb(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Bt(t,e))return;i.uniform4uiv(this.addr,e),Vt(t,e)}}function vb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(gl.compareFunction=t.isReversedDepthBuffer()?Nc:Lc,r=gl):r=hh,t.setTexture2D(e||r,s)}function _b(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||ph,s)}function bb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||mh,s)}function yb(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||fh,s)}function Sb(i){switch(i){case 5126:return nb;case 35664:return ib;case 35665:return sb;case 35666:return rb;case 35674:return ab;case 35675:return ob;case 35676:return cb;case 5124:case 35670:return lb;case 35667:case 35671:return db;case 35668:case 35672:return ub;case 35669:case 35673:return hb;case 5125:return fb;case 36294:return pb;case 36295:return mb;case 36296:return gb;case 35678:case 36198:case 36298:case 36306:case 35682:return vb;case 35679:case 36299:case 36307:return _b;case 35680:case 36300:case 36308:case 36293:return bb;case 36289:case 36303:case 36311:case 36292:return yb}}function xb(i,e){i.uniform1fv(this.addr,e)}function Tb(i,e){const t=$s(e,this.size,2);i.uniform2fv(this.addr,t)}function Eb(i,e){const t=$s(e,this.size,3);i.uniform3fv(this.addr,t)}function Cb(i,e){const t=$s(e,this.size,4);i.uniform4fv(this.addr,t)}function Mb(i,e){const t=$s(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function wb(i,e){const t=$s(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function Ab(i,e){const t=$s(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function Rb(i,e){i.uniform1iv(this.addr,e)}function Pb(i,e){i.uniform2iv(this.addr,e)}function kb(i,e){i.uniform3iv(this.addr,e)}function Ib(i,e){i.uniform4iv(this.addr,e)}function Db(i,e){i.uniform1uiv(this.addr,e)}function Lb(i,e){i.uniform2uiv(this.addr,e)}function Nb(i,e){i.uniform3uiv(this.addr,e)}function Ob(i,e){i.uniform4uiv(this.addr,e)}function Ub(i,e,t){const n=this.cache,s=e.length,r=Fa(t,s);Bt(n,r)||(i.uniform1iv(this.addr,r),Vt(n,r));let o;this.type===i.SAMPLER_2D_SHADOW?o=gl:o=hh;for(let a=0;a!==s;++a)t.setTexture2D(e[a]||o,r[a])}function Fb(i,e,t){const n=this.cache,s=e.length,r=Fa(t,s);Bt(n,r)||(i.uniform1iv(this.addr,r),Vt(n,r));for(let o=0;o!==s;++o)t.setTexture3D(e[o]||ph,r[o])}function Bb(i,e,t){const n=this.cache,s=e.length,r=Fa(t,s);Bt(n,r)||(i.uniform1iv(this.addr,r),Vt(n,r));for(let o=0;o!==s;++o)t.setTextureCube(e[o]||mh,r[o])}function Vb(i,e,t){const n=this.cache,s=e.length,r=Fa(t,s);Bt(n,r)||(i.uniform1iv(this.addr,r),Vt(n,r));for(let o=0;o!==s;++o)t.setTexture2DArray(e[o]||fh,r[o])}function zb(i){switch(i){case 5126:return xb;case 35664:return Tb;case 35665:return Eb;case 35666:return Cb;case 35674:return Mb;case 35675:return wb;case 35676:return Ab;case 5124:case 35670:return Rb;case 35667:case 35671:return Pb;case 35668:case 35672:return kb;case 35669:case 35673:return Ib;case 5125:return Db;case 36294:return Lb;case 36295:return Nb;case 36296:return Ob;case 35678:case 36198:case 36298:case 36306:case 35682:return Ub;case 35679:case 36299:case 36307:return Fb;case 35680:case 36300:case 36308:case 36293:return Bb;case 36289:case 36303:case 36311:case 36292:return Vb}}class Gb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Sb(t.type)}}class Hb{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=zb(t.type)}}class Wb{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,o=s.length;r!==o;++r){const a=s[r];a.setValue(e,t[a.id],n)}}}const vl=/(\w+)(\])?(\[|\.)?/g;function Sh(i,e){i.seq.push(e),i.map[e.id]=e}function qb(i,e,t){const n=i.name,s=n.length;for(vl.lastIndex=0;;){const r=vl.exec(n),o=vl.lastIndex;let a=r[1];const c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===s){Sh(t,l===void 0?new Gb(a,i,e):new Hb(a,i,e));break}else{let u=t.map[a];u===void 0&&(u=new Wb(a),Sh(t,u)),t=u}}}class Ba{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){const a=e.getActiveUniform(t,o),c=e.getUniformLocation(t,a.name);qb(a,c,this)}const s=[],r=[];for(const o of this.seq)o.type===e.SAMPLER_2D_SHADOW||o.type===e.SAMPLER_CUBE_SHADOW||o.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(o):r.push(o);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,o=t.length;r!==o;++r){const a=t[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const o=e[s];o.id in t&&n.push(o)}return n}}function xh(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const jb=37297;let Xb=0;function $b(i,e){const t=i.split(`
3956
3956
  `),n=[],s=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let o=s;o<r;o++){const a=o+1;n.push(`${a===e?">":" "} ${a}: ${t[o]}`)}return n.join(`
3957
- `)}const Th=new Ve;function Kb(i){Ze._getMatrix(Th,Ze.workingColorSpace,i);const e=`mat3( ${Th.elements.map(t=>t.toFixed(4))} )`;switch(Ze.getTransfer(i)){case pa:return[e,"LinearTransferOETF"];case ct:return[e,"sRGBTransferOETF"];default:return Oe("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Eh(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),r=(i.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";const o=/ERROR: 0:(\d+)/.exec(r);if(o){const a=parseInt(o[1]);return t.toUpperCase()+`
3957
+ `)}const Th=new Ve;function Kb(i){Ze._getMatrix(Th,Ze.workingColorSpace,i);const e=`mat3( ${Th.elements.map(t=>t.toFixed(4))} )`;switch(Ze.getTransfer(i)){case fa:return[e,"LinearTransferOETF"];case ot:return[e,"sRGBTransferOETF"];default:return Oe("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Eh(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),r=(i.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";const o=/ERROR: 0:(\d+)/.exec(r);if(o){const a=parseInt(o[1]);return t.toUpperCase()+`
3958
3958
 
3959
3959
  `+r+`
3960
3960
 
3961
3961
  `+$b(i.getShaderSource(e),a)}else return r}function Yb(i,e){const t=Kb(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
3962
- `)}const Jb={[cu]:"Linear",[lu]:"Reinhard",[du]:"Cineon",[uu]:"ACESFilmic",[fu]:"AgX",[pu]:"Neutral",[hu]:"Custom"};function Zb(i,e){const t=Jb[e];return t===void 0?(Oe("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const za=new V;function Qb(){Ze.getLuminanceCoefficients(za);const i=za.x.toFixed(4),e=za.y.toFixed(4),t=za.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
3962
+ `)}const Jb={[cu]:"Linear",[lu]:"Reinhard",[du]:"Cineon",[uu]:"ACESFilmic",[fu]:"AgX",[pu]:"Neutral",[hu]:"Custom"};function Zb(i,e){const t=Jb[e];return t===void 0?(Oe("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Va=new V;function Qb(){Ze.getLuminanceCoefficients(Va);const i=Va.x.toFixed(4),e=Va.y.toFixed(4),t=Va.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
3963
3963
  `)}function ey(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Or).join(`
3964
3964
  `)}function ty(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`
3965
3965
  `)}function ny(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){const r=i.getActiveAttrib(e,s),o=r.name;let a=1;r.type===i.FLOAT_MAT2&&(a=2),r.type===i.FLOAT_MAT3&&(a=3),r.type===i.FLOAT_MAT4&&(a=4),t[o]={type:r.type,location:i.getAttribLocation(e,o),locationSize:a}}return t}function Or(i){return i!==""}function Ch(i,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return i.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function Mh(i,e){return i.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const iy=/^[ \t]*#include +<([\w\d./]+)>/gm;function _l(i){return i.replace(iy,ry)}const sy=new Map;function ry(i,e){let t=He[e];if(t===void 0){const n=sy.get(e);if(n!==void 0)t=He[n],Oe('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return _l(t)}const ay=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function wh(i){return i.replace(ay,oy)}function oy(i,e,t,n){let s="";for(let r=parseInt(e);r<parseInt(t);r++)s+=n.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return s}function Ah(i){let e=`precision ${i.precision} float;
@@ -3982,7 +3982,7 @@ void main() {
3982
3982
  `;return i.precision==="highp"?e+=`
3983
3983
  #define HIGH_PRECISION`:i.precision==="mediump"?e+=`
3984
3984
  #define MEDIUM_PRECISION`:i.precision==="lowp"&&(e+=`
3985
- #define LOW_PRECISION`),e}const cy={[oa]:"SHADOWMAP_TYPE_PCF",[Sr]:"SHADOWMAP_TYPE_VSM"};function ly(i){return cy[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const dy={[is]:"ENVMAP_TYPE_CUBE",[Rs]:"ENVMAP_TYPE_CUBE",[ca]:"ENVMAP_TYPE_CUBE_UV"};function uy(i){return i.envMap===!1?"ENVMAP_TYPE_CUBE":dy[i.envMapMode]||"ENVMAP_TYPE_CUBE"}const hy={[Rs]:"ENVMAP_MODE_REFRACTION"};function fy(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":hy[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}const py={[ou]:"ENVMAP_BLENDING_MULTIPLY",[Fg]:"ENVMAP_BLENDING_MIX",[Bg]:"ENVMAP_BLENDING_ADD"};function my(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":py[i.combine]||"ENVMAP_BLENDING_NONE"}function gy(i){const e=i.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function vy(i,e,t,n){const s=i.getContext(),r=t.defines;let o=t.vertexShader,a=t.fragmentShader;const c=ly(t),l=uy(t),d=fy(t),u=my(t),h=gy(t),f=ey(t),g=ty(r),v=s.createProgram();let m,p,T=t.glslVersion?"#version "+t.glslVersion+`
3985
+ #define LOW_PRECISION`),e}const cy={[aa]:"SHADOWMAP_TYPE_PCF",[Sr]:"SHADOWMAP_TYPE_VSM"};function ly(i){return cy[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const dy={[is]:"ENVMAP_TYPE_CUBE",[As]:"ENVMAP_TYPE_CUBE",[oa]:"ENVMAP_TYPE_CUBE_UV"};function uy(i){return i.envMap===!1?"ENVMAP_TYPE_CUBE":dy[i.envMapMode]||"ENVMAP_TYPE_CUBE"}const hy={[As]:"ENVMAP_MODE_REFRACTION"};function fy(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":hy[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}const py={[ou]:"ENVMAP_BLENDING_MULTIPLY",[Fg]:"ENVMAP_BLENDING_MIX",[Bg]:"ENVMAP_BLENDING_ADD"};function my(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":py[i.combine]||"ENVMAP_BLENDING_NONE"}function gy(i){const e=i.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function vy(i,e,t,n){const s=i.getContext(),r=t.defines;let o=t.vertexShader,a=t.fragmentShader;const c=ly(t),l=uy(t),d=fy(t),u=my(t),h=gy(t),f=ey(t),g=ty(r),v=s.createProgram();let m,p,T=t.glslVersion?"#version "+t.glslVersion+`
3986
3986
  `:"";t.isRawShaderMaterial?(m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(Or).join(`
3987
3987
  `),m.length>0&&(m+=`
3988
3988
  `),p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(Or).join(`
@@ -4003,7 +4003,7 @@ Material Type: `+R.type+`
4003
4003
 
4004
4004
  Program Info Log: `+$+`
4005
4005
  `+le+`
4006
- `+_e)}else $!==""?Oe("WebGLProgram: Program Info Log:",$):(G===""||W==="")&&(ge=!1);ge&&(R.diagnostics={runnable:ee,programLog:$,vertexShader:{log:G,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(E),k=new Va(s,v),y=ny(s,v)}let k;this.getUniforms=function(){return k===void 0&&w(this),k};let y;this.getAttributes=function(){return y===void 0&&w(this),y};let x=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return x===!1&&(x=s.getProgramParameter(v,jb)),x},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Xb++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=E,this}let _y=0;class by{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(s)===!1&&(o.add(s),s.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new yy(e),t.set(e,n)),n}}class yy{constructor(e){this.id=_y++,this.code=e,this.usedTimes=0}}function Sy(i,e,t,n,s,r,o){const a=new Nu,c=new by,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(y){return l.add(y),y===0?"uv":`uv${y}`}function m(y,x,R,O,U){const q=O.fog,$=U.geometry,G=y.isMeshStandardMaterial?O.environment:null,W=(y.isMeshStandardMaterial?t:e).get(y.envMap||G),ee=W&&W.mapping===ca?W.image.height:null,ge=g[y.type];y.precision!==null&&(f=s.getMaxPrecision(y.precision),f!==y.precision&&Oe("WebGLProgram.getParameters:",y.precision,"not supported, using",f,"instead."));const le=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,_e=le!==void 0?le.length:0;let Be=0;$.morphAttributes.position!==void 0&&(Be=1),$.morphAttributes.normal!==void 0&&(Be=2),$.morphAttributes.color!==void 0&&(Be=3);let Fe,Tt,ft,K;if(ge){const dt=Zn[ge];Fe=dt.vertexShader,Tt=dt.fragmentShader}else Fe=y.vertexShader,Tt=y.fragmentShader,c.update(y),ft=c.getVertexShaderID(y),K=c.getFragmentShaderID(y);const ne=i.getRenderTarget(),xe=i.state.buffers.depth.getReversed(),Ge=U.isInstancedMesh===!0,Ce=U.isBatchedMesh===!0,nt=!!y.map,Xt=!!y.matcap,et=!!W,lt=!!y.aoMap,vt=!!y.lightMap,We=!!y.bumpMap,Ut=!!y.normalMap,I=!!y.displacementMap,Ft=!!y.emissiveMap,at=!!y.metalnessMap,yt=!!y.roughnessMap,we=y.anisotropy>0,A=y.clearcoat>0,b=y.dispersion>0,L=y.iridescence>0,X=y.sheen>0,Q=y.transmission>0,j=we&&!!y.anisotropyMap,Re=A&&!!y.clearcoatMap,ue=A&&!!y.clearcoatNormalMap,Me=A&&!!y.clearcoatRoughnessMap,Ne=L&&!!y.iridescenceMap,se=L&&!!y.iridescenceThicknessMap,fe=X&&!!y.sheenColorMap,Ee=X&&!!y.sheenRoughnessMap,Ae=!!y.specularMap,he=!!y.specularColorMap,qe=!!y.specularIntensityMap,D=Q&&!!y.transmissionMap,be=Q&&!!y.thicknessMap,ae=!!y.gradientMap,ye=!!y.alphaMap,ie=y.alphaTest>0,Z=!!y.alphaHash,de=!!y.extensions;let Ue=jn;y.toneMapped&&(ne===null||ne.isXRRenderTarget===!0)&&(Ue=i.toneMapping);const St={shaderID:ge,shaderType:y.type,shaderName:y.name,vertexShader:Fe,fragmentShader:Tt,defines:y.defines,customVertexShaderID:ft,customFragmentShaderID:K,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:f,batching:Ce,batchingColor:Ce&&U._colorsTexture!==null,instancing:Ge,instancingColor:Ge&&U.instanceColor!==null,instancingMorph:Ge&&U.morphTexture!==null,outputColorSpace:ne===null?i.outputColorSpace:ne.isXRRenderTarget===!0?ne.texture.colorSpace:ks,alphaToCoverage:!!y.alphaToCoverage,map:nt,matcap:Xt,envMap:et,envMapMode:et&&W.mapping,envMapCubeUVHeight:ee,aoMap:lt,lightMap:vt,bumpMap:We,normalMap:Ut,displacementMap:I,emissiveMap:Ft,normalMapObjectSpace:Ut&&y.normalMapType===Hg,normalMapTangentSpace:Ut&&y.normalMapType===Gg,metalnessMap:at,roughnessMap:yt,anisotropy:we,anisotropyMap:j,clearcoat:A,clearcoatMap:Re,clearcoatNormalMap:ue,clearcoatRoughnessMap:Me,dispersion:b,iridescence:L,iridescenceMap:Ne,iridescenceThicknessMap:se,sheen:X,sheenColorMap:fe,sheenRoughnessMap:Ee,specularMap:Ae,specularColorMap:he,specularIntensityMap:qe,transmission:Q,transmissionMap:D,thicknessMap:be,gradientMap:ae,opaque:y.transparent===!1&&y.blending===ws&&y.alphaToCoverage===!1,alphaMap:ye,alphaTest:ie,alphaHash:Z,combine:y.combine,mapUv:nt&&v(y.map.channel),aoMapUv:lt&&v(y.aoMap.channel),lightMapUv:vt&&v(y.lightMap.channel),bumpMapUv:We&&v(y.bumpMap.channel),normalMapUv:Ut&&v(y.normalMap.channel),displacementMapUv:I&&v(y.displacementMap.channel),emissiveMapUv:Ft&&v(y.emissiveMap.channel),metalnessMapUv:at&&v(y.metalnessMap.channel),roughnessMapUv:yt&&v(y.roughnessMap.channel),anisotropyMapUv:j&&v(y.anisotropyMap.channel),clearcoatMapUv:Re&&v(y.clearcoatMap.channel),clearcoatNormalMapUv:ue&&v(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Me&&v(y.clearcoatRoughnessMap.channel),iridescenceMapUv:Ne&&v(y.iridescenceMap.channel),iridescenceThicknessMapUv:se&&v(y.iridescenceThicknessMap.channel),sheenColorMapUv:fe&&v(y.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&v(y.sheenRoughnessMap.channel),specularMapUv:Ae&&v(y.specularMap.channel),specularColorMapUv:he&&v(y.specularColorMap.channel),specularIntensityMapUv:qe&&v(y.specularIntensityMap.channel),transmissionMapUv:D&&v(y.transmissionMap.channel),thicknessMapUv:be&&v(y.thicknessMap.channel),alphaMapUv:ye&&v(y.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Ut||we),vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:U.isPoints===!0&&!!$.attributes.uv&&(nt||ye),fog:!!q,useFog:y.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:y.flatShading===!0&&y.wireframe===!1,sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:xe,skinning:U.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Be,numDirLights:x.directional.length,numPointLights:x.point.length,numSpotLights:x.spot.length,numSpotLightMaps:x.spotLightMap.length,numRectAreaLights:x.rectArea.length,numHemiLights:x.hemi.length,numDirLightShadows:x.directionalShadowMap.length,numPointLightShadows:x.pointShadowMap.length,numSpotLightShadows:x.spotShadowMap.length,numSpotLightShadowsWithMaps:x.numSpotLightShadowsWithMaps,numLightProbes:x.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:y.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Ue,decodeVideoTexture:nt&&y.map.isVideoTexture===!0&&Ze.getTransfer(y.map.colorSpace)===ct,decodeVideoTextureEmissive:Ft&&y.emissiveMap.isVideoTexture===!0&&Ze.getTransfer(y.emissiveMap.colorSpace)===ct,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===li,flipSided:y.side===en,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:de&&y.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(de&&y.extensions.multiDraw===!0||Ce)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function p(y){const x=[];if(y.shaderID?x.push(y.shaderID):(x.push(y.customVertexShaderID),x.push(y.customFragmentShaderID)),y.defines!==void 0)for(const R in y.defines)x.push(R),x.push(y.defines[R]);return y.isRawShaderMaterial===!1&&(T(x,y),C(x,y),x.push(i.outputColorSpace)),x.push(y.customProgramCacheKey),x.join()}function T(y,x){y.push(x.precision),y.push(x.outputColorSpace),y.push(x.envMapMode),y.push(x.envMapCubeUVHeight),y.push(x.mapUv),y.push(x.alphaMapUv),y.push(x.lightMapUv),y.push(x.aoMapUv),y.push(x.bumpMapUv),y.push(x.normalMapUv),y.push(x.displacementMapUv),y.push(x.emissiveMapUv),y.push(x.metalnessMapUv),y.push(x.roughnessMapUv),y.push(x.anisotropyMapUv),y.push(x.clearcoatMapUv),y.push(x.clearcoatNormalMapUv),y.push(x.clearcoatRoughnessMapUv),y.push(x.iridescenceMapUv),y.push(x.iridescenceThicknessMapUv),y.push(x.sheenColorMapUv),y.push(x.sheenRoughnessMapUv),y.push(x.specularMapUv),y.push(x.specularColorMapUv),y.push(x.specularIntensityMapUv),y.push(x.transmissionMapUv),y.push(x.thicknessMapUv),y.push(x.combine),y.push(x.fogExp2),y.push(x.sizeAttenuation),y.push(x.morphTargetsCount),y.push(x.morphAttributeCount),y.push(x.numDirLights),y.push(x.numPointLights),y.push(x.numSpotLights),y.push(x.numSpotLightMaps),y.push(x.numHemiLights),y.push(x.numRectAreaLights),y.push(x.numDirLightShadows),y.push(x.numPointLightShadows),y.push(x.numSpotLightShadows),y.push(x.numSpotLightShadowsWithMaps),y.push(x.numLightProbes),y.push(x.shadowMapType),y.push(x.toneMapping),y.push(x.numClippingPlanes),y.push(x.numClipIntersection),y.push(x.depthPacking)}function C(y,x){a.disableAll(),x.instancing&&a.enable(0),x.instancingColor&&a.enable(1),x.instancingMorph&&a.enable(2),x.matcap&&a.enable(3),x.envMap&&a.enable(4),x.normalMapObjectSpace&&a.enable(5),x.normalMapTangentSpace&&a.enable(6),x.clearcoat&&a.enable(7),x.iridescence&&a.enable(8),x.alphaTest&&a.enable(9),x.vertexColors&&a.enable(10),x.vertexAlphas&&a.enable(11),x.vertexUv1s&&a.enable(12),x.vertexUv2s&&a.enable(13),x.vertexUv3s&&a.enable(14),x.vertexTangents&&a.enable(15),x.anisotropy&&a.enable(16),x.alphaHash&&a.enable(17),x.batching&&a.enable(18),x.dispersion&&a.enable(19),x.batchingColor&&a.enable(20),x.gradientMap&&a.enable(21),y.push(a.mask),a.disableAll(),x.fog&&a.enable(0),x.useFog&&a.enable(1),x.flatShading&&a.enable(2),x.logarithmicDepthBuffer&&a.enable(3),x.reversedDepthBuffer&&a.enable(4),x.skinning&&a.enable(5),x.morphTargets&&a.enable(6),x.morphNormals&&a.enable(7),x.morphColors&&a.enable(8),x.premultipliedAlpha&&a.enable(9),x.shadowMapEnabled&&a.enable(10),x.doubleSided&&a.enable(11),x.flipSided&&a.enable(12),x.useDepthPacking&&a.enable(13),x.dithering&&a.enable(14),x.transmission&&a.enable(15),x.sheen&&a.enable(16),x.opaque&&a.enable(17),x.pointsUvs&&a.enable(18),x.decodeVideoTexture&&a.enable(19),x.decodeVideoTextureEmissive&&a.enable(20),x.alphaToCoverage&&a.enable(21),y.push(a.mask)}function _(y){const x=g[y.type];let R;if(x){const O=Zn[x];R=_v.clone(O.uniforms)}else R=y.uniforms;return R}function S(y,x){let R=u.get(x);return R!==void 0?++R.usedTimes:(R=new vy(i,x,y,r),d.push(R),u.set(x,R)),R}function E(y){if(--y.usedTimes===0){const x=d.indexOf(y);d[x]=d[d.length-1],d.pop(),u.delete(y.cacheKey),y.destroy()}}function w(y){c.remove(y)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:_,acquireProgram:S,releaseProgram:E,releaseShaderCache:w,programs:d,dispose:k}}function xy(){let i=new WeakMap;function e(o){return i.has(o)}function t(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,c){i.get(o)[a]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function Ty(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function Rh(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Ph(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function o(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function a(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||Ty),n.length>1&&n.sort(h||Rh),s.length>1&&s.sort(h||Rh)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:a,unshift:c,finish:d,sort:l}}function Ey(){let i=new WeakMap;function e(n,s){const r=i.get(n);let o;return r===void 0?(o=new Ph,i.set(n,[o])):s>=r.length?(o=new Ph,r.push(o)):o=r[s],o}function t(){i=new WeakMap}return{get:e,dispose:t}}function Cy(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new V,color:new Je};break;case"SpotLight":t={position:new V,direction:new V,color:new Je,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new V,color:new Je,distance:0,decay:0};break;case"HemisphereLight":t={direction:new V,skyColor:new Je,groundColor:new Je};break;case"RectAreaLight":t={color:new Je,position:new V,halfWidth:new V,halfHeight:new V};break}return i[e.id]=t,t}}}function My(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let wy=0;function Ay(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function Ry(i){const e=new Cy,t=My(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new V);const s=new V,r=new Dt,o=new Dt;function a(l){let d=0,u=0,h=0;for(let y=0;y<9;y++)n.probe[y].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,T=0,C=0,_=0,S=0,E=0,w=0;l.sort(Ay);for(let y=0,x=l.length;y<x;y++){const R=l[y],O=R.color,U=R.intensity,q=R.distance;let $=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Ps?$=R.shadow.map.texture:$=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=O.r*U,u+=O.g*U,h+=O.b*U;else if(R.isLightProbe){for(let G=0;G<9;G++)n.probe[G].addScaledVector(R.sh.coefficients[G],U);w++}else if(R.isDirectionalLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,n.directionalShadow[f]=ee,n.directionalShadowMap[f]=$,n.directionalShadowMatrix[f]=R.shadow.matrix,T++}n.directional[f]=G,f++}else if(R.isSpotLight){const G=e.get(R);G.position.setFromMatrixPosition(R.matrixWorld),G.color.copy(O).multiplyScalar(U),G.distance=q,G.coneCos=Math.cos(R.angle),G.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),G.decay=R.decay,n.spot[v]=G;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&E++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,n.spotShadow[v]=ee,n.spotShadowMap[v]=$,_++}v++}else if(R.isRectAreaLight){const G=e.get(R);G.color.copy(O).multiplyScalar(U),G.halfWidth.set(R.width*.5,0,0),G.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=G,m++}else if(R.isPointLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),G.distance=R.distance,G.decay=R.decay,R.castShadow){const W=R.shadow,ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,ee.shadowCameraNear=W.camera.near,ee.shadowCameraFar=W.camera.far,n.pointShadow[g]=ee,n.pointShadowMap[g]=$,n.pointShadowMatrix[g]=R.shadow.matrix,C++}n.point[g]=G,g++}else if(R.isHemisphereLight){const G=e.get(R);G.skyColor.copy(R.color).multiplyScalar(U),G.groundColor.copy(R.groundColor).multiplyScalar(U),n.hemi[p]=G,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=me.LTC_FLOAT_1,n.rectAreaLTC2=me.LTC_FLOAT_2):(n.rectAreaLTC1=me.LTC_HALF_1,n.rectAreaLTC2=me.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==T||k.numPointShadows!==C||k.numSpotShadows!==_||k.numSpotMaps!==S||k.numLightProbes!==w)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=C,n.pointShadowMap.length=C,n.spotShadow.length=_,n.spotShadowMap.length=_,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=C,n.spotLightMatrix.length=_+S-E,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=w,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=T,k.numPointShadows=C,k.numSpotShadows=_,k.numSpotMaps=S,k.numLightProbes=w,n.version=wy++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,T=l.length;p<T;p++){const C=l[p];if(C.isDirectionalLight){const _=n.directional[u];_.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),_.direction.sub(s),_.direction.transformDirection(m),u++}else if(C.isSpotLight){const _=n.spot[f];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),_.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),_.direction.sub(s),_.direction.transformDirection(m),f++}else if(C.isRectAreaLight){const _=n.rectArea[g];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),o.identity(),r.copy(C.matrixWorld),r.premultiply(m),o.extractRotation(r),_.halfWidth.set(C.width*.5,0,0),_.halfHeight.set(0,C.height*.5,0),_.halfWidth.applyMatrix4(o),_.halfHeight.applyMatrix4(o),g++}else if(C.isPointLight){const _=n.point[h];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),h++}else if(C.isHemisphereLight){const _=n.hemi[v];_.direction.setFromMatrixPosition(C.matrixWorld),_.direction.transformDirection(m),v++}}}return{setup:a,setupView:c,state:n}}function kh(i){const e=new Ry(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function o(d){n.push(d)}function a(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:a,setupLightsView:c,pushLight:r,pushShadow:o}}function Py(i){let e=new WeakMap;function t(s,r=0){const o=e.get(s);let a;return o===void 0?(a=new kh(i),e.set(s,[a])):r>=o.length?(a=new kh(i),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const ky=`void main() {
4006
+ `+_e)}else $!==""?Oe("WebGLProgram: Program Info Log:",$):(G===""||W==="")&&(ge=!1);ge&&(R.diagnostics={runnable:ee,programLog:$,vertexShader:{log:G,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(E),k=new Ba(s,v),y=ny(s,v)}let k;this.getUniforms=function(){return k===void 0&&w(this),k};let y;this.getAttributes=function(){return y===void 0&&w(this),y};let x=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return x===!1&&(x=s.getProgramParameter(v,jb)),x},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Xb++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=E,this}let _y=0;class by{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(s)===!1&&(o.add(s),s.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new yy(e),t.set(e,n)),n}}class yy{constructor(e){this.id=_y++,this.code=e,this.usedTimes=0}}function Sy(i,e,t,n,s,r,o){const a=new Nu,c=new by,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(y){return l.add(y),y===0?"uv":`uv${y}`}function m(y,x,R,O,U){const q=O.fog,$=U.geometry,G=y.isMeshStandardMaterial?O.environment:null,W=(y.isMeshStandardMaterial?t:e).get(y.envMap||G),ee=W&&W.mapping===oa?W.image.height:null,ge=g[y.type];y.precision!==null&&(f=s.getMaxPrecision(y.precision),f!==y.precision&&Oe("WebGLProgram.getParameters:",y.precision,"not supported, using",f,"instead."));const le=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,_e=le!==void 0?le.length:0;let Be=0;$.morphAttributes.position!==void 0&&(Be=1),$.morphAttributes.normal!==void 0&&(Be=2),$.morphAttributes.color!==void 0&&(Be=3);let Fe,Tt,ht,K;if(ge){const lt=Zn[ge];Fe=lt.vertexShader,Tt=lt.fragmentShader}else Fe=y.vertexShader,Tt=y.fragmentShader,c.update(y),ht=c.getVertexShaderID(y),K=c.getFragmentShaderID(y);const ne=i.getRenderTarget(),xe=i.state.buffers.depth.getReversed(),Ge=U.isInstancedMesh===!0,Ce=U.isBatchedMesh===!0,nt=!!y.map,Xt=!!y.matcap,et=!!W,ct=!!y.aoMap,gt=!!y.lightMap,We=!!y.bumpMap,Ot=!!y.normalMap,I=!!y.displacementMap,Ut=!!y.emissiveMap,at=!!y.metalnessMap,bt=!!y.roughnessMap,we=y.anisotropy>0,A=y.clearcoat>0,b=y.dispersion>0,L=y.iridescence>0,X=y.sheen>0,Q=y.transmission>0,j=we&&!!y.anisotropyMap,Re=A&&!!y.clearcoatMap,ue=A&&!!y.clearcoatNormalMap,Me=A&&!!y.clearcoatRoughnessMap,Ne=L&&!!y.iridescenceMap,se=L&&!!y.iridescenceThicknessMap,fe=X&&!!y.sheenColorMap,Ee=X&&!!y.sheenRoughnessMap,Ae=!!y.specularMap,he=!!y.specularColorMap,qe=!!y.specularIntensityMap,D=Q&&!!y.transmissionMap,be=Q&&!!y.thicknessMap,ae=!!y.gradientMap,ye=!!y.alphaMap,ie=y.alphaTest>0,Z=!!y.alphaHash,de=!!y.extensions;let Ue=jn;y.toneMapped&&(ne===null||ne.isXRRenderTarget===!0)&&(Ue=i.toneMapping);const yt={shaderID:ge,shaderType:y.type,shaderName:y.name,vertexShader:Fe,fragmentShader:Tt,defines:y.defines,customVertexShaderID:ht,customFragmentShaderID:K,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:f,batching:Ce,batchingColor:Ce&&U._colorsTexture!==null,instancing:Ge,instancingColor:Ge&&U.instanceColor!==null,instancingMorph:Ge&&U.morphTexture!==null,outputColorSpace:ne===null?i.outputColorSpace:ne.isXRRenderTarget===!0?ne.texture.colorSpace:Ps,alphaToCoverage:!!y.alphaToCoverage,map:nt,matcap:Xt,envMap:et,envMapMode:et&&W.mapping,envMapCubeUVHeight:ee,aoMap:ct,lightMap:gt,bumpMap:We,normalMap:Ot,displacementMap:I,emissiveMap:Ut,normalMapObjectSpace:Ot&&y.normalMapType===Hg,normalMapTangentSpace:Ot&&y.normalMapType===Gg,metalnessMap:at,roughnessMap:bt,anisotropy:we,anisotropyMap:j,clearcoat:A,clearcoatMap:Re,clearcoatNormalMap:ue,clearcoatRoughnessMap:Me,dispersion:b,iridescence:L,iridescenceMap:Ne,iridescenceThicknessMap:se,sheen:X,sheenColorMap:fe,sheenRoughnessMap:Ee,specularMap:Ae,specularColorMap:he,specularIntensityMap:qe,transmission:Q,transmissionMap:D,thicknessMap:be,gradientMap:ae,opaque:y.transparent===!1&&y.blending===Ms&&y.alphaToCoverage===!1,alphaMap:ye,alphaTest:ie,alphaHash:Z,combine:y.combine,mapUv:nt&&v(y.map.channel),aoMapUv:ct&&v(y.aoMap.channel),lightMapUv:gt&&v(y.lightMap.channel),bumpMapUv:We&&v(y.bumpMap.channel),normalMapUv:Ot&&v(y.normalMap.channel),displacementMapUv:I&&v(y.displacementMap.channel),emissiveMapUv:Ut&&v(y.emissiveMap.channel),metalnessMapUv:at&&v(y.metalnessMap.channel),roughnessMapUv:bt&&v(y.roughnessMap.channel),anisotropyMapUv:j&&v(y.anisotropyMap.channel),clearcoatMapUv:Re&&v(y.clearcoatMap.channel),clearcoatNormalMapUv:ue&&v(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Me&&v(y.clearcoatRoughnessMap.channel),iridescenceMapUv:Ne&&v(y.iridescenceMap.channel),iridescenceThicknessMapUv:se&&v(y.iridescenceThicknessMap.channel),sheenColorMapUv:fe&&v(y.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&v(y.sheenRoughnessMap.channel),specularMapUv:Ae&&v(y.specularMap.channel),specularColorMapUv:he&&v(y.specularColorMap.channel),specularIntensityMapUv:qe&&v(y.specularIntensityMap.channel),transmissionMapUv:D&&v(y.transmissionMap.channel),thicknessMapUv:be&&v(y.thicknessMap.channel),alphaMapUv:ye&&v(y.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Ot||we),vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:U.isPoints===!0&&!!$.attributes.uv&&(nt||ye),fog:!!q,useFog:y.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:y.flatShading===!0&&y.wireframe===!1,sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:xe,skinning:U.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Be,numDirLights:x.directional.length,numPointLights:x.point.length,numSpotLights:x.spot.length,numSpotLightMaps:x.spotLightMap.length,numRectAreaLights:x.rectArea.length,numHemiLights:x.hemi.length,numDirLightShadows:x.directionalShadowMap.length,numPointLightShadows:x.pointShadowMap.length,numSpotLightShadows:x.spotShadowMap.length,numSpotLightShadowsWithMaps:x.numSpotLightShadowsWithMaps,numLightProbes:x.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:y.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Ue,decodeVideoTexture:nt&&y.map.isVideoTexture===!0&&Ze.getTransfer(y.map.colorSpace)===ot,decodeVideoTextureEmissive:Ut&&y.emissiveMap.isVideoTexture===!0&&Ze.getTransfer(y.emissiveMap.colorSpace)===ot,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===li,flipSided:y.side===en,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:de&&y.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(de&&y.extensions.multiDraw===!0||Ce)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return yt.vertexUv1s=l.has(1),yt.vertexUv2s=l.has(2),yt.vertexUv3s=l.has(3),l.clear(),yt}function p(y){const x=[];if(y.shaderID?x.push(y.shaderID):(x.push(y.customVertexShaderID),x.push(y.customFragmentShaderID)),y.defines!==void 0)for(const R in y.defines)x.push(R),x.push(y.defines[R]);return y.isRawShaderMaterial===!1&&(T(x,y),C(x,y),x.push(i.outputColorSpace)),x.push(y.customProgramCacheKey),x.join()}function T(y,x){y.push(x.precision),y.push(x.outputColorSpace),y.push(x.envMapMode),y.push(x.envMapCubeUVHeight),y.push(x.mapUv),y.push(x.alphaMapUv),y.push(x.lightMapUv),y.push(x.aoMapUv),y.push(x.bumpMapUv),y.push(x.normalMapUv),y.push(x.displacementMapUv),y.push(x.emissiveMapUv),y.push(x.metalnessMapUv),y.push(x.roughnessMapUv),y.push(x.anisotropyMapUv),y.push(x.clearcoatMapUv),y.push(x.clearcoatNormalMapUv),y.push(x.clearcoatRoughnessMapUv),y.push(x.iridescenceMapUv),y.push(x.iridescenceThicknessMapUv),y.push(x.sheenColorMapUv),y.push(x.sheenRoughnessMapUv),y.push(x.specularMapUv),y.push(x.specularColorMapUv),y.push(x.specularIntensityMapUv),y.push(x.transmissionMapUv),y.push(x.thicknessMapUv),y.push(x.combine),y.push(x.fogExp2),y.push(x.sizeAttenuation),y.push(x.morphTargetsCount),y.push(x.morphAttributeCount),y.push(x.numDirLights),y.push(x.numPointLights),y.push(x.numSpotLights),y.push(x.numSpotLightMaps),y.push(x.numHemiLights),y.push(x.numRectAreaLights),y.push(x.numDirLightShadows),y.push(x.numPointLightShadows),y.push(x.numSpotLightShadows),y.push(x.numSpotLightShadowsWithMaps),y.push(x.numLightProbes),y.push(x.shadowMapType),y.push(x.toneMapping),y.push(x.numClippingPlanes),y.push(x.numClipIntersection),y.push(x.depthPacking)}function C(y,x){a.disableAll(),x.instancing&&a.enable(0),x.instancingColor&&a.enable(1),x.instancingMorph&&a.enable(2),x.matcap&&a.enable(3),x.envMap&&a.enable(4),x.normalMapObjectSpace&&a.enable(5),x.normalMapTangentSpace&&a.enable(6),x.clearcoat&&a.enable(7),x.iridescence&&a.enable(8),x.alphaTest&&a.enable(9),x.vertexColors&&a.enable(10),x.vertexAlphas&&a.enable(11),x.vertexUv1s&&a.enable(12),x.vertexUv2s&&a.enable(13),x.vertexUv3s&&a.enable(14),x.vertexTangents&&a.enable(15),x.anisotropy&&a.enable(16),x.alphaHash&&a.enable(17),x.batching&&a.enable(18),x.dispersion&&a.enable(19),x.batchingColor&&a.enable(20),x.gradientMap&&a.enable(21),y.push(a.mask),a.disableAll(),x.fog&&a.enable(0),x.useFog&&a.enable(1),x.flatShading&&a.enable(2),x.logarithmicDepthBuffer&&a.enable(3),x.reversedDepthBuffer&&a.enable(4),x.skinning&&a.enable(5),x.morphTargets&&a.enable(6),x.morphNormals&&a.enable(7),x.morphColors&&a.enable(8),x.premultipliedAlpha&&a.enable(9),x.shadowMapEnabled&&a.enable(10),x.doubleSided&&a.enable(11),x.flipSided&&a.enable(12),x.useDepthPacking&&a.enable(13),x.dithering&&a.enable(14),x.transmission&&a.enable(15),x.sheen&&a.enable(16),x.opaque&&a.enable(17),x.pointsUvs&&a.enable(18),x.decodeVideoTexture&&a.enable(19),x.decodeVideoTextureEmissive&&a.enable(20),x.alphaToCoverage&&a.enable(21),y.push(a.mask)}function _(y){const x=g[y.type];let R;if(x){const O=Zn[x];R=_v.clone(O.uniforms)}else R=y.uniforms;return R}function S(y,x){let R=u.get(x);return R!==void 0?++R.usedTimes:(R=new vy(i,x,y,r),d.push(R),u.set(x,R)),R}function E(y){if(--y.usedTimes===0){const x=d.indexOf(y);d[x]=d[d.length-1],d.pop(),u.delete(y.cacheKey),y.destroy()}}function w(y){c.remove(y)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:_,acquireProgram:S,releaseProgram:E,releaseShaderCache:w,programs:d,dispose:k}}function xy(){let i=new WeakMap;function e(o){return i.has(o)}function t(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,c){i.get(o)[a]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function Ty(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function Rh(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Ph(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function o(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function a(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||Ty),n.length>1&&n.sort(h||Rh),s.length>1&&s.sort(h||Rh)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:a,unshift:c,finish:d,sort:l}}function Ey(){let i=new WeakMap;function e(n,s){const r=i.get(n);let o;return r===void 0?(o=new Ph,i.set(n,[o])):s>=r.length?(o=new Ph,r.push(o)):o=r[s],o}function t(){i=new WeakMap}return{get:e,dispose:t}}function Cy(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new V,color:new Je};break;case"SpotLight":t={position:new V,direction:new V,color:new Je,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new V,color:new Je,distance:0,decay:0};break;case"HemisphereLight":t={direction:new V,skyColor:new Je,groundColor:new Je};break;case"RectAreaLight":t={color:new Je,position:new V,halfWidth:new V,halfHeight:new V};break}return i[e.id]=t,t}}}function My(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new st,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let wy=0;function Ay(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function Ry(i){const e=new Cy,t=My(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new V);const s=new V,r=new Dt,o=new Dt;function a(l){let d=0,u=0,h=0;for(let y=0;y<9;y++)n.probe[y].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,T=0,C=0,_=0,S=0,E=0,w=0;l.sort(Ay);for(let y=0,x=l.length;y<x;y++){const R=l[y],O=R.color,U=R.intensity,q=R.distance;let $=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Rs?$=R.shadow.map.texture:$=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=O.r*U,u+=O.g*U,h+=O.b*U;else if(R.isLightProbe){for(let G=0;G<9;G++)n.probe[G].addScaledVector(R.sh.coefficients[G],U);w++}else if(R.isDirectionalLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,n.directionalShadow[f]=ee,n.directionalShadowMap[f]=$,n.directionalShadowMatrix[f]=R.shadow.matrix,T++}n.directional[f]=G,f++}else if(R.isSpotLight){const G=e.get(R);G.position.setFromMatrixPosition(R.matrixWorld),G.color.copy(O).multiplyScalar(U),G.distance=q,G.coneCos=Math.cos(R.angle),G.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),G.decay=R.decay,n.spot[v]=G;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&E++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,n.spotShadow[v]=ee,n.spotShadowMap[v]=$,_++}v++}else if(R.isRectAreaLight){const G=e.get(R);G.color.copy(O).multiplyScalar(U),G.halfWidth.set(R.width*.5,0,0),G.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=G,m++}else if(R.isPointLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),G.distance=R.distance,G.decay=R.decay,R.castShadow){const W=R.shadow,ee=t.get(R);ee.shadowIntensity=W.intensity,ee.shadowBias=W.bias,ee.shadowNormalBias=W.normalBias,ee.shadowRadius=W.radius,ee.shadowMapSize=W.mapSize,ee.shadowCameraNear=W.camera.near,ee.shadowCameraFar=W.camera.far,n.pointShadow[g]=ee,n.pointShadowMap[g]=$,n.pointShadowMatrix[g]=R.shadow.matrix,C++}n.point[g]=G,g++}else if(R.isHemisphereLight){const G=e.get(R);G.skyColor.copy(R.color).multiplyScalar(U),G.groundColor.copy(R.groundColor).multiplyScalar(U),n.hemi[p]=G,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=me.LTC_FLOAT_1,n.rectAreaLTC2=me.LTC_FLOAT_2):(n.rectAreaLTC1=me.LTC_HALF_1,n.rectAreaLTC2=me.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==T||k.numPointShadows!==C||k.numSpotShadows!==_||k.numSpotMaps!==S||k.numLightProbes!==w)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=C,n.pointShadowMap.length=C,n.spotShadow.length=_,n.spotShadowMap.length=_,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=C,n.spotLightMatrix.length=_+S-E,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=w,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=T,k.numPointShadows=C,k.numSpotShadows=_,k.numSpotMaps=S,k.numLightProbes=w,n.version=wy++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,T=l.length;p<T;p++){const C=l[p];if(C.isDirectionalLight){const _=n.directional[u];_.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),_.direction.sub(s),_.direction.transformDirection(m),u++}else if(C.isSpotLight){const _=n.spot[f];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),_.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),_.direction.sub(s),_.direction.transformDirection(m),f++}else if(C.isRectAreaLight){const _=n.rectArea[g];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),o.identity(),r.copy(C.matrixWorld),r.premultiply(m),o.extractRotation(r),_.halfWidth.set(C.width*.5,0,0),_.halfHeight.set(0,C.height*.5,0),_.halfWidth.applyMatrix4(o),_.halfHeight.applyMatrix4(o),g++}else if(C.isPointLight){const _=n.point[h];_.position.setFromMatrixPosition(C.matrixWorld),_.position.applyMatrix4(m),h++}else if(C.isHemisphereLight){const _=n.hemi[v];_.direction.setFromMatrixPosition(C.matrixWorld),_.direction.transformDirection(m),v++}}}return{setup:a,setupView:c,state:n}}function kh(i){const e=new Ry(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function o(d){n.push(d)}function a(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:a,setupLightsView:c,pushLight:r,pushShadow:o}}function Py(i){let e=new WeakMap;function t(s,r=0){const o=e.get(s);let a;return o===void 0?(a=new kh(i),e.set(s,[a])):r>=o.length?(a=new kh(i),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const ky=`void main() {
4007
4007
  gl_Position = vec4( position, 1.0 );
4008
4008
  }`,Iy=`uniform sampler2D shadow_pass;
4009
4009
  uniform vec2 resolution;
@@ -4030,7 +4030,7 @@ void main() {
4030
4030
  squared_mean = squared_mean / samples;
4031
4031
  float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
4032
4032
  gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
4033
- }`,Dy=[new V(1,0,0),new V(-1,0,0),new V(0,1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1)],Ly=[new V(0,-1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1),new V(0,-1,0),new V(0,-1,0)],Ih=new Dt,Ur=new V,bl=new V;function Ny(i,e,t){let n=new th;const s=new st,r=new st,o=new Pt,a=new Pv,c=new kv,l={},d=t.maxTextureSize,u={[ci]:en,[en]:ci,[li]:li},h=new Mn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new st},radius:{value:4}},vertexShader:ky,fragmentShader:Iy}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new Un;g.setAttribute("position",new Jn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Fn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=oa;let p=this.type;this.render=function(E,w,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||E.length===0)return;E.type===bg&&(Oe("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),E.type=oa);const y=i.getRenderTarget(),x=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),O=i.state;O.setBlending(di),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const U=p!==this.type;U&&w.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach($=>$.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,$=E.length;q<$;q++){const G=E[q],W=G.shadow;if(W===void 0){Oe("WebGLShadowMap:",G,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const ee=W.getFrameExtents();if(s.multiply(ee),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/ee.x),s.x=r.x*ee.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/ee.y),s.y=r.y*ee.y,W.mapSize.y=r.y)),W.map===null||U===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Sr){if(G.isPointLight){Oe("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Yn(s.x,s.y,{format:Ps,type:hi,minFilter:Jt,magFilter:Jt,generateMipmaps:!1}),W.map.texture.name=G.name+".shadowMap",W.map.depthTexture=new Lr(s.x,s.y,$n),W.map.depthTexture.name=G.name+".shadowMapDepth",W.map.depthTexture.format=fi,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=$t,W.map.depthTexture.magFilter=$t}else{G.isPointLight?(W.map=new eh(s.x),W.map.depthTexture=new Av(s.x,Xn)):(W.map=new Yn(s.x,s.y),W.map.depthTexture=new Lr(s.x,s.y,Xn)),W.map.depthTexture.name=G.name+".shadowMap",W.map.depthTexture.format=fi;const le=i.state.buffers.depth.getReversed();this.type===oa?(W.map.depthTexture.compareFunction=le?Nc:Lc,W.map.depthTexture.minFilter=Jt,W.map.depthTexture.magFilter=Jt):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=$t,W.map.depthTexture.magFilter=$t)}W.camera.updateProjectionMatrix()}const ge=W.map.isWebGLCubeRenderTarget?6:1;for(let le=0;le<ge;le++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,le),i.clear();else{le===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(le);o.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),O.viewport(o)}if(G.isPointLight){const _e=W.camera,Be=W.matrix,Fe=G.distance||_e.far;Fe!==_e.far&&(_e.far=Fe,_e.updateProjectionMatrix()),Ur.setFromMatrixPosition(G.matrixWorld),_e.position.copy(Ur),bl.copy(_e.position),bl.add(Dy[le]),_e.up.copy(Ly[le]),_e.lookAt(bl),_e.updateMatrixWorld(),Be.makeTranslation(-Ur.x,-Ur.y,-Ur.z),Ih.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(Ih,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(G);n=W.getFrustum(),_(w,k,W.camera,G,this.type)}W.isPointLightShadow!==!0&&this.type===Sr&&T(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(y,x,R)};function T(E,w){const k=e.update(v);h.defines.VSM_SAMPLES!==E.blurSamples&&(h.defines.VSM_SAMPLES=E.blurSamples,f.defines.VSM_SAMPLES=E.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),E.mapPass===null&&(E.mapPass=new Yn(s.x,s.y,{format:Ps,type:hi})),h.uniforms.shadow_pass.value=E.map.depthTexture,h.uniforms.resolution.value=E.mapSize,h.uniforms.radius.value=E.radius,i.setRenderTarget(E.mapPass),i.clear(),i.renderBufferDirect(w,null,k,h,v,null),f.uniforms.shadow_pass.value=E.mapPass.texture,f.uniforms.resolution.value=E.mapSize,f.uniforms.radius.value=E.radius,i.setRenderTarget(E.map),i.clear(),i.renderBufferDirect(w,null,k,f,v,null)}function C(E,w,k,y){let x=null;const R=k.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(R!==void 0)x=R;else if(x=k.isPointLight===!0?c:a,i.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=x.uuid,U=w.uuid;let q=l[O];q===void 0&&(q={},l[O]=q);let $=q[U];$===void 0&&($=x.clone(),q[U]=$,w.addEventListener("dispose",S)),x=$}if(x.visible=w.visible,x.wireframe=w.wireframe,y===Sr?x.side=w.shadowSide!==null?w.shadowSide:w.side:x.side=w.shadowSide!==null?w.shadowSide:u[w.side],x.alphaMap=w.alphaMap,x.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,x.map=w.map,x.clipShadows=w.clipShadows,x.clippingPlanes=w.clippingPlanes,x.clipIntersection=w.clipIntersection,x.displacementMap=w.displacementMap,x.displacementScale=w.displacementScale,x.displacementBias=w.displacementBias,x.wireframeLinewidth=w.wireframeLinewidth,x.linewidth=w.linewidth,k.isPointLight===!0&&x.isMeshDistanceMaterial===!0){const O=i.properties.get(x);O.light=k}return x}function _(E,w,k,y,x){if(E.visible===!1)return;if(E.layers.test(w.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&x===Sr)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,E.matrixWorld);const U=e.update(E),q=E.material;if(Array.isArray(q)){const $=U.groups;for(let G=0,W=$.length;G<W;G++){const ee=$[G],ge=q[ee.materialIndex];if(ge&&ge.visible){const le=C(E,ge,y,x);E.onBeforeShadow(i,E,w,k,U,le,ee),i.renderBufferDirect(k,null,U,le,E,ee),E.onAfterShadow(i,E,w,k,U,le,ee)}}}else if(q.visible){const $=C(E,q,y,x);E.onBeforeShadow(i,E,w,k,U,$,null),i.renderBufferDirect(k,null,U,$,E,null),E.onAfterShadow(i,E,w,k,U,$,null)}}const O=E.children;for(let U=0,q=O.length;U<q;U++)_(O[U],w,k,y,x)}function S(E){E.target.removeEventListener("dispose",S);for(const k in l){const y=l[k],x=E.target.uuid;x in y&&(y[x].dispose(),delete y[x])}}}const Oy={[Fo]:Bo,[Vo]:Ho,[zo]:Wo,[As]:Go,[Bo]:Fo,[Ho]:Vo,[Wo]:zo,[Go]:As};function Uy(i,e){function t(){let D=!1;const be=new Pt;let ae=null;const ye=new Pt(0,0,0,0);return{setMask:function(ie){ae!==ie&&!D&&(i.colorMask(ie,ie,ie,ie),ae=ie)},setLocked:function(ie){D=ie},setClear:function(ie,Z,de,Ue,St){St===!0&&(ie*=Ue,Z*=Ue,de*=Ue),be.set(ie,Z,de,Ue),ye.equals(be)===!1&&(i.clearColor(ie,Z,de,Ue),ye.copy(be))},reset:function(){D=!1,ae=null,ye.set(-1,0,0,0)}}}function n(){let D=!1,be=!1,ae=null,ye=null,ie=null;return{setReversed:function(Z){if(be!==Z){const de=e.get("EXT_clip_control");Z?de.clipControlEXT(de.LOWER_LEFT_EXT,de.ZERO_TO_ONE_EXT):de.clipControlEXT(de.LOWER_LEFT_EXT,de.NEGATIVE_ONE_TO_ONE_EXT),be=Z;const Ue=ie;ie=null,this.setClear(Ue)}},getReversed:function(){return be},setTest:function(Z){Z?ne(i.DEPTH_TEST):xe(i.DEPTH_TEST)},setMask:function(Z){ae!==Z&&!D&&(i.depthMask(Z),ae=Z)},setFunc:function(Z){if(be&&(Z=Oy[Z]),ye!==Z){switch(Z){case Fo:i.depthFunc(i.NEVER);break;case Bo:i.depthFunc(i.ALWAYS);break;case Vo:i.depthFunc(i.LESS);break;case As:i.depthFunc(i.LEQUAL);break;case zo:i.depthFunc(i.EQUAL);break;case Go:i.depthFunc(i.GEQUAL);break;case Ho:i.depthFunc(i.GREATER);break;case Wo:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}ye=Z}},setLocked:function(Z){D=Z},setClear:function(Z){ie!==Z&&(be&&(Z=1-Z),i.clearDepth(Z),ie=Z)},reset:function(){D=!1,ae=null,ye=null,ie=null,be=!1}}}function s(){let D=!1,be=null,ae=null,ye=null,ie=null,Z=null,de=null,Ue=null,St=null;return{setTest:function(dt){D||(dt?ne(i.STENCIL_TEST):xe(i.STENCIL_TEST))},setMask:function(dt){be!==dt&&!D&&(i.stencilMask(dt),be=dt)},setFunc:function(dt,oi,Ai){(ae!==dt||ye!==oi||ie!==Ai)&&(i.stencilFunc(dt,oi,Ai),ae=dt,ye=oi,ie=Ai)},setOp:function(dt,oi,Ai){(Z!==dt||de!==oi||Ue!==Ai)&&(i.stencilOp(dt,oi,Ai),Z=dt,de=oi,Ue=Ai)},setLocked:function(dt){D=dt},setClear:function(dt){St!==dt&&(i.clearStencil(dt),St=dt)},reset:function(){D=!1,be=null,ae=null,ye=null,ie=null,Z=null,de=null,Ue=null,St=null}}}const r=new t,o=new n,a=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,C=null,_=null,S=null,E=null,w=new Je(0,0,0),k=0,y=!1,x=null,R=null,O=null,U=null,q=null;const $=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let G=!1,W=0;const ee=i.getParameter(i.VERSION);ee.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(ee)[1]),G=W>=1):ee.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(ee)[1]),G=W>=2);let ge=null,le={};const _e=i.getParameter(i.SCISSOR_BOX),Be=i.getParameter(i.VIEWPORT),Fe=new Pt().fromArray(_e),Tt=new Pt().fromArray(Be);function ft(D,be,ae,ye){const ie=new Uint8Array(4),Z=i.createTexture();i.bindTexture(D,Z),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let de=0;de<ae;de++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(be,0,i.RGBA,1,1,ye,0,i.RGBA,i.UNSIGNED_BYTE,ie):i.texImage2D(be+de,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,ie);return Z}const K={};K[i.TEXTURE_2D]=ft(i.TEXTURE_2D,i.TEXTURE_2D,1),K[i.TEXTURE_CUBE_MAP]=ft(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),K[i.TEXTURE_2D_ARRAY]=ft(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),K[i.TEXTURE_3D]=ft(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),ne(i.DEPTH_TEST),o.setFunc(As),We(!1),Ut(su),ne(i.CULL_FACE),lt(di);function ne(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function xe(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function Ge(D,be){return u[D]!==be?(i.bindFramebuffer(D,be),u[D]=be,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=be),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=be),!0):!1}function Ce(D,be){let ae=f,ye=!1;if(D){ae=h.get(be),ae===void 0&&(ae=[],h.set(be,ae));const ie=D.textures;if(ae.length!==ie.length||ae[0]!==i.COLOR_ATTACHMENT0){for(let Z=0,de=ie.length;Z<de;Z++)ae[Z]=i.COLOR_ATTACHMENT0+Z;ae.length=ie.length,ye=!0}}else ae[0]!==i.BACK&&(ae[0]=i.BACK,ye=!0);ye&&i.drawBuffers(ae)}function nt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const Xt={[ns]:i.FUNC_ADD,[Sg]:i.FUNC_SUBTRACT,[xg]:i.FUNC_REVERSE_SUBTRACT};Xt[Tg]=i.MIN,Xt[Eg]=i.MAX;const et={[Cg]:i.ZERO,[Mg]:i.ONE,[wg]:i.SRC_COLOR,[Oo]:i.SRC_ALPHA,[Dg]:i.SRC_ALPHA_SATURATE,[kg]:i.DST_COLOR,[Rg]:i.DST_ALPHA,[Ag]:i.ONE_MINUS_SRC_COLOR,[Uo]:i.ONE_MINUS_SRC_ALPHA,[Ig]:i.ONE_MINUS_DST_COLOR,[Pg]:i.ONE_MINUS_DST_ALPHA,[Lg]:i.CONSTANT_COLOR,[Ng]:i.ONE_MINUS_CONSTANT_COLOR,[Og]:i.CONSTANT_ALPHA,[Ug]:i.ONE_MINUS_CONSTANT_ALPHA};function lt(D,be,ae,ye,ie,Z,de,Ue,St,dt){if(D===di){v===!0&&(xe(i.BLEND),v=!1);return}if(v===!1&&(ne(i.BLEND),v=!0),D!==yg){if(D!==m||dt!==y){if((p!==ns||_!==ns)&&(i.blendEquation(i.FUNC_ADD),p=ns,_=ns),dt)switch(D){case ws:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case No:i.blendFunc(i.ONE,i.ONE);break;case ru:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case au:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:tt("WebGLState: Invalid blending: ",D);break}else switch(D){case ws:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case No:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case ru:tt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case au:tt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:tt("WebGLState: Invalid blending: ",D);break}T=null,C=null,S=null,E=null,w.set(0,0,0),k=0,m=D,y=dt}return}ie=ie||be,Z=Z||ae,de=de||ye,(be!==p||ie!==_)&&(i.blendEquationSeparate(Xt[be],Xt[ie]),p=be,_=ie),(ae!==T||ye!==C||Z!==S||de!==E)&&(i.blendFuncSeparate(et[ae],et[ye],et[Z],et[de]),T=ae,C=ye,S=Z,E=de),(Ue.equals(w)===!1||St!==k)&&(i.blendColor(Ue.r,Ue.g,Ue.b,St),w.copy(Ue),k=St),m=D,y=!1}function vt(D,be){D.side===li?xe(i.CULL_FACE):ne(i.CULL_FACE);let ae=D.side===en;be&&(ae=!ae),We(ae),D.blending===ws&&D.transparent===!1?lt(di):lt(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),o.setFunc(D.depthFunc),o.setTest(D.depthTest),o.setMask(D.depthWrite),r.setMask(D.colorWrite);const ye=D.stencilWrite;a.setTest(ye),ye&&(a.setMask(D.stencilWriteMask),a.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),a.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Ft(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ne(i.SAMPLE_ALPHA_TO_COVERAGE):xe(i.SAMPLE_ALPHA_TO_COVERAGE)}function We(D){x!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),x=D)}function Ut(D){D!==vg?(ne(i.CULL_FACE),D!==R&&(D===su?i.cullFace(i.BACK):D===_g?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):xe(i.CULL_FACE),R=D}function I(D){D!==O&&(G&&i.lineWidth(D),O=D)}function Ft(D,be,ae){D?(ne(i.POLYGON_OFFSET_FILL),(U!==be||q!==ae)&&(i.polygonOffset(be,ae),U=be,q=ae)):xe(i.POLYGON_OFFSET_FILL)}function at(D){D?ne(i.SCISSOR_TEST):xe(i.SCISSOR_TEST)}function yt(D){D===void 0&&(D=i.TEXTURE0+$-1),ge!==D&&(i.activeTexture(D),ge=D)}function we(D,be,ae){ae===void 0&&(ge===null?ae=i.TEXTURE0+$-1:ae=ge);let ye=le[ae];ye===void 0&&(ye={type:void 0,texture:void 0},le[ae]=ye),(ye.type!==D||ye.texture!==be)&&(ge!==ae&&(i.activeTexture(ae),ge=ae),i.bindTexture(D,be||K[D]),ye.type=D,ye.texture=be)}function A(){const D=le[ge];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function b(){try{i.compressedTexImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function X(){try{i.texSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Q(){try{i.texSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Re(){try{i.compressedTexSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function ue(){try{i.texStorage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Me(){try{i.texStorage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ne(){try{i.texImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function se(){try{i.texImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function fe(D){Fe.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Fe.copy(D))}function Ee(D){Tt.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Tt.copy(D))}function Ae(D,be){let ae=l.get(be);ae===void 0&&(ae=new WeakMap,l.set(be,ae));let ye=ae.get(D);ye===void 0&&(ye=i.getUniformBlockIndex(be,D.name),ae.set(D,ye))}function he(D,be){const ye=l.get(be).get(D);c.get(be)!==ye&&(i.uniformBlockBinding(be,ye,D.__bindingPointIndex),c.set(be,ye))}function qe(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),o.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ge=null,le={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,C=null,_=null,S=null,E=null,w=new Je(0,0,0),k=0,y=!1,x=null,R=null,O=null,U=null,q=null,Fe.set(0,0,i.canvas.width,i.canvas.height),Tt.set(0,0,i.canvas.width,i.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:ne,disable:xe,bindFramebuffer:Ge,drawBuffers:Ce,useProgram:nt,setBlending:lt,setMaterial:vt,setFlipSided:We,setCullFace:Ut,setLineWidth:I,setPolygonOffset:Ft,setScissorTest:at,activeTexture:yt,bindTexture:we,unbindTexture:A,compressedTexImage2D:b,compressedTexImage3D:L,texImage2D:Ne,texImage3D:se,updateUBOMapping:Ae,uniformBlockBinding:he,texStorage2D:ue,texStorage3D:Me,texSubImage2D:X,texSubImage3D:Q,compressedTexSubImage2D:j,compressedTexSubImage3D:Re,scissor:fe,viewport:Ee,reset:qe}}function Fy(i,e,t,n,s,r,o){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new st,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(A,b){return f?new OffscreenCanvas(A,b):ga("canvas")}function v(A,b,L){let X=1;const Q=we(A);if((Q.width>L||Q.height>L)&&(X=L/Math.max(Q.width,Q.height)),X<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){const j=Math.floor(X*Q.width),Re=Math.floor(X*Q.height);u===void 0&&(u=g(j,Re));const ue=b?g(j,Re):u;return ue.width=j,ue.height=Re,ue.getContext("2d").drawImage(A,0,0,j,Re),Oe("WebGLRenderer: Texture has been resized from ("+Q.width+"x"+Q.height+") to ("+j+"x"+Re+")."),ue}else return"data"in A&&Oe("WebGLRenderer: Image in DataTexture is too big ("+Q.width+"x"+Q.height+")."),A;return A}function m(A){return A.generateMipmaps}function p(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function C(A,b,L,X,Q=!1){if(A!==null){if(i[A]!==void 0)return i[A];Oe("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let j=b;if(b===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),b===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),b===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),b===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),b===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),b===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),b===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),b===i.RGBA){const Re=Q?pa:Ze.getTransfer(X);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=Re===ct?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function _(A,b){let L;return A?b===null||b===Xn||b===Tr?L=i.DEPTH24_STENCIL8:b===$n?L=i.DEPTH32F_STENCIL8:b===xr&&(L=i.DEPTH24_STENCIL8,Oe("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===Xn||b===Tr?L=i.DEPTH_COMPONENT24:b===$n?L=i.DEPTH_COMPONENT32F:b===xr&&(L=i.DEPTH_COMPONENT16),L}function S(A,b){return m(A)===!0||A.isFramebufferTexture&&A.minFilter!==$t&&A.minFilter!==Jt?Math.log2(Math.max(b.width,b.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?b.mipmaps.length:1}function E(A){const b=A.target;b.removeEventListener("dispose",E),k(b),b.isVideoTexture&&d.delete(b)}function w(A){const b=A.target;b.removeEventListener("dispose",w),x(b)}function k(A){const b=n.get(A);if(b.__webglInit===void 0)return;const L=A.source,X=h.get(L);if(X){const Q=X[b.__cacheKey];Q.usedTimes--,Q.usedTimes===0&&y(A),Object.keys(X).length===0&&h.delete(L)}n.remove(A)}function y(A){const b=n.get(A);i.deleteTexture(b.__webglTexture);const L=A.source,X=h.get(L);delete X[b.__cacheKey],o.memory.textures--}function x(A){const b=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(b.__webglFramebuffer[X]))for(let Q=0;Q<b.__webglFramebuffer[X].length;Q++)i.deleteFramebuffer(b.__webglFramebuffer[X][Q]);else i.deleteFramebuffer(b.__webglFramebuffer[X]);b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer[X])}else{if(Array.isArray(b.__webglFramebuffer))for(let X=0;X<b.__webglFramebuffer.length;X++)i.deleteFramebuffer(b.__webglFramebuffer[X]);else i.deleteFramebuffer(b.__webglFramebuffer);if(b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer),b.__webglMultisampledFramebuffer&&i.deleteFramebuffer(b.__webglMultisampledFramebuffer),b.__webglColorRenderbuffer)for(let X=0;X<b.__webglColorRenderbuffer.length;X++)b.__webglColorRenderbuffer[X]&&i.deleteRenderbuffer(b.__webglColorRenderbuffer[X]);b.__webglDepthRenderbuffer&&i.deleteRenderbuffer(b.__webglDepthRenderbuffer)}const L=A.textures;for(let X=0,Q=L.length;X<Q;X++){const j=n.get(L[X]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),o.memory.textures--),n.remove(L[X])}n.remove(A)}let R=0;function O(){R=0}function U(){const A=R;return A>=s.maxTextures&&Oe("WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+s.maxTextures),R+=1,A}function q(A){const b=[];return b.push(A.wrapS),b.push(A.wrapT),b.push(A.wrapR||0),b.push(A.magFilter),b.push(A.minFilter),b.push(A.anisotropy),b.push(A.internalFormat),b.push(A.format),b.push(A.type),b.push(A.generateMipmaps),b.push(A.premultiplyAlpha),b.push(A.flipY),b.push(A.unpackAlignment),b.push(A.colorSpace),b.join()}function $(A,b){const L=n.get(A);if(A.isVideoTexture&&at(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&L.__version!==A.version){const X=A.image;if(X===null)Oe("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)Oe("WebGLRenderer: Texture marked for update but image is incomplete");else{K(L,A,b);return}}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+b)}function G(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){K(L,A,b);return}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+b)}function W(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){K(L,A,b);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+b)}function ee(A,b){const L=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&L.__version!==A.version){ne(L,A,b);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+b)}const ge={[Xo]:i.REPEAT,[ui]:i.CLAMP_TO_EDGE,[$o]:i.MIRRORED_REPEAT},le={[$t]:i.NEAREST,[Vg]:i.NEAREST_MIPMAP_NEAREST,[la]:i.NEAREST_MIPMAP_LINEAR,[Jt]:i.LINEAR,[Ko]:i.LINEAR_MIPMAP_NEAREST,[ss]:i.LINEAR_MIPMAP_LINEAR},_e={[Wg]:i.NEVER,[Kg]:i.ALWAYS,[qg]:i.LESS,[Lc]:i.LEQUAL,[jg]:i.EQUAL,[Nc]:i.GEQUAL,[Xg]:i.GREATER,[$g]:i.NOTEQUAL};function Be(A,b){if(b.type===$n&&e.has("OES_texture_float_linear")===!1&&(b.magFilter===Jt||b.magFilter===Ko||b.magFilter===la||b.magFilter===ss||b.minFilter===Jt||b.minFilter===Ko||b.minFilter===la||b.minFilter===ss)&&Oe("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,ge[b.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,ge[b.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,ge[b.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,le[b.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,le[b.minFilter]),b.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,_e[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===$t||b.minFilter!==la&&b.minFilter!==ss||b.type===$n&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(A,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,s.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function Fe(A,b){let L=!1;A.__webglInit===void 0&&(A.__webglInit=!0,b.addEventListener("dispose",E));const X=b.source;let Q=h.get(X);Q===void 0&&(Q={},h.set(X,Q));const j=q(b);if(j!==A.__cacheKey){Q[j]===void 0&&(Q[j]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,L=!0),Q[j].usedTimes++;const Re=Q[A.__cacheKey];Re!==void 0&&(Q[A.__cacheKey].usedTimes--,Re.usedTimes===0&&y(b)),A.__cacheKey=j,A.__webglTexture=Q[j].texture}return L}function Tt(A,b,L){return Math.floor(Math.floor(A/L)/b)}function ft(A,b,L,X){const j=A.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,b.width,b.height,L,X,b.data);else{j.sort((se,fe)=>se.start-fe.start);let Re=0;for(let se=1;se<j.length;se++){const fe=j[Re],Ee=j[se],Ae=fe.start+fe.count,he=Tt(Ee.start,b.width,4),qe=Tt(fe.start,b.width,4);Ee.start<=Ae+1&&he===qe&&Tt(Ee.start+Ee.count-1,b.width,4)===he?fe.count=Math.max(fe.count,Ee.start+Ee.count-fe.start):(++Re,j[Re]=Ee)}j.length=Re+1;const ue=i.getParameter(i.UNPACK_ROW_LENGTH),Me=i.getParameter(i.UNPACK_SKIP_PIXELS),Ne=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,b.width);for(let se=0,fe=j.length;se<fe;se++){const Ee=j[se],Ae=Math.floor(Ee.start/4),he=Math.ceil(Ee.count/4),qe=Ae%b.width,D=Math.floor(Ae/b.width),be=he,ae=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,qe),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,qe,D,be,ae,L,X,b.data)}A.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,ue),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Me),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ne)}}function K(A,b,L){let X=i.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(X=i.TEXTURE_2D_ARRAY),b.isData3DTexture&&(X=i.TEXTURE_3D);const Q=Fe(A,b),j=b.source;t.bindTexture(X,A.__webglTexture,i.TEXTURE0+L);const Re=n.get(j);if(j.version!==Re.__version||Q===!0){t.activeTexture(i.TEXTURE0+L);const ue=Ze.getPrimaries(Ze.workingColorSpace),Me=b.colorSpace===Ii?null:Ze.getPrimaries(b.colorSpace),Ne=b.colorSpace===Ii||ue===Me?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ne);let se=v(b.image,!1,s.maxTextureSize);se=yt(b,se);const fe=r.convert(b.format,b.colorSpace),Ee=r.convert(b.type);let Ae=C(b.internalFormat,fe,Ee,b.colorSpace,b.isVideoTexture);Be(X,b);let he;const qe=b.mipmaps,D=b.isVideoTexture!==!0,be=Re.__version===void 0||Q===!0,ae=j.dataReady,ye=S(b,se);if(b.isDepthTexture)Ae=_(b.format===rs,b.type),be&&(D?t.texStorage2D(i.TEXTURE_2D,1,Ae,se.width,se.height):t.texImage2D(i.TEXTURE_2D,0,Ae,se.width,se.height,0,fe,Ee,null));else if(b.isDataTexture)if(qe.length>0){D&&be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,qe[0].width,qe[0].height);for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,Ee,he.data):t.texImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,fe,Ee,he.data);b.generateMipmaps=!1}else D?(be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,se.width,se.height),ae&&ft(b,se,fe,Ee)):t.texImage2D(i.TEXTURE_2D,0,Ae,se.width,se.height,0,fe,Ee,se.data);else if(b.isCompressedTexture)if(b.isCompressedArrayTexture){D&&be&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ye,Ae,qe[0].width,qe[0].height,se.depth);for(let ie=0,Z=qe.length;ie<Z;ie++)if(he=qe[ie],b.format!==In)if(fe!==null)if(D){if(ae)if(b.layerUpdates.size>0){const de=sh(he.width,he.height,b.format,b.type);for(const Ue of b.layerUpdates){const St=he.data.subarray(Ue*de/he.data.BYTES_PER_ELEMENT,(Ue+1)*de/he.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,Ue,he.width,he.height,1,fe,St)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,0,he.width,he.height,se.depth,fe,he.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,ie,Ae,he.width,he.height,se.depth,0,he.data,0,0);else Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?ae&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,0,he.width,he.height,se.depth,fe,Ee,he.data):t.texImage3D(i.TEXTURE_2D_ARRAY,ie,Ae,he.width,he.height,se.depth,0,fe,Ee,he.data)}else{D&&be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,qe[0].width,qe[0].height);for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],b.format!==In?fe!==null?D?ae&&t.compressedTexSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,he.data):t.compressedTexImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,he.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,Ee,he.data):t.texImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,fe,Ee,he.data)}else if(b.isDataArrayTexture)if(D){if(be&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ye,Ae,se.width,se.height,se.depth),ae)if(b.layerUpdates.size>0){const ie=sh(se.width,se.height,b.format,b.type);for(const Z of b.layerUpdates){const de=se.data.subarray(Z*ie/se.data.BYTES_PER_ELEMENT,(Z+1)*ie/se.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Z,se.width,se.height,1,fe,Ee,de)}b.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,se.width,se.height,se.depth,fe,Ee,se.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Ae,se.width,se.height,se.depth,0,fe,Ee,se.data);else if(b.isData3DTexture)D?(be&&t.texStorage3D(i.TEXTURE_3D,ye,Ae,se.width,se.height,se.depth),ae&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,se.width,se.height,se.depth,fe,Ee,se.data)):t.texImage3D(i.TEXTURE_3D,0,Ae,se.width,se.height,se.depth,0,fe,Ee,se.data);else if(b.isFramebufferTexture){if(be)if(D)t.texStorage2D(i.TEXTURE_2D,ye,Ae,se.width,se.height);else{let ie=se.width,Z=se.height;for(let de=0;de<ye;de++)t.texImage2D(i.TEXTURE_2D,de,Ae,ie,Z,0,fe,Ee,null),ie>>=1,Z>>=1}}else if(qe.length>0){if(D&&be){const ie=we(qe[0]);t.texStorage2D(i.TEXTURE_2D,ye,Ae,ie.width,ie.height)}for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,fe,Ee,he):t.texImage2D(i.TEXTURE_2D,ie,Ae,fe,Ee,he);b.generateMipmaps=!1}else if(D){if(be){const ie=we(se);t.texStorage2D(i.TEXTURE_2D,ye,Ae,ie.width,ie.height)}ae&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,fe,Ee,se)}else t.texImage2D(i.TEXTURE_2D,0,Ae,fe,Ee,se);m(b)&&p(X),Re.__version=j.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function ne(A,b,L){if(b.image.length!==6)return;const X=Fe(A,b),Q=b.source;t.bindTexture(i.TEXTURE_CUBE_MAP,A.__webglTexture,i.TEXTURE0+L);const j=n.get(Q);if(Q.version!==j.__version||X===!0){t.activeTexture(i.TEXTURE0+L);const Re=Ze.getPrimaries(Ze.workingColorSpace),ue=b.colorSpace===Ii?null:Ze.getPrimaries(b.colorSpace),Me=b.colorSpace===Ii||Re===ue?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Me);const Ne=b.isCompressedTexture||b.image[0].isCompressedTexture,se=b.image[0]&&b.image[0].isDataTexture,fe=[];for(let Z=0;Z<6;Z++)!Ne&&!se?fe[Z]=v(b.image[Z],!0,s.maxCubemapSize):fe[Z]=se?b.image[Z].image:b.image[Z],fe[Z]=yt(b,fe[Z]);const Ee=fe[0],Ae=r.convert(b.format,b.colorSpace),he=r.convert(b.type),qe=C(b.internalFormat,Ae,he,b.colorSpace),D=b.isVideoTexture!==!0,be=j.__version===void 0||X===!0,ae=Q.dataReady;let ye=S(b,Ee);Be(i.TEXTURE_CUBE_MAP,b);let ie;if(Ne){D&&be&&t.texStorage2D(i.TEXTURE_CUBE_MAP,ye,qe,Ee.width,Ee.height);for(let Z=0;Z<6;Z++){ie=fe[Z].mipmaps;for(let de=0;de<ie.length;de++){const Ue=ie[de];b.format!==In?Ae!==null?D?ae&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,0,0,Ue.width,Ue.height,Ae,Ue.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,qe,Ue.width,Ue.height,0,Ue.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,0,0,Ue.width,Ue.height,Ae,he,Ue.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,qe,Ue.width,Ue.height,0,Ae,he,Ue.data)}}}else{if(ie=b.mipmaps,D&&be){ie.length>0&&ye++;const Z=we(fe[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,ye,qe,Z.width,Z.height)}for(let Z=0;Z<6;Z++)if(se){D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,fe[Z].width,fe[Z].height,Ae,he,fe[Z].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,qe,fe[Z].width,fe[Z].height,0,Ae,he,fe[Z].data);for(let de=0;de<ie.length;de++){const St=ie[de].image[Z].image;D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,0,0,St.width,St.height,Ae,he,St.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,qe,St.width,St.height,0,Ae,he,St.data)}}else{D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,Ae,he,fe[Z]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,qe,Ae,he,fe[Z]);for(let de=0;de<ie.length;de++){const Ue=ie[de];D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,0,0,Ae,he,Ue.image[Z]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,qe,Ae,he,Ue.image[Z])}}}m(b)&&p(i.TEXTURE_CUBE_MAP),j.__version=Q.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function xe(A,b,L,X,Q,j){const Re=r.convert(L.format,L.colorSpace),ue=r.convert(L.type),Me=C(L.internalFormat,Re,ue,L.colorSpace),Ne=n.get(b),se=n.get(L);if(se.__renderTarget=b,!Ne.__hasExternalTextures){const fe=Math.max(1,b.width>>j),Ee=Math.max(1,b.height>>j);Q===i.TEXTURE_3D||Q===i.TEXTURE_2D_ARRAY?t.texImage3D(Q,j,Me,fe,Ee,b.depth,0,Re,ue,null):t.texImage2D(Q,j,Me,fe,Ee,0,Re,ue,null)}t.bindFramebuffer(i.FRAMEBUFFER,A),Ft(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,X,Q,se.__webglTexture,0,I(b)):(Q===i.TEXTURE_2D||Q>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&Q<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,X,Q,se.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ge(A,b,L){if(i.bindRenderbuffer(i.RENDERBUFFER,A),b.depthBuffer){const X=b.depthTexture,Q=X&&X.isDepthTexture?X.type:null,j=_(b.stencilBuffer,Q),Re=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Ft(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),j,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),j,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,j,b.width,b.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Re,i.RENDERBUFFER,A)}else{const X=b.textures;for(let Q=0;Q<X.length;Q++){const j=X[Q],Re=r.convert(j.format,j.colorSpace),ue=r.convert(j.type),Me=C(j.internalFormat,Re,ue,j.colorSpace);Ft(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),Me,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),Me,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,Me,b.width,b.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ce(A,b,L){const X=b.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,A),!(b.depthTexture&&b.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const Q=n.get(b.depthTexture);if(Q.__renderTarget=b,(!Q.__webglTexture||b.depthTexture.image.width!==b.width||b.depthTexture.image.height!==b.height)&&(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0),X){if(Q.__webglInit===void 0&&(Q.__webglInit=!0,b.depthTexture.addEventListener("dispose",E)),Q.__webglTexture===void 0){Q.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,Q.__webglTexture),Be(i.TEXTURE_CUBE_MAP,b.depthTexture);const Ne=r.convert(b.depthTexture.format),se=r.convert(b.depthTexture.type);let fe;b.depthTexture.format===fi?fe=i.DEPTH_COMPONENT24:b.depthTexture.format===rs&&(fe=i.DEPTH24_STENCIL8);for(let Ee=0;Ee<6;Ee++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ee,0,fe,b.width,b.height,0,Ne,se,null)}}else $(b.depthTexture,0);const j=Q.__webglTexture,Re=I(b),ue=X?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Me=b.depthTexture.format===rs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(b.depthTexture.format===fi)Ft(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Me,ue,j,0,Re):i.framebufferTexture2D(i.FRAMEBUFFER,Me,ue,j,0);else if(b.depthTexture.format===rs)Ft(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Me,ue,j,0,Re):i.framebufferTexture2D(i.FRAMEBUFFER,Me,ue,j,0);else throw new Error("Unknown depthTexture format")}function nt(A){const b=n.get(A),L=A.isWebGLCubeRenderTarget===!0;if(b.__boundDepthTexture!==A.depthTexture){const X=A.depthTexture;if(b.__depthDisposeCallback&&b.__depthDisposeCallback(),X){const Q=()=>{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,X.removeEventListener("dispose",Q)};X.addEventListener("dispose",Q),b.__depthDisposeCallback=Q}b.__boundDepthTexture=X}if(A.depthTexture&&!b.__autoAllocateDepthBuffer)if(L)for(let X=0;X<6;X++)Ce(b.__webglFramebuffer[X],A,X);else{const X=A.texture.mipmaps;X&&X.length>0?Ce(b.__webglFramebuffer[0],A,0):Ce(b.__webglFramebuffer,A,0)}else if(L){b.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[X]),b.__webglDepthbuffer[X]===void 0)b.__webglDepthbuffer[X]=i.createRenderbuffer(),Ge(b.__webglDepthbuffer[X],A,!1);else{const Q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer[X];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,Q,i.RENDERBUFFER,j)}}else{const X=A.texture.mipmaps;if(X&&X.length>0?t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=i.createRenderbuffer(),Ge(b.__webglDepthbuffer,A,!1);else{const Q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,Q,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function Xt(A,b,L){const X=n.get(A);b!==void 0&&xe(X.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&nt(A)}function et(A){const b=A.texture,L=n.get(A),X=n.get(b);A.addEventListener("dispose",w);const Q=A.textures,j=A.isWebGLCubeRenderTarget===!0,Re=Q.length>1;if(Re||(X.__webglTexture===void 0&&(X.__webglTexture=i.createTexture()),X.__version=b.version,o.memory.textures++),j){L.__webglFramebuffer=[];for(let ue=0;ue<6;ue++)if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer[ue]=[];for(let Me=0;Me<b.mipmaps.length;Me++)L.__webglFramebuffer[ue][Me]=i.createFramebuffer()}else L.__webglFramebuffer[ue]=i.createFramebuffer()}else{if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer=[];for(let ue=0;ue<b.mipmaps.length;ue++)L.__webglFramebuffer[ue]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(Re)for(let ue=0,Me=Q.length;ue<Me;ue++){const Ne=n.get(Q[ue]);Ne.__webglTexture===void 0&&(Ne.__webglTexture=i.createTexture(),o.memory.textures++)}if(A.samples>0&&Ft(A)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let ue=0;ue<Q.length;ue++){const Me=Q[ue];L.__webglColorRenderbuffer[ue]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[ue]);const Ne=r.convert(Me.format,Me.colorSpace),se=r.convert(Me.type),fe=C(Me.internalFormat,Ne,se,Me.colorSpace,A.isXRRenderTarget===!0),Ee=I(A);i.renderbufferStorageMultisample(i.RENDERBUFFER,Ee,fe,A.width,A.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+ue,i.RENDERBUFFER,L.__webglColorRenderbuffer[ue])}i.bindRenderbuffer(i.RENDERBUFFER,null),A.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),Ge(L.__webglDepthRenderbuffer,A,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,X.__webglTexture),Be(i.TEXTURE_CUBE_MAP,b);for(let ue=0;ue<6;ue++)if(b.mipmaps&&b.mipmaps.length>0)for(let Me=0;Me<b.mipmaps.length;Me++)xe(L.__webglFramebuffer[ue][Me],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ue,Me);else xe(L.__webglFramebuffer[ue],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0);m(b)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Re){for(let ue=0,Me=Q.length;ue<Me;ue++){const Ne=Q[ue],se=n.get(Ne);let fe=i.TEXTURE_2D;(A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(fe=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(fe,se.__webglTexture),Be(fe,Ne),xe(L.__webglFramebuffer,A,Ne,i.COLOR_ATTACHMENT0+ue,fe,0),m(Ne)&&p(fe)}t.unbindTexture()}else{let ue=i.TEXTURE_2D;if((A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(ue=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ue,X.__webglTexture),Be(ue,b),b.mipmaps&&b.mipmaps.length>0)for(let Me=0;Me<b.mipmaps.length;Me++)xe(L.__webglFramebuffer[Me],A,b,i.COLOR_ATTACHMENT0,ue,Me);else xe(L.__webglFramebuffer,A,b,i.COLOR_ATTACHMENT0,ue,0);m(b)&&p(ue),t.unbindTexture()}A.depthBuffer&&nt(A)}function lt(A){const b=A.textures;for(let L=0,X=b.length;L<X;L++){const Q=b[L];if(m(Q)){const j=T(A),Re=n.get(Q).__webglTexture;t.bindTexture(j,Re),p(j),t.unbindTexture()}}}const vt=[],We=[];function Ut(A){if(A.samples>0){if(Ft(A)===!1){const b=A.textures,L=A.width,X=A.height;let Q=i.COLOR_BUFFER_BIT;const j=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Re=n.get(A),ue=b.length>1;if(ue)for(let Ne=0;Ne<b.length;Ne++)t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Re.__webglMultisampledFramebuffer);const Me=A.texture.mipmaps;Me&&Me.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglFramebuffer);for(let Ne=0;Ne<b.length;Ne++){if(A.resolveDepthBuffer&&(A.depthBuffer&&(Q|=i.DEPTH_BUFFER_BIT),A.stencilBuffer&&A.resolveStencilBuffer&&(Q|=i.STENCIL_BUFFER_BIT)),ue){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Re.__webglColorRenderbuffer[Ne]);const se=n.get(b[Ne]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,se,0)}i.blitFramebuffer(0,0,L,X,0,0,L,X,Q,i.NEAREST),c===!0&&(vt.length=0,We.length=0,vt.push(i.COLOR_ATTACHMENT0+Ne),A.depthBuffer&&A.resolveDepthBuffer===!1&&(vt.push(j),We.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,We)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,vt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),ue)for(let Ne=0;Ne<b.length;Ne++){t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.RENDERBUFFER,Re.__webglColorRenderbuffer[Ne]);const se=n.get(b[Ne]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.TEXTURE_2D,se,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglMultisampledFramebuffer)}else if(A.depthBuffer&&A.resolveDepthBuffer===!1&&c){const b=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[b])}}}function I(A){return Math.min(s.maxSamples,A.samples)}function Ft(A){const b=n.get(A);return A.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function at(A){const b=o.render.frame;d.get(A)!==b&&(d.set(A,b),A.update())}function yt(A,b){const L=A.colorSpace,X=A.format,Q=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||L!==ks&&L!==Ii&&(Ze.getTransfer(L)===ct?(X!==In||Q!==Tn)&&Oe("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):tt("WebGLTextures: Unsupported texture color space:",L)),b}function we(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=U,this.resetTextureUnits=O,this.setTexture2D=$,this.setTexture2DArray=G,this.setTexture3D=W,this.setTextureCube=ee,this.rebindTextures=Xt,this.setupRenderTarget=et,this.updateRenderTargetMipmap=lt,this.updateMultisampleRenderTarget=Ut,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=Ft,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function By(i,e){function t(n,s=Ii){let r;const o=Ze.getTransfer(s);if(n===Tn)return i.UNSIGNED_BYTE;if(n===Jo)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Zo)return i.UNSIGNED_SHORT_5_5_5_1;if(n===_u)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===bu)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===gu)return i.BYTE;if(n===vu)return i.SHORT;if(n===xr)return i.UNSIGNED_SHORT;if(n===Yo)return i.INT;if(n===Xn)return i.UNSIGNED_INT;if(n===$n)return i.FLOAT;if(n===hi)return i.HALF_FLOAT;if(n===yu)return i.ALPHA;if(n===Su)return i.RGB;if(n===In)return i.RGBA;if(n===fi)return i.DEPTH_COMPONENT;if(n===rs)return i.DEPTH_STENCIL;if(n===xu)return i.RED;if(n===Qo)return i.RED_INTEGER;if(n===Ps)return i.RG;if(n===ec)return i.RG_INTEGER;if(n===tc)return i.RGBA_INTEGER;if(n===da||n===ua||n===ha||n===fa)if(o===ct)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===da)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===ua)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===ha)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===fa)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===da)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===ua)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===ha)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===fa)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===nc||n===ic||n===sc||n===rc)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===nc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ic)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===sc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===rc)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ac||n===oc||n===cc||n===lc||n===dc||n===uc||n===hc)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===ac||n===oc)return o===ct?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===cc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===lc)return r.COMPRESSED_R11_EAC;if(n===dc)return r.COMPRESSED_SIGNED_R11_EAC;if(n===uc)return r.COMPRESSED_RG11_EAC;if(n===hc)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===fc||n===pc||n===mc||n===gc||n===vc||n===_c||n===bc||n===yc||n===Sc||n===xc||n===Tc||n===Ec||n===Cc||n===Mc)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===fc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===pc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===mc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===gc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===vc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===_c)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===bc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===yc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Sc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===xc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Tc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ec)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Cc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Mc)return o===ct?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===wc||n===Ac||n===Rc)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===wc)return o===ct?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ac)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Rc)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Pc||n===kc||n===Ic||n===Dc)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===Pc)return r.COMPRESSED_RED_RGTC1_EXT;if(n===kc)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Ic)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Dc)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Tr?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const Vy=`
4033
+ }`,Dy=[new V(1,0,0),new V(-1,0,0),new V(0,1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1)],Ly=[new V(0,-1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1),new V(0,-1,0),new V(0,-1,0)],Ih=new Dt,Ur=new V,bl=new V;function Ny(i,e,t){let n=new th;const s=new st,r=new st,o=new Pt,a=new Pv,c=new kv,l={},d=t.maxTextureSize,u={[ci]:en,[en]:ci,[li]:li},h=new Mn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new st},radius:{value:4}},vertexShader:ky,fragmentShader:Iy}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new Un;g.setAttribute("position",new Jn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Fn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=aa;let p=this.type;this.render=function(E,w,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||E.length===0)return;E.type===bg&&(Oe("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),E.type=aa);const y=i.getRenderTarget(),x=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),O=i.state;O.setBlending(di),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const U=p!==this.type;U&&w.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach($=>$.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,$=E.length;q<$;q++){const G=E[q],W=G.shadow;if(W===void 0){Oe("WebGLShadowMap:",G,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const ee=W.getFrameExtents();if(s.multiply(ee),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/ee.x),s.x=r.x*ee.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/ee.y),s.y=r.y*ee.y,W.mapSize.y=r.y)),W.map===null||U===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Sr){if(G.isPointLight){Oe("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Yn(s.x,s.y,{format:Rs,type:hi,minFilter:Jt,magFilter:Jt,generateMipmaps:!1}),W.map.texture.name=G.name+".shadowMap",W.map.depthTexture=new Lr(s.x,s.y,$n),W.map.depthTexture.name=G.name+".shadowMapDepth",W.map.depthTexture.format=fi,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=$t,W.map.depthTexture.magFilter=$t}else{G.isPointLight?(W.map=new eh(s.x),W.map.depthTexture=new Av(s.x,Xn)):(W.map=new Yn(s.x,s.y),W.map.depthTexture=new Lr(s.x,s.y,Xn)),W.map.depthTexture.name=G.name+".shadowMap",W.map.depthTexture.format=fi;const le=i.state.buffers.depth.getReversed();this.type===aa?(W.map.depthTexture.compareFunction=le?Nc:Lc,W.map.depthTexture.minFilter=Jt,W.map.depthTexture.magFilter=Jt):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=$t,W.map.depthTexture.magFilter=$t)}W.camera.updateProjectionMatrix()}const ge=W.map.isWebGLCubeRenderTarget?6:1;for(let le=0;le<ge;le++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,le),i.clear();else{le===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(le);o.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),O.viewport(o)}if(G.isPointLight){const _e=W.camera,Be=W.matrix,Fe=G.distance||_e.far;Fe!==_e.far&&(_e.far=Fe,_e.updateProjectionMatrix()),Ur.setFromMatrixPosition(G.matrixWorld),_e.position.copy(Ur),bl.copy(_e.position),bl.add(Dy[le]),_e.up.copy(Ly[le]),_e.lookAt(bl),_e.updateMatrixWorld(),Be.makeTranslation(-Ur.x,-Ur.y,-Ur.z),Ih.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(Ih,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(G);n=W.getFrustum(),_(w,k,W.camera,G,this.type)}W.isPointLightShadow!==!0&&this.type===Sr&&T(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(y,x,R)};function T(E,w){const k=e.update(v);h.defines.VSM_SAMPLES!==E.blurSamples&&(h.defines.VSM_SAMPLES=E.blurSamples,f.defines.VSM_SAMPLES=E.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),E.mapPass===null&&(E.mapPass=new Yn(s.x,s.y,{format:Rs,type:hi})),h.uniforms.shadow_pass.value=E.map.depthTexture,h.uniforms.resolution.value=E.mapSize,h.uniforms.radius.value=E.radius,i.setRenderTarget(E.mapPass),i.clear(),i.renderBufferDirect(w,null,k,h,v,null),f.uniforms.shadow_pass.value=E.mapPass.texture,f.uniforms.resolution.value=E.mapSize,f.uniforms.radius.value=E.radius,i.setRenderTarget(E.map),i.clear(),i.renderBufferDirect(w,null,k,f,v,null)}function C(E,w,k,y){let x=null;const R=k.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(R!==void 0)x=R;else if(x=k.isPointLight===!0?c:a,i.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=x.uuid,U=w.uuid;let q=l[O];q===void 0&&(q={},l[O]=q);let $=q[U];$===void 0&&($=x.clone(),q[U]=$,w.addEventListener("dispose",S)),x=$}if(x.visible=w.visible,x.wireframe=w.wireframe,y===Sr?x.side=w.shadowSide!==null?w.shadowSide:w.side:x.side=w.shadowSide!==null?w.shadowSide:u[w.side],x.alphaMap=w.alphaMap,x.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,x.map=w.map,x.clipShadows=w.clipShadows,x.clippingPlanes=w.clippingPlanes,x.clipIntersection=w.clipIntersection,x.displacementMap=w.displacementMap,x.displacementScale=w.displacementScale,x.displacementBias=w.displacementBias,x.wireframeLinewidth=w.wireframeLinewidth,x.linewidth=w.linewidth,k.isPointLight===!0&&x.isMeshDistanceMaterial===!0){const O=i.properties.get(x);O.light=k}return x}function _(E,w,k,y,x){if(E.visible===!1)return;if(E.layers.test(w.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&x===Sr)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,E.matrixWorld);const U=e.update(E),q=E.material;if(Array.isArray(q)){const $=U.groups;for(let G=0,W=$.length;G<W;G++){const ee=$[G],ge=q[ee.materialIndex];if(ge&&ge.visible){const le=C(E,ge,y,x);E.onBeforeShadow(i,E,w,k,U,le,ee),i.renderBufferDirect(k,null,U,le,E,ee),E.onAfterShadow(i,E,w,k,U,le,ee)}}}else if(q.visible){const $=C(E,q,y,x);E.onBeforeShadow(i,E,w,k,U,$,null),i.renderBufferDirect(k,null,U,$,E,null),E.onAfterShadow(i,E,w,k,U,$,null)}}const O=E.children;for(let U=0,q=O.length;U<q;U++)_(O[U],w,k,y,x)}function S(E){E.target.removeEventListener("dispose",S);for(const k in l){const y=l[k],x=E.target.uuid;x in y&&(y[x].dispose(),delete y[x])}}}const Oy={[Fo]:Bo,[Vo]:Ho,[zo]:Wo,[ws]:Go,[Bo]:Fo,[Ho]:Vo,[Wo]:zo,[Go]:ws};function Uy(i,e){function t(){let D=!1;const be=new Pt;let ae=null;const ye=new Pt(0,0,0,0);return{setMask:function(ie){ae!==ie&&!D&&(i.colorMask(ie,ie,ie,ie),ae=ie)},setLocked:function(ie){D=ie},setClear:function(ie,Z,de,Ue,yt){yt===!0&&(ie*=Ue,Z*=Ue,de*=Ue),be.set(ie,Z,de,Ue),ye.equals(be)===!1&&(i.clearColor(ie,Z,de,Ue),ye.copy(be))},reset:function(){D=!1,ae=null,ye.set(-1,0,0,0)}}}function n(){let D=!1,be=!1,ae=null,ye=null,ie=null;return{setReversed:function(Z){if(be!==Z){const de=e.get("EXT_clip_control");Z?de.clipControlEXT(de.LOWER_LEFT_EXT,de.ZERO_TO_ONE_EXT):de.clipControlEXT(de.LOWER_LEFT_EXT,de.NEGATIVE_ONE_TO_ONE_EXT),be=Z;const Ue=ie;ie=null,this.setClear(Ue)}},getReversed:function(){return be},setTest:function(Z){Z?ne(i.DEPTH_TEST):xe(i.DEPTH_TEST)},setMask:function(Z){ae!==Z&&!D&&(i.depthMask(Z),ae=Z)},setFunc:function(Z){if(be&&(Z=Oy[Z]),ye!==Z){switch(Z){case Fo:i.depthFunc(i.NEVER);break;case Bo:i.depthFunc(i.ALWAYS);break;case Vo:i.depthFunc(i.LESS);break;case ws:i.depthFunc(i.LEQUAL);break;case zo:i.depthFunc(i.EQUAL);break;case Go:i.depthFunc(i.GEQUAL);break;case Ho:i.depthFunc(i.GREATER);break;case Wo:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}ye=Z}},setLocked:function(Z){D=Z},setClear:function(Z){ie!==Z&&(be&&(Z=1-Z),i.clearDepth(Z),ie=Z)},reset:function(){D=!1,ae=null,ye=null,ie=null,be=!1}}}function s(){let D=!1,be=null,ae=null,ye=null,ie=null,Z=null,de=null,Ue=null,yt=null;return{setTest:function(lt){D||(lt?ne(i.STENCIL_TEST):xe(i.STENCIL_TEST))},setMask:function(lt){be!==lt&&!D&&(i.stencilMask(lt),be=lt)},setFunc:function(lt,oi,Ai){(ae!==lt||ye!==oi||ie!==Ai)&&(i.stencilFunc(lt,oi,Ai),ae=lt,ye=oi,ie=Ai)},setOp:function(lt,oi,Ai){(Z!==lt||de!==oi||Ue!==Ai)&&(i.stencilOp(lt,oi,Ai),Z=lt,de=oi,Ue=Ai)},setLocked:function(lt){D=lt},setClear:function(lt){yt!==lt&&(i.clearStencil(lt),yt=lt)},reset:function(){D=!1,be=null,ae=null,ye=null,ie=null,Z=null,de=null,Ue=null,yt=null}}}const r=new t,o=new n,a=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,C=null,_=null,S=null,E=null,w=new Je(0,0,0),k=0,y=!1,x=null,R=null,O=null,U=null,q=null;const $=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let G=!1,W=0;const ee=i.getParameter(i.VERSION);ee.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(ee)[1]),G=W>=1):ee.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(ee)[1]),G=W>=2);let ge=null,le={};const _e=i.getParameter(i.SCISSOR_BOX),Be=i.getParameter(i.VIEWPORT),Fe=new Pt().fromArray(_e),Tt=new Pt().fromArray(Be);function ht(D,be,ae,ye){const ie=new Uint8Array(4),Z=i.createTexture();i.bindTexture(D,Z),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let de=0;de<ae;de++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(be,0,i.RGBA,1,1,ye,0,i.RGBA,i.UNSIGNED_BYTE,ie):i.texImage2D(be+de,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,ie);return Z}const K={};K[i.TEXTURE_2D]=ht(i.TEXTURE_2D,i.TEXTURE_2D,1),K[i.TEXTURE_CUBE_MAP]=ht(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),K[i.TEXTURE_2D_ARRAY]=ht(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),K[i.TEXTURE_3D]=ht(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),ne(i.DEPTH_TEST),o.setFunc(ws),We(!1),Ot(su),ne(i.CULL_FACE),ct(di);function ne(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function xe(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function Ge(D,be){return u[D]!==be?(i.bindFramebuffer(D,be),u[D]=be,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=be),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=be),!0):!1}function Ce(D,be){let ae=f,ye=!1;if(D){ae=h.get(be),ae===void 0&&(ae=[],h.set(be,ae));const ie=D.textures;if(ae.length!==ie.length||ae[0]!==i.COLOR_ATTACHMENT0){for(let Z=0,de=ie.length;Z<de;Z++)ae[Z]=i.COLOR_ATTACHMENT0+Z;ae.length=ie.length,ye=!0}}else ae[0]!==i.BACK&&(ae[0]=i.BACK,ye=!0);ye&&i.drawBuffers(ae)}function nt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const Xt={[ns]:i.FUNC_ADD,[Sg]:i.FUNC_SUBTRACT,[xg]:i.FUNC_REVERSE_SUBTRACT};Xt[Tg]=i.MIN,Xt[Eg]=i.MAX;const et={[Cg]:i.ZERO,[Mg]:i.ONE,[wg]:i.SRC_COLOR,[Oo]:i.SRC_ALPHA,[Dg]:i.SRC_ALPHA_SATURATE,[kg]:i.DST_COLOR,[Rg]:i.DST_ALPHA,[Ag]:i.ONE_MINUS_SRC_COLOR,[Uo]:i.ONE_MINUS_SRC_ALPHA,[Ig]:i.ONE_MINUS_DST_COLOR,[Pg]:i.ONE_MINUS_DST_ALPHA,[Lg]:i.CONSTANT_COLOR,[Ng]:i.ONE_MINUS_CONSTANT_COLOR,[Og]:i.CONSTANT_ALPHA,[Ug]:i.ONE_MINUS_CONSTANT_ALPHA};function ct(D,be,ae,ye,ie,Z,de,Ue,yt,lt){if(D===di){v===!0&&(xe(i.BLEND),v=!1);return}if(v===!1&&(ne(i.BLEND),v=!0),D!==yg){if(D!==m||lt!==y){if((p!==ns||_!==ns)&&(i.blendEquation(i.FUNC_ADD),p=ns,_=ns),lt)switch(D){case Ms:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case No:i.blendFunc(i.ONE,i.ONE);break;case ru:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case au:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:tt("WebGLState: Invalid blending: ",D);break}else switch(D){case Ms:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case No:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case ru:tt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case au:tt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:tt("WebGLState: Invalid blending: ",D);break}T=null,C=null,S=null,E=null,w.set(0,0,0),k=0,m=D,y=lt}return}ie=ie||be,Z=Z||ae,de=de||ye,(be!==p||ie!==_)&&(i.blendEquationSeparate(Xt[be],Xt[ie]),p=be,_=ie),(ae!==T||ye!==C||Z!==S||de!==E)&&(i.blendFuncSeparate(et[ae],et[ye],et[Z],et[de]),T=ae,C=ye,S=Z,E=de),(Ue.equals(w)===!1||yt!==k)&&(i.blendColor(Ue.r,Ue.g,Ue.b,yt),w.copy(Ue),k=yt),m=D,y=!1}function gt(D,be){D.side===li?xe(i.CULL_FACE):ne(i.CULL_FACE);let ae=D.side===en;be&&(ae=!ae),We(ae),D.blending===Ms&&D.transparent===!1?ct(di):ct(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),o.setFunc(D.depthFunc),o.setTest(D.depthTest),o.setMask(D.depthWrite),r.setMask(D.colorWrite);const ye=D.stencilWrite;a.setTest(ye),ye&&(a.setMask(D.stencilWriteMask),a.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),a.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Ut(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ne(i.SAMPLE_ALPHA_TO_COVERAGE):xe(i.SAMPLE_ALPHA_TO_COVERAGE)}function We(D){x!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),x=D)}function Ot(D){D!==vg?(ne(i.CULL_FACE),D!==R&&(D===su?i.cullFace(i.BACK):D===_g?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):xe(i.CULL_FACE),R=D}function I(D){D!==O&&(G&&i.lineWidth(D),O=D)}function Ut(D,be,ae){D?(ne(i.POLYGON_OFFSET_FILL),(U!==be||q!==ae)&&(i.polygonOffset(be,ae),U=be,q=ae)):xe(i.POLYGON_OFFSET_FILL)}function at(D){D?ne(i.SCISSOR_TEST):xe(i.SCISSOR_TEST)}function bt(D){D===void 0&&(D=i.TEXTURE0+$-1),ge!==D&&(i.activeTexture(D),ge=D)}function we(D,be,ae){ae===void 0&&(ge===null?ae=i.TEXTURE0+$-1:ae=ge);let ye=le[ae];ye===void 0&&(ye={type:void 0,texture:void 0},le[ae]=ye),(ye.type!==D||ye.texture!==be)&&(ge!==ae&&(i.activeTexture(ae),ge=ae),i.bindTexture(D,be||K[D]),ye.type=D,ye.texture=be)}function A(){const D=le[ge];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function b(){try{i.compressedTexImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function X(){try{i.texSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Q(){try{i.texSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Re(){try{i.compressedTexSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function ue(){try{i.texStorage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Me(){try{i.texStorage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ne(){try{i.texImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function se(){try{i.texImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function fe(D){Fe.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Fe.copy(D))}function Ee(D){Tt.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Tt.copy(D))}function Ae(D,be){let ae=l.get(be);ae===void 0&&(ae=new WeakMap,l.set(be,ae));let ye=ae.get(D);ye===void 0&&(ye=i.getUniformBlockIndex(be,D.name),ae.set(D,ye))}function he(D,be){const ye=l.get(be).get(D);c.get(be)!==ye&&(i.uniformBlockBinding(be,ye,D.__bindingPointIndex),c.set(be,ye))}function qe(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),o.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ge=null,le={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,C=null,_=null,S=null,E=null,w=new Je(0,0,0),k=0,y=!1,x=null,R=null,O=null,U=null,q=null,Fe.set(0,0,i.canvas.width,i.canvas.height),Tt.set(0,0,i.canvas.width,i.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:ne,disable:xe,bindFramebuffer:Ge,drawBuffers:Ce,useProgram:nt,setBlending:ct,setMaterial:gt,setFlipSided:We,setCullFace:Ot,setLineWidth:I,setPolygonOffset:Ut,setScissorTest:at,activeTexture:bt,bindTexture:we,unbindTexture:A,compressedTexImage2D:b,compressedTexImage3D:L,texImage2D:Ne,texImage3D:se,updateUBOMapping:Ae,uniformBlockBinding:he,texStorage2D:ue,texStorage3D:Me,texSubImage2D:X,texSubImage3D:Q,compressedTexSubImage2D:j,compressedTexSubImage3D:Re,scissor:fe,viewport:Ee,reset:qe}}function Fy(i,e,t,n,s,r,o){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new st,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(A,b){return f?new OffscreenCanvas(A,b):ma("canvas")}function v(A,b,L){let X=1;const Q=we(A);if((Q.width>L||Q.height>L)&&(X=L/Math.max(Q.width,Q.height)),X<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){const j=Math.floor(X*Q.width),Re=Math.floor(X*Q.height);u===void 0&&(u=g(j,Re));const ue=b?g(j,Re):u;return ue.width=j,ue.height=Re,ue.getContext("2d").drawImage(A,0,0,j,Re),Oe("WebGLRenderer: Texture has been resized from ("+Q.width+"x"+Q.height+") to ("+j+"x"+Re+")."),ue}else return"data"in A&&Oe("WebGLRenderer: Image in DataTexture is too big ("+Q.width+"x"+Q.height+")."),A;return A}function m(A){return A.generateMipmaps}function p(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function C(A,b,L,X,Q=!1){if(A!==null){if(i[A]!==void 0)return i[A];Oe("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let j=b;if(b===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),b===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),b===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),b===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),b===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),b===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),b===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),b===i.RGBA){const Re=Q?fa:Ze.getTransfer(X);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=Re===ot?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function _(A,b){let L;return A?b===null||b===Xn||b===Tr?L=i.DEPTH24_STENCIL8:b===$n?L=i.DEPTH32F_STENCIL8:b===xr&&(L=i.DEPTH24_STENCIL8,Oe("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===Xn||b===Tr?L=i.DEPTH_COMPONENT24:b===$n?L=i.DEPTH_COMPONENT32F:b===xr&&(L=i.DEPTH_COMPONENT16),L}function S(A,b){return m(A)===!0||A.isFramebufferTexture&&A.minFilter!==$t&&A.minFilter!==Jt?Math.log2(Math.max(b.width,b.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?b.mipmaps.length:1}function E(A){const b=A.target;b.removeEventListener("dispose",E),k(b),b.isVideoTexture&&d.delete(b)}function w(A){const b=A.target;b.removeEventListener("dispose",w),x(b)}function k(A){const b=n.get(A);if(b.__webglInit===void 0)return;const L=A.source,X=h.get(L);if(X){const Q=X[b.__cacheKey];Q.usedTimes--,Q.usedTimes===0&&y(A),Object.keys(X).length===0&&h.delete(L)}n.remove(A)}function y(A){const b=n.get(A);i.deleteTexture(b.__webglTexture);const L=A.source,X=h.get(L);delete X[b.__cacheKey],o.memory.textures--}function x(A){const b=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(b.__webglFramebuffer[X]))for(let Q=0;Q<b.__webglFramebuffer[X].length;Q++)i.deleteFramebuffer(b.__webglFramebuffer[X][Q]);else i.deleteFramebuffer(b.__webglFramebuffer[X]);b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer[X])}else{if(Array.isArray(b.__webglFramebuffer))for(let X=0;X<b.__webglFramebuffer.length;X++)i.deleteFramebuffer(b.__webglFramebuffer[X]);else i.deleteFramebuffer(b.__webglFramebuffer);if(b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer),b.__webglMultisampledFramebuffer&&i.deleteFramebuffer(b.__webglMultisampledFramebuffer),b.__webglColorRenderbuffer)for(let X=0;X<b.__webglColorRenderbuffer.length;X++)b.__webglColorRenderbuffer[X]&&i.deleteRenderbuffer(b.__webglColorRenderbuffer[X]);b.__webglDepthRenderbuffer&&i.deleteRenderbuffer(b.__webglDepthRenderbuffer)}const L=A.textures;for(let X=0,Q=L.length;X<Q;X++){const j=n.get(L[X]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),o.memory.textures--),n.remove(L[X])}n.remove(A)}let R=0;function O(){R=0}function U(){const A=R;return A>=s.maxTextures&&Oe("WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+s.maxTextures),R+=1,A}function q(A){const b=[];return b.push(A.wrapS),b.push(A.wrapT),b.push(A.wrapR||0),b.push(A.magFilter),b.push(A.minFilter),b.push(A.anisotropy),b.push(A.internalFormat),b.push(A.format),b.push(A.type),b.push(A.generateMipmaps),b.push(A.premultiplyAlpha),b.push(A.flipY),b.push(A.unpackAlignment),b.push(A.colorSpace),b.join()}function $(A,b){const L=n.get(A);if(A.isVideoTexture&&at(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&L.__version!==A.version){const X=A.image;if(X===null)Oe("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)Oe("WebGLRenderer: Texture marked for update but image is incomplete");else{K(L,A,b);return}}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+b)}function G(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){K(L,A,b);return}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+b)}function W(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){K(L,A,b);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+b)}function ee(A,b){const L=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&L.__version!==A.version){ne(L,A,b);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+b)}const ge={[Xo]:i.REPEAT,[ui]:i.CLAMP_TO_EDGE,[$o]:i.MIRRORED_REPEAT},le={[$t]:i.NEAREST,[Vg]:i.NEAREST_MIPMAP_NEAREST,[ca]:i.NEAREST_MIPMAP_LINEAR,[Jt]:i.LINEAR,[Ko]:i.LINEAR_MIPMAP_NEAREST,[ss]:i.LINEAR_MIPMAP_LINEAR},_e={[Wg]:i.NEVER,[Kg]:i.ALWAYS,[qg]:i.LESS,[Lc]:i.LEQUAL,[jg]:i.EQUAL,[Nc]:i.GEQUAL,[Xg]:i.GREATER,[$g]:i.NOTEQUAL};function Be(A,b){if(b.type===$n&&e.has("OES_texture_float_linear")===!1&&(b.magFilter===Jt||b.magFilter===Ko||b.magFilter===ca||b.magFilter===ss||b.minFilter===Jt||b.minFilter===Ko||b.minFilter===ca||b.minFilter===ss)&&Oe("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,ge[b.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,ge[b.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,ge[b.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,le[b.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,le[b.minFilter]),b.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,_e[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===$t||b.minFilter!==ca&&b.minFilter!==ss||b.type===$n&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(A,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,s.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function Fe(A,b){let L=!1;A.__webglInit===void 0&&(A.__webglInit=!0,b.addEventListener("dispose",E));const X=b.source;let Q=h.get(X);Q===void 0&&(Q={},h.set(X,Q));const j=q(b);if(j!==A.__cacheKey){Q[j]===void 0&&(Q[j]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,L=!0),Q[j].usedTimes++;const Re=Q[A.__cacheKey];Re!==void 0&&(Q[A.__cacheKey].usedTimes--,Re.usedTimes===0&&y(b)),A.__cacheKey=j,A.__webglTexture=Q[j].texture}return L}function Tt(A,b,L){return Math.floor(Math.floor(A/L)/b)}function ht(A,b,L,X){const j=A.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,b.width,b.height,L,X,b.data);else{j.sort((se,fe)=>se.start-fe.start);let Re=0;for(let se=1;se<j.length;se++){const fe=j[Re],Ee=j[se],Ae=fe.start+fe.count,he=Tt(Ee.start,b.width,4),qe=Tt(fe.start,b.width,4);Ee.start<=Ae+1&&he===qe&&Tt(Ee.start+Ee.count-1,b.width,4)===he?fe.count=Math.max(fe.count,Ee.start+Ee.count-fe.start):(++Re,j[Re]=Ee)}j.length=Re+1;const ue=i.getParameter(i.UNPACK_ROW_LENGTH),Me=i.getParameter(i.UNPACK_SKIP_PIXELS),Ne=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,b.width);for(let se=0,fe=j.length;se<fe;se++){const Ee=j[se],Ae=Math.floor(Ee.start/4),he=Math.ceil(Ee.count/4),qe=Ae%b.width,D=Math.floor(Ae/b.width),be=he,ae=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,qe),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,qe,D,be,ae,L,X,b.data)}A.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,ue),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Me),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ne)}}function K(A,b,L){let X=i.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(X=i.TEXTURE_2D_ARRAY),b.isData3DTexture&&(X=i.TEXTURE_3D);const Q=Fe(A,b),j=b.source;t.bindTexture(X,A.__webglTexture,i.TEXTURE0+L);const Re=n.get(j);if(j.version!==Re.__version||Q===!0){t.activeTexture(i.TEXTURE0+L);const ue=Ze.getPrimaries(Ze.workingColorSpace),Me=b.colorSpace===Ii?null:Ze.getPrimaries(b.colorSpace),Ne=b.colorSpace===Ii||ue===Me?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ne);let se=v(b.image,!1,s.maxTextureSize);se=bt(b,se);const fe=r.convert(b.format,b.colorSpace),Ee=r.convert(b.type);let Ae=C(b.internalFormat,fe,Ee,b.colorSpace,b.isVideoTexture);Be(X,b);let he;const qe=b.mipmaps,D=b.isVideoTexture!==!0,be=Re.__version===void 0||Q===!0,ae=j.dataReady,ye=S(b,se);if(b.isDepthTexture)Ae=_(b.format===rs,b.type),be&&(D?t.texStorage2D(i.TEXTURE_2D,1,Ae,se.width,se.height):t.texImage2D(i.TEXTURE_2D,0,Ae,se.width,se.height,0,fe,Ee,null));else if(b.isDataTexture)if(qe.length>0){D&&be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,qe[0].width,qe[0].height);for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,Ee,he.data):t.texImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,fe,Ee,he.data);b.generateMipmaps=!1}else D?(be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,se.width,se.height),ae&&ht(b,se,fe,Ee)):t.texImage2D(i.TEXTURE_2D,0,Ae,se.width,se.height,0,fe,Ee,se.data);else if(b.isCompressedTexture)if(b.isCompressedArrayTexture){D&&be&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ye,Ae,qe[0].width,qe[0].height,se.depth);for(let ie=0,Z=qe.length;ie<Z;ie++)if(he=qe[ie],b.format!==In)if(fe!==null)if(D){if(ae)if(b.layerUpdates.size>0){const de=sh(he.width,he.height,b.format,b.type);for(const Ue of b.layerUpdates){const yt=he.data.subarray(Ue*de/he.data.BYTES_PER_ELEMENT,(Ue+1)*de/he.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,Ue,he.width,he.height,1,fe,yt)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,0,he.width,he.height,se.depth,fe,he.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,ie,Ae,he.width,he.height,se.depth,0,he.data,0,0);else Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?ae&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,ie,0,0,0,he.width,he.height,se.depth,fe,Ee,he.data):t.texImage3D(i.TEXTURE_2D_ARRAY,ie,Ae,he.width,he.height,se.depth,0,fe,Ee,he.data)}else{D&&be&&t.texStorage2D(i.TEXTURE_2D,ye,Ae,qe[0].width,qe[0].height);for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],b.format!==In?fe!==null?D?ae&&t.compressedTexSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,he.data):t.compressedTexImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,he.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,he.width,he.height,fe,Ee,he.data):t.texImage2D(i.TEXTURE_2D,ie,Ae,he.width,he.height,0,fe,Ee,he.data)}else if(b.isDataArrayTexture)if(D){if(be&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ye,Ae,se.width,se.height,se.depth),ae)if(b.layerUpdates.size>0){const ie=sh(se.width,se.height,b.format,b.type);for(const Z of b.layerUpdates){const de=se.data.subarray(Z*ie/se.data.BYTES_PER_ELEMENT,(Z+1)*ie/se.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Z,se.width,se.height,1,fe,Ee,de)}b.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,se.width,se.height,se.depth,fe,Ee,se.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Ae,se.width,se.height,se.depth,0,fe,Ee,se.data);else if(b.isData3DTexture)D?(be&&t.texStorage3D(i.TEXTURE_3D,ye,Ae,se.width,se.height,se.depth),ae&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,se.width,se.height,se.depth,fe,Ee,se.data)):t.texImage3D(i.TEXTURE_3D,0,Ae,se.width,se.height,se.depth,0,fe,Ee,se.data);else if(b.isFramebufferTexture){if(be)if(D)t.texStorage2D(i.TEXTURE_2D,ye,Ae,se.width,se.height);else{let ie=se.width,Z=se.height;for(let de=0;de<ye;de++)t.texImage2D(i.TEXTURE_2D,de,Ae,ie,Z,0,fe,Ee,null),ie>>=1,Z>>=1}}else if(qe.length>0){if(D&&be){const ie=we(qe[0]);t.texStorage2D(i.TEXTURE_2D,ye,Ae,ie.width,ie.height)}for(let ie=0,Z=qe.length;ie<Z;ie++)he=qe[ie],D?ae&&t.texSubImage2D(i.TEXTURE_2D,ie,0,0,fe,Ee,he):t.texImage2D(i.TEXTURE_2D,ie,Ae,fe,Ee,he);b.generateMipmaps=!1}else if(D){if(be){const ie=we(se);t.texStorage2D(i.TEXTURE_2D,ye,Ae,ie.width,ie.height)}ae&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,fe,Ee,se)}else t.texImage2D(i.TEXTURE_2D,0,Ae,fe,Ee,se);m(b)&&p(X),Re.__version=j.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function ne(A,b,L){if(b.image.length!==6)return;const X=Fe(A,b),Q=b.source;t.bindTexture(i.TEXTURE_CUBE_MAP,A.__webglTexture,i.TEXTURE0+L);const j=n.get(Q);if(Q.version!==j.__version||X===!0){t.activeTexture(i.TEXTURE0+L);const Re=Ze.getPrimaries(Ze.workingColorSpace),ue=b.colorSpace===Ii?null:Ze.getPrimaries(b.colorSpace),Me=b.colorSpace===Ii||Re===ue?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Me);const Ne=b.isCompressedTexture||b.image[0].isCompressedTexture,se=b.image[0]&&b.image[0].isDataTexture,fe=[];for(let Z=0;Z<6;Z++)!Ne&&!se?fe[Z]=v(b.image[Z],!0,s.maxCubemapSize):fe[Z]=se?b.image[Z].image:b.image[Z],fe[Z]=bt(b,fe[Z]);const Ee=fe[0],Ae=r.convert(b.format,b.colorSpace),he=r.convert(b.type),qe=C(b.internalFormat,Ae,he,b.colorSpace),D=b.isVideoTexture!==!0,be=j.__version===void 0||X===!0,ae=Q.dataReady;let ye=S(b,Ee);Be(i.TEXTURE_CUBE_MAP,b);let ie;if(Ne){D&&be&&t.texStorage2D(i.TEXTURE_CUBE_MAP,ye,qe,Ee.width,Ee.height);for(let Z=0;Z<6;Z++){ie=fe[Z].mipmaps;for(let de=0;de<ie.length;de++){const Ue=ie[de];b.format!==In?Ae!==null?D?ae&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,0,0,Ue.width,Ue.height,Ae,Ue.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,qe,Ue.width,Ue.height,0,Ue.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,0,0,Ue.width,Ue.height,Ae,he,Ue.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de,qe,Ue.width,Ue.height,0,Ae,he,Ue.data)}}}else{if(ie=b.mipmaps,D&&be){ie.length>0&&ye++;const Z=we(fe[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,ye,qe,Z.width,Z.height)}for(let Z=0;Z<6;Z++)if(se){D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,fe[Z].width,fe[Z].height,Ae,he,fe[Z].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,qe,fe[Z].width,fe[Z].height,0,Ae,he,fe[Z].data);for(let de=0;de<ie.length;de++){const yt=ie[de].image[Z].image;D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,0,0,yt.width,yt.height,Ae,he,yt.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,qe,yt.width,yt.height,0,Ae,he,yt.data)}}else{D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,Ae,he,fe[Z]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,qe,Ae,he,fe[Z]);for(let de=0;de<ie.length;de++){const Ue=ie[de];D?ae&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,0,0,Ae,he,Ue.image[Z]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,de+1,qe,Ae,he,Ue.image[Z])}}}m(b)&&p(i.TEXTURE_CUBE_MAP),j.__version=Q.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function xe(A,b,L,X,Q,j){const Re=r.convert(L.format,L.colorSpace),ue=r.convert(L.type),Me=C(L.internalFormat,Re,ue,L.colorSpace),Ne=n.get(b),se=n.get(L);if(se.__renderTarget=b,!Ne.__hasExternalTextures){const fe=Math.max(1,b.width>>j),Ee=Math.max(1,b.height>>j);Q===i.TEXTURE_3D||Q===i.TEXTURE_2D_ARRAY?t.texImage3D(Q,j,Me,fe,Ee,b.depth,0,Re,ue,null):t.texImage2D(Q,j,Me,fe,Ee,0,Re,ue,null)}t.bindFramebuffer(i.FRAMEBUFFER,A),Ut(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,X,Q,se.__webglTexture,0,I(b)):(Q===i.TEXTURE_2D||Q>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&Q<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,X,Q,se.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ge(A,b,L){if(i.bindRenderbuffer(i.RENDERBUFFER,A),b.depthBuffer){const X=b.depthTexture,Q=X&&X.isDepthTexture?X.type:null,j=_(b.stencilBuffer,Q),Re=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Ut(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),j,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),j,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,j,b.width,b.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Re,i.RENDERBUFFER,A)}else{const X=b.textures;for(let Q=0;Q<X.length;Q++){const j=X[Q],Re=r.convert(j.format,j.colorSpace),ue=r.convert(j.type),Me=C(j.internalFormat,Re,ue,j.colorSpace);Ut(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),Me,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),Me,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,Me,b.width,b.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ce(A,b,L){const X=b.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,A),!(b.depthTexture&&b.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const Q=n.get(b.depthTexture);if(Q.__renderTarget=b,(!Q.__webglTexture||b.depthTexture.image.width!==b.width||b.depthTexture.image.height!==b.height)&&(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0),X){if(Q.__webglInit===void 0&&(Q.__webglInit=!0,b.depthTexture.addEventListener("dispose",E)),Q.__webglTexture===void 0){Q.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,Q.__webglTexture),Be(i.TEXTURE_CUBE_MAP,b.depthTexture);const Ne=r.convert(b.depthTexture.format),se=r.convert(b.depthTexture.type);let fe;b.depthTexture.format===fi?fe=i.DEPTH_COMPONENT24:b.depthTexture.format===rs&&(fe=i.DEPTH24_STENCIL8);for(let Ee=0;Ee<6;Ee++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Ee,0,fe,b.width,b.height,0,Ne,se,null)}}else $(b.depthTexture,0);const j=Q.__webglTexture,Re=I(b),ue=X?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Me=b.depthTexture.format===rs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(b.depthTexture.format===fi)Ut(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Me,ue,j,0,Re):i.framebufferTexture2D(i.FRAMEBUFFER,Me,ue,j,0);else if(b.depthTexture.format===rs)Ut(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Me,ue,j,0,Re):i.framebufferTexture2D(i.FRAMEBUFFER,Me,ue,j,0);else throw new Error("Unknown depthTexture format")}function nt(A){const b=n.get(A),L=A.isWebGLCubeRenderTarget===!0;if(b.__boundDepthTexture!==A.depthTexture){const X=A.depthTexture;if(b.__depthDisposeCallback&&b.__depthDisposeCallback(),X){const Q=()=>{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,X.removeEventListener("dispose",Q)};X.addEventListener("dispose",Q),b.__depthDisposeCallback=Q}b.__boundDepthTexture=X}if(A.depthTexture&&!b.__autoAllocateDepthBuffer)if(L)for(let X=0;X<6;X++)Ce(b.__webglFramebuffer[X],A,X);else{const X=A.texture.mipmaps;X&&X.length>0?Ce(b.__webglFramebuffer[0],A,0):Ce(b.__webglFramebuffer,A,0)}else if(L){b.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[X]),b.__webglDepthbuffer[X]===void 0)b.__webglDepthbuffer[X]=i.createRenderbuffer(),Ge(b.__webglDepthbuffer[X],A,!1);else{const Q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer[X];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,Q,i.RENDERBUFFER,j)}}else{const X=A.texture.mipmaps;if(X&&X.length>0?t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=i.createRenderbuffer(),Ge(b.__webglDepthbuffer,A,!1);else{const Q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,Q,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function Xt(A,b,L){const X=n.get(A);b!==void 0&&xe(X.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&nt(A)}function et(A){const b=A.texture,L=n.get(A),X=n.get(b);A.addEventListener("dispose",w);const Q=A.textures,j=A.isWebGLCubeRenderTarget===!0,Re=Q.length>1;if(Re||(X.__webglTexture===void 0&&(X.__webglTexture=i.createTexture()),X.__version=b.version,o.memory.textures++),j){L.__webglFramebuffer=[];for(let ue=0;ue<6;ue++)if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer[ue]=[];for(let Me=0;Me<b.mipmaps.length;Me++)L.__webglFramebuffer[ue][Me]=i.createFramebuffer()}else L.__webglFramebuffer[ue]=i.createFramebuffer()}else{if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer=[];for(let ue=0;ue<b.mipmaps.length;ue++)L.__webglFramebuffer[ue]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(Re)for(let ue=0,Me=Q.length;ue<Me;ue++){const Ne=n.get(Q[ue]);Ne.__webglTexture===void 0&&(Ne.__webglTexture=i.createTexture(),o.memory.textures++)}if(A.samples>0&&Ut(A)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let ue=0;ue<Q.length;ue++){const Me=Q[ue];L.__webglColorRenderbuffer[ue]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[ue]);const Ne=r.convert(Me.format,Me.colorSpace),se=r.convert(Me.type),fe=C(Me.internalFormat,Ne,se,Me.colorSpace,A.isXRRenderTarget===!0),Ee=I(A);i.renderbufferStorageMultisample(i.RENDERBUFFER,Ee,fe,A.width,A.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+ue,i.RENDERBUFFER,L.__webglColorRenderbuffer[ue])}i.bindRenderbuffer(i.RENDERBUFFER,null),A.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),Ge(L.__webglDepthRenderbuffer,A,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,X.__webglTexture),Be(i.TEXTURE_CUBE_MAP,b);for(let ue=0;ue<6;ue++)if(b.mipmaps&&b.mipmaps.length>0)for(let Me=0;Me<b.mipmaps.length;Me++)xe(L.__webglFramebuffer[ue][Me],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ue,Me);else xe(L.__webglFramebuffer[ue],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0);m(b)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Re){for(let ue=0,Me=Q.length;ue<Me;ue++){const Ne=Q[ue],se=n.get(Ne);let fe=i.TEXTURE_2D;(A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(fe=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(fe,se.__webglTexture),Be(fe,Ne),xe(L.__webglFramebuffer,A,Ne,i.COLOR_ATTACHMENT0+ue,fe,0),m(Ne)&&p(fe)}t.unbindTexture()}else{let ue=i.TEXTURE_2D;if((A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(ue=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ue,X.__webglTexture),Be(ue,b),b.mipmaps&&b.mipmaps.length>0)for(let Me=0;Me<b.mipmaps.length;Me++)xe(L.__webglFramebuffer[Me],A,b,i.COLOR_ATTACHMENT0,ue,Me);else xe(L.__webglFramebuffer,A,b,i.COLOR_ATTACHMENT0,ue,0);m(b)&&p(ue),t.unbindTexture()}A.depthBuffer&&nt(A)}function ct(A){const b=A.textures;for(let L=0,X=b.length;L<X;L++){const Q=b[L];if(m(Q)){const j=T(A),Re=n.get(Q).__webglTexture;t.bindTexture(j,Re),p(j),t.unbindTexture()}}}const gt=[],We=[];function Ot(A){if(A.samples>0){if(Ut(A)===!1){const b=A.textures,L=A.width,X=A.height;let Q=i.COLOR_BUFFER_BIT;const j=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Re=n.get(A),ue=b.length>1;if(ue)for(let Ne=0;Ne<b.length;Ne++)t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Re.__webglMultisampledFramebuffer);const Me=A.texture.mipmaps;Me&&Me.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglFramebuffer);for(let Ne=0;Ne<b.length;Ne++){if(A.resolveDepthBuffer&&(A.depthBuffer&&(Q|=i.DEPTH_BUFFER_BIT),A.stencilBuffer&&A.resolveStencilBuffer&&(Q|=i.STENCIL_BUFFER_BIT)),ue){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Re.__webglColorRenderbuffer[Ne]);const se=n.get(b[Ne]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,se,0)}i.blitFramebuffer(0,0,L,X,0,0,L,X,Q,i.NEAREST),c===!0&&(gt.length=0,We.length=0,gt.push(i.COLOR_ATTACHMENT0+Ne),A.depthBuffer&&A.resolveDepthBuffer===!1&&(gt.push(j),We.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,We)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,gt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),ue)for(let Ne=0;Ne<b.length;Ne++){t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.RENDERBUFFER,Re.__webglColorRenderbuffer[Ne]);const se=n.get(b[Ne]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Re.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ne,i.TEXTURE_2D,se,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Re.__webglMultisampledFramebuffer)}else if(A.depthBuffer&&A.resolveDepthBuffer===!1&&c){const b=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[b])}}}function I(A){return Math.min(s.maxSamples,A.samples)}function Ut(A){const b=n.get(A);return A.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function at(A){const b=o.render.frame;d.get(A)!==b&&(d.set(A,b),A.update())}function bt(A,b){const L=A.colorSpace,X=A.format,Q=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||L!==Ps&&L!==Ii&&(Ze.getTransfer(L)===ot?(X!==In||Q!==Tn)&&Oe("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):tt("WebGLTextures: Unsupported texture color space:",L)),b}function we(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=U,this.resetTextureUnits=O,this.setTexture2D=$,this.setTexture2DArray=G,this.setTexture3D=W,this.setTextureCube=ee,this.rebindTextures=Xt,this.setupRenderTarget=et,this.updateRenderTargetMipmap=ct,this.updateMultisampleRenderTarget=Ot,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=Ut,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function By(i,e){function t(n,s=Ii){let r;const o=Ze.getTransfer(s);if(n===Tn)return i.UNSIGNED_BYTE;if(n===Jo)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Zo)return i.UNSIGNED_SHORT_5_5_5_1;if(n===_u)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===bu)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===gu)return i.BYTE;if(n===vu)return i.SHORT;if(n===xr)return i.UNSIGNED_SHORT;if(n===Yo)return i.INT;if(n===Xn)return i.UNSIGNED_INT;if(n===$n)return i.FLOAT;if(n===hi)return i.HALF_FLOAT;if(n===yu)return i.ALPHA;if(n===Su)return i.RGB;if(n===In)return i.RGBA;if(n===fi)return i.DEPTH_COMPONENT;if(n===rs)return i.DEPTH_STENCIL;if(n===xu)return i.RED;if(n===Qo)return i.RED_INTEGER;if(n===Rs)return i.RG;if(n===ec)return i.RG_INTEGER;if(n===tc)return i.RGBA_INTEGER;if(n===la||n===da||n===ua||n===ha)if(o===ot)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===la)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===da)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===ua)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===ha)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===la)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===da)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===ua)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===ha)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===nc||n===ic||n===sc||n===rc)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===nc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ic)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===sc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===rc)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ac||n===oc||n===cc||n===lc||n===dc||n===uc||n===hc)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===ac||n===oc)return o===ot?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===cc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===lc)return r.COMPRESSED_R11_EAC;if(n===dc)return r.COMPRESSED_SIGNED_R11_EAC;if(n===uc)return r.COMPRESSED_RG11_EAC;if(n===hc)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===fc||n===pc||n===mc||n===gc||n===vc||n===_c||n===bc||n===yc||n===Sc||n===xc||n===Tc||n===Ec||n===Cc||n===Mc)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===fc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===pc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===mc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===gc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===vc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===_c)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===bc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===yc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Sc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===xc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Tc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ec)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Cc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Mc)return o===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===wc||n===Ac||n===Rc)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===wc)return o===ot?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ac)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Rc)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Pc||n===kc||n===Ic||n===Dc)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===Pc)return r.COMPRESSED_RED_RGTC1_EXT;if(n===kc)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Ic)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Dc)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Tr?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const Vy=`
4034
4034
  void main() {
4035
4035
 
4036
4036
  gl_Position = vec4( position, 1.0 );
@@ -4054,7 +4054,7 @@ void main() {
4054
4054
 
4055
4055
  }
4056
4056
 
4057
- }`;class Gy{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new nh(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Mn({vertexShader:Vy,fragmentShader:zy,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Fn(new Oa(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Hy extends Ds{constructor(e,t){super();const n=this;let s=null,r=1,o=null,a="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new Gy,p={},T=t.getContextAttributes();let C=null,_=null;const S=[],E=[],w=new st;let k=null;const y=new wn;y.viewport=new Pt;const x=new wn;x.viewport=new Pt;const R=[y,x],O=new Iv;let U=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getTargetRaySpace()},this.getControllerGrip=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getGripSpace()},this.getHand=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getHandSpace()};function $(K){const ne=E.indexOf(K.inputSource);if(ne===-1)return;const xe=S[ne];xe!==void 0&&(xe.update(K.inputSource,K.frame,l||o),xe.dispatchEvent({type:K.type,data:K.inputSource}))}function G(){s.removeEventListener("select",$),s.removeEventListener("selectstart",$),s.removeEventListener("selectend",$),s.removeEventListener("squeeze",$),s.removeEventListener("squeezestart",$),s.removeEventListener("squeezeend",$),s.removeEventListener("end",G),s.removeEventListener("inputsourceschange",W);for(let K=0;K<S.length;K++){const ne=E[K];ne!==null&&(E[K]=null,S[K].disconnect(ne))}U=null,q=null,m.reset();for(const K in p)delete p[K];e.setRenderTarget(C),f=null,h=null,u=null,s=null,_=null,ft.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(w.width,w.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(K){r=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(K){a=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(K){l=K},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(K){if(s=K,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",$),s.addEventListener("selectstart",$),s.addEventListener("selectend",$),s.addEventListener("squeeze",$),s.addEventListener("squeezestart",$),s.addEventListener("squeezeend",$),s.addEventListener("end",G),s.addEventListener("inputsourceschange",W),T.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(w),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let xe=null,Ge=null,Ce=null;T.depth&&(Ce=T.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,xe=T.stencil?rs:fi,Ge=T.stencil?Tr:Xn);const nt={colorFormat:t.RGBA8,depthFormat:Ce,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(nt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new Yn(h.textureWidth,h.textureHeight,{format:In,type:Tn,depthTexture:new Lr(h.textureWidth,h.textureHeight,Ge,void 0,void 0,void 0,void 0,void 0,void 0,xe),stencilBuffer:T.stencil,colorSpace:e.outputColorSpace,samples:T.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const xe={antialias:T.antialias,alpha:!0,depth:T.depth,stencil:T.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,xe),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new Yn(f.framebufferWidth,f.framebufferHeight,{format:In,type:Tn,colorSpace:e.outputColorSpace,stencilBuffer:T.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await s.requestReferenceSpace(a),ft.setContext(s),ft.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(K){for(let ne=0;ne<K.removed.length;ne++){const xe=K.removed[ne],Ge=E.indexOf(xe);Ge>=0&&(E[Ge]=null,S[Ge].disconnect(xe))}for(let ne=0;ne<K.added.length;ne++){const xe=K.added[ne];let Ge=E.indexOf(xe);if(Ge===-1){for(let nt=0;nt<S.length;nt++)if(nt>=E.length){E.push(xe),Ge=nt;break}else if(E[nt]===null){E[nt]=xe,Ge=nt;break}if(Ge===-1)break}const Ce=S[Ge];Ce&&Ce.connect(xe)}}const ee=new V,ge=new V;function le(K,ne,xe){ee.setFromMatrixPosition(ne.matrixWorld),ge.setFromMatrixPosition(xe.matrixWorld);const Ge=ee.distanceTo(ge),Ce=ne.projectionMatrix.elements,nt=xe.projectionMatrix.elements,Xt=Ce[14]/(Ce[10]-1),et=Ce[14]/(Ce[10]+1),lt=(Ce[9]+1)/Ce[5],vt=(Ce[9]-1)/Ce[5],We=(Ce[8]-1)/Ce[0],Ut=(nt[8]+1)/nt[0],I=Xt*We,Ft=Xt*Ut,at=Ge/(-We+Ut),yt=at*-We;if(ne.matrixWorld.decompose(K.position,K.quaternion,K.scale),K.translateX(yt),K.translateZ(at),K.matrixWorld.compose(K.position,K.quaternion,K.scale),K.matrixWorldInverse.copy(K.matrixWorld).invert(),Ce[10]===-1)K.projectionMatrix.copy(ne.projectionMatrix),K.projectionMatrixInverse.copy(ne.projectionMatrixInverse);else{const we=Xt+at,A=et+at,b=I-yt,L=Ft+(Ge-yt),X=lt*et/A*we,Q=vt*et/A*we;K.projectionMatrix.makePerspective(b,L,X,Q,we,A),K.projectionMatrixInverse.copy(K.projectionMatrix).invert()}}function _e(K,ne){ne===null?K.matrixWorld.copy(K.matrix):K.matrixWorld.multiplyMatrices(ne.matrixWorld,K.matrix),K.matrixWorldInverse.copy(K.matrixWorld).invert()}this.updateCamera=function(K){if(s===null)return;let ne=K.near,xe=K.far;m.texture!==null&&(m.depthNear>0&&(ne=m.depthNear),m.depthFar>0&&(xe=m.depthFar)),O.near=x.near=y.near=ne,O.far=x.far=y.far=xe,(U!==O.near||q!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),U=O.near,q=O.far),O.layers.mask=K.layers.mask|6,y.layers.mask=O.layers.mask&3,x.layers.mask=O.layers.mask&5;const Ge=K.parent,Ce=O.cameras;_e(O,Ge);for(let nt=0;nt<Ce.length;nt++)_e(Ce[nt],Ge);Ce.length===2?le(O,y,x):O.projectionMatrix.copy(y.projectionMatrix),Be(K,O,Ge)};function Be(K,ne,xe){xe===null?K.matrix.copy(ne.matrixWorld):(K.matrix.copy(xe.matrixWorld),K.matrix.invert(),K.matrix.multiply(ne.matrixWorld)),K.matrix.decompose(K.position,K.quaternion,K.scale),K.updateMatrixWorld(!0),K.projectionMatrix.copy(ne.projectionMatrix),K.projectionMatrixInverse.copy(ne.projectionMatrixInverse),K.isPerspectiveCamera&&(K.fov=Uc*2*Math.atan(1/K.projectionMatrix.elements[5]),K.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(K){c=K,h!==null&&(h.fixedFoveation=K),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=K)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(K){return p[K]};let Fe=null;function Tt(K,ne){if(d=ne.getViewerPose(l||o),g=ne,d!==null){const xe=d.views;f!==null&&(e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_));let Ge=!1;xe.length!==O.cameras.length&&(O.cameras.length=0,Ge=!0);for(let et=0;et<xe.length;et++){const lt=xe[et];let vt=null;if(f!==null)vt=f.getViewport(lt);else{const Ut=u.getViewSubImage(h,lt);vt=Ut.viewport,et===0&&(e.setRenderTargetTextures(_,Ut.colorTexture,Ut.depthStencilTexture),e.setRenderTarget(_))}let We=R[et];We===void 0&&(We=new wn,We.layers.enable(et),We.viewport=new Pt,R[et]=We),We.matrix.fromArray(lt.transform.matrix),We.matrix.decompose(We.position,We.quaternion,We.scale),We.projectionMatrix.fromArray(lt.projectionMatrix),We.projectionMatrixInverse.copy(We.projectionMatrix).invert(),We.viewport.set(vt.x,vt.y,vt.width,vt.height),et===0&&(O.matrix.copy(We.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),Ge===!0&&O.cameras.push(We)}const Ce=s.enabledFeatures;if(Ce&&Ce.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const et=u.getDepthInformation(xe[0]);et&&et.isValid&&et.texture&&m.init(et,s.renderState)}if(Ce&&Ce.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let et=0;et<xe.length;et++){const lt=xe[et].camera;if(lt){let vt=p[lt];vt||(vt=new nh,p[lt]=vt);const We=u.getCameraImage(lt);vt.sourceTexture=We}}}}for(let xe=0;xe<S.length;xe++){const Ge=E[xe],Ce=S[xe];Ge!==null&&Ce!==void 0&&Ce.update(Ge,ne,l||o)}Fe&&Fe(K,ne),ne.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ne}),g=null}const ft=new rh;ft.setAnimationLoop(Tt),this.setAnimationLoop=function(K){Fe=K},this.dispose=function(){}}}const fs=new vi,Wy=new Dt;function qy(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,Ku(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,T,C,_){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,_)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(o(m,p),p.isLineDashedMaterial&&a(m,p)):p.isPointsMaterial?c(m,p,T,C):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===en&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===en&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const T=e.get(p),C=T.envMap,_=T.envMapRotation;C&&(m.envMap.value=C,fs.copy(_),fs.x*=-1,fs.y*=-1,fs.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(fs.y*=-1,fs.z*=-1),m.envMapRotation.value.setFromMatrix4(Wy.makeRotationFromEuler(fs)),m.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function o(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function a(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,T,C){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*T,m.scale.value=C*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,T){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===en&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=T.texture,m.transmissionSamplerSize.value.set(T.width,T.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const T=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(T.matrixWorld),m.nearDistance.value=T.shadow.camera.near,m.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function jy(i,e,t,n){let s={},r={},o=[];const a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(T,C){const _=C.program;n.uniformBlockBinding(T,_)}function l(T,C){let _=s[T.id];_===void 0&&(g(T),_=d(T),s[T.id]=_,T.addEventListener("dispose",m));const S=C.program;n.updateUBOMapping(T,S);const E=e.render.frame;r[T.id]!==E&&(h(T),r[T.id]=E)}function d(T){const C=u();T.__bindingPointIndex=C;const _=i.createBuffer(),S=T.__size,E=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,_),i.bufferData(i.UNIFORM_BUFFER,S,E),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,C,_),_}function u(){for(let T=0;T<a;T++)if(o.indexOf(T)===-1)return o.push(T),T;return tt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(T){const C=s[T.id],_=T.uniforms,S=T.__cache;i.bindBuffer(i.UNIFORM_BUFFER,C);for(let E=0,w=_.length;E<w;E++){const k=Array.isArray(_[E])?_[E]:[_[E]];for(let y=0,x=k.length;y<x;y++){const R=k[y];if(f(R,E,y,S)===!0){const O=R.__offset,U=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let $=0;$<U.length;$++){const G=U[$],W=v(G);typeof G=="number"||typeof G=="boolean"?(R.__data[0]=G,i.bufferSubData(i.UNIFORM_BUFFER,O+q,R.__data)):G.isMatrix3?(R.__data[0]=G.elements[0],R.__data[1]=G.elements[1],R.__data[2]=G.elements[2],R.__data[3]=0,R.__data[4]=G.elements[3],R.__data[5]=G.elements[4],R.__data[6]=G.elements[5],R.__data[7]=0,R.__data[8]=G.elements[6],R.__data[9]=G.elements[7],R.__data[10]=G.elements[8],R.__data[11]=0):(G.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(T,C,_,S){const E=T.value,w=C+"_"+_;if(S[w]===void 0)return typeof E=="number"||typeof E=="boolean"?S[w]=E:S[w]=E.clone(),!0;{const k=S[w];if(typeof E=="number"||typeof E=="boolean"){if(k!==E)return S[w]=E,!0}else if(k.equals(E)===!1)return k.copy(E),!0}return!1}function g(T){const C=T.uniforms;let _=0;const S=16;for(let w=0,k=C.length;w<k;w++){const y=Array.isArray(C[w])?C[w]:[C[w]];for(let x=0,R=y.length;x<R;x++){const O=y[x],U=Array.isArray(O.value)?O.value:[O.value];for(let q=0,$=U.length;q<$;q++){const G=U[q],W=v(G),ee=_%S,ge=ee%W.boundary,le=ee+ge;_+=ge,le!==0&&S-le<W.storage&&(_+=S-le),O.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=_,_+=W.storage}}}const E=_%S;return E>0&&(_+=S-E),T.__size=_,T.__cache={},this}function v(T){const C={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(C.boundary=4,C.storage=4):T.isVector2?(C.boundary=8,C.storage=8):T.isVector3||T.isColor?(C.boundary=16,C.storage=12):T.isVector4?(C.boundary=16,C.storage=16):T.isMatrix3?(C.boundary=48,C.storage=48):T.isMatrix4?(C.boundary=64,C.storage=64):T.isTexture?Oe("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Oe("WebGLRenderer: Unsupported uniform value type.",T),C}function m(T){const C=T.target;C.removeEventListener("dispose",m);const _=o.indexOf(C.__bindingPointIndex);o.splice(_,1),i.deleteBuffer(s[C.id]),delete s[C.id],delete r[C.id]}function p(){for(const T in s)i.deleteBuffer(s[T]);o=[],s={},r={}}return{bind:c,update:l,dispose:p}}const Xy=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Qn=null;function $y(){return Qn===null&&(Qn=new Ev(Xy,16,16,Ps,hi),Qn.name="DFG_LUT",Qn.minFilter=Jt,Qn.magFilter=Jt,Qn.wrapS=ui,Qn.wrapT=ui,Qn.generateMipmaps=!1,Qn.needsUpdate=!0),Qn}class Ky{constructor(e={}){const{canvas:t=Yg(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=Tn}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;const v=f,m=new Set([tc,ec,Qo]),p=new Set([Tn,Xn,xr,Tr,Jo,Zo]),T=new Uint32Array(4),C=new Int32Array(4);let _=null,S=null;const E=[],w=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=jn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const y=this;let x=!1;this._outputColorSpace=En;let R=0,O=0,U=null,q=-1,$=null;const G=new Pt,W=new Pt;let ee=null;const ge=new Je(0);let le=0,_e=t.width,Be=t.height,Fe=1,Tt=null,ft=null;const K=new Pt(0,0,_e,Be),ne=new Pt(0,0,_e,Be);let xe=!1;const Ge=new th;let Ce=!1,nt=!1;const Xt=new Dt,et=new V,lt=new Pt,vt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let We=!1;function Ut(){return U===null?Fe:1}let I=n;function Ft(M,N){return t.getContext(M,N)}try{const M={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Lo}`),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",dt,!1),I===null){const N="webgl2";if(I=Ft(N,M),I===null)throw Ft(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(M){throw tt("WebGLRenderer: "+M.message),M}let at,yt,we,A,b,L,X,Q,j,Re,ue,Me,Ne,se,fe,Ee,Ae,he,qe,D,be,ae,ye,ie;function Z(){at=new $_(I),at.init(),ae=new By(I,at),yt=new B_(I,at,e,ae),we=new Uy(I,at),yt.reversedDepthBuffer&&h&&we.buffers.depth.setReversed(!0),A=new J_(I),b=new xy,L=new Fy(I,at,we,b,yt,ae,A),X=new z_(y),Q=new X_(y),j=new Nv(I),ye=new U_(I,j),Re=new K_(I,j,A,ye),ue=new Q_(I,Re,j,A),qe=new Z_(I,yt,L),Ee=new V_(b),Me=new Sy(y,X,Q,at,yt,ye,Ee),Ne=new qy(y,b),se=new Ey,fe=new Py(at),he=new O_(y,X,Q,we,ue,g,c),Ae=new Ny(y,ue,yt),ie=new jy(I,A,yt,we),D=new F_(I,at,A),be=new Y_(I,at,A),A.programs=Me.programs,y.capabilities=yt,y.extensions=at,y.properties=b,y.renderLists=se,y.shadowMap=Ae,y.state=we,y.info=A}Z(),v!==Tn&&(k=new tb(v,t.width,t.height,s,r));const de=new Hy(y,I);this.xr=de,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const M=at.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){const M=at.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return Fe},this.setPixelRatio=function(M){M!==void 0&&(Fe=M,this.setSize(_e,Be,!1))},this.getSize=function(M){return M.set(_e,Be)},this.setSize=function(M,N,H=!0){if(de.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=M,Be=N,t.width=Math.floor(M*Fe),t.height=Math.floor(N*Fe),H===!0&&(t.style.width=M+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,M,N)},this.getDrawingBufferSize=function(M){return M.set(_e*Fe,Be*Fe).floor()},this.setDrawingBufferSize=function(M,N,H){_e=M,Be=N,Fe=H,t.width=Math.floor(M*H),t.height=Math.floor(N*H),this.setViewport(0,0,M,N)},this.setEffects=function(M){if(v===Tn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let N=0;N<M.length;N++)if(M[N].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(G)},this.getViewport=function(M){return M.copy(K)},this.setViewport=function(M,N,H,z){M.isVector4?K.set(M.x,M.y,M.z,M.w):K.set(M,N,H,z),we.viewport(G.copy(K).multiplyScalar(Fe).round())},this.getScissor=function(M){return M.copy(ne)},this.setScissor=function(M,N,H,z){M.isVector4?ne.set(M.x,M.y,M.z,M.w):ne.set(M,N,H,z),we.scissor(W.copy(ne).multiplyScalar(Fe).round())},this.getScissorTest=function(){return xe},this.setScissorTest=function(M){we.setScissorTest(xe=M)},this.setOpaqueSort=function(M){Tt=M},this.setTransparentSort=function(M){ft=M},this.getClearColor=function(M){return M.copy(he.getClearColor())},this.setClearColor=function(){he.setClearColor(...arguments)},this.getClearAlpha=function(){return he.getClearAlpha()},this.setClearAlpha=function(){he.setClearAlpha(...arguments)},this.clear=function(M=!0,N=!0,H=!0){let z=0;if(M){let F=!1;if(U!==null){const pe=U.texture.format;F=m.has(pe)}if(F){const pe=U.texture.type,Se=p.has(pe),ve=he.getClearColor(),Te=he.getClearAlpha(),Pe=ve.r,Le=ve.g,ke=ve.b;Se?(T[0]=Pe,T[1]=Le,T[2]=ke,T[3]=Te,I.clearBufferuiv(I.COLOR,0,T)):(C[0]=Pe,C[1]=Le,C[2]=ke,C[3]=Te,I.clearBufferiv(I.COLOR,0,C))}else z|=I.COLOR_BUFFER_BIT}N&&(z|=I.DEPTH_BUFFER_BIT),H&&(z|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(z)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",St,!1),t.removeEventListener("webglcontextcreationerror",dt,!1),he.dispose(),se.dispose(),fe.dispose(),b.dispose(),X.dispose(),Q.dispose(),ue.dispose(),ye.dispose(),ie.dispose(),Me.dispose(),de.dispose(),de.removeEventListener("sessionstart",Bm),de.removeEventListener("sessionend",Vm),xs.stop()};function Ue(M){M.preventDefault(),Au("WebGLRenderer: Context Lost."),x=!0}function St(){Au("WebGLRenderer: Context Restored."),x=!1;const M=A.autoReset,N=Ae.enabled,H=Ae.autoUpdate,z=Ae.needsUpdate,F=Ae.type;Z(),A.autoReset=M,Ae.enabled=N,Ae.autoUpdate=H,Ae.needsUpdate=z,Ae.type=F}function dt(M){tt("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function oi(M){const N=M.target;N.removeEventListener("dispose",oi),Ai(N)}function Ai(M){PC(M),b.remove(M)}function PC(M){const N=b.get(M).programs;N!==void 0&&(N.forEach(function(H){Me.releaseProgram(H)}),M.isShaderMaterial&&Me.releaseShaderCache(M))}this.renderBufferDirect=function(M,N,H,z,F,pe){N===null&&(N=vt);const Se=F.isMesh&&F.matrixWorld.determinant()<0,ve=IC(M,N,H,z,F);we.setMaterial(z,Se);let Te=H.index,Pe=1;if(z.wireframe===!0){if(Te=Re.getWireframeAttribute(H),Te===void 0)return;Pe=2}const Le=H.drawRange,ke=H.attributes.position;let Xe=Le.start*Pe,pt=(Le.start+Le.count)*Pe;pe!==null&&(Xe=Math.max(Xe,pe.start*Pe),pt=Math.min(pt,(pe.start+pe.count)*Pe)),Te!==null?(Xe=Math.max(Xe,0),pt=Math.min(pt,Te.count)):ke!=null&&(Xe=Math.max(Xe,0),pt=Math.min(pt,ke.count));const At=pt-Xe;if(At<0||At===1/0)return;ye.setup(F,z,ve,H,Te);let Rt,_t=D;if(Te!==null&&(Rt=j.get(Te),_t=be,_t.setIndex(Rt)),F.isMesh)z.wireframe===!0?(we.setLineWidth(z.wireframeLinewidth*Ut()),_t.setMode(I.LINES)):_t.setMode(I.TRIANGLES);else if(F.isLine){let Ie=z.linewidth;Ie===void 0&&(Ie=1),we.setLineWidth(Ie*Ut()),F.isLineSegments?_t.setMode(I.LINES):F.isLineLoop?_t.setMode(I.LINE_LOOP):_t.setMode(I.LINE_STRIP)}else F.isPoints?_t.setMode(I.POINTS):F.isSprite&&_t.setMode(I.TRIANGLES);if(F.isBatchedMesh)if(F._multiDrawInstances!==null)Er("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_t.renderMultiDrawInstances(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount,F._multiDrawInstances);else if(at.get("WEBGL_multi_draw"))_t.renderMultiDraw(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount);else{const Ie=F._multiDrawStarts,ut=F._multiDrawCounts,it=F._multiDrawCount,Sn=Te?j.get(Te).bytesPerElement:1,hr=b.get(z).currentProgram.getUniforms();for(let xn=0;xn<it;xn++)hr.setValue(I,"_gl_DrawID",xn),_t.render(Ie[xn]/Sn,ut[xn])}else if(F.isInstancedMesh)_t.renderInstances(Xe,At,F.count);else if(H.isInstancedBufferGeometry){const Ie=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,ut=Math.min(H.instanceCount,Ie);_t.renderInstances(Xe,At,ut)}else _t.render(Xe,At)};function Fm(M,N,H){M.transparent===!0&&M.side===li&&M.forceSinglePass===!1?(M.side=en,M.needsUpdate=!0,Co(M,N,H),M.side=ci,M.needsUpdate=!0,Co(M,N,H),M.side=li):Co(M,N,H)}this.compile=function(M,N,H=null){H===null&&(H=M),S=fe.get(H),S.init(N),w.push(S),H.traverseVisible(function(F){F.isLight&&F.layers.test(N.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),M!==H&&M.traverseVisible(function(F){F.isLight&&F.layers.test(N.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),S.setupLights();const z=new Set;return M.traverse(function(F){if(!(F.isMesh||F.isPoints||F.isLine||F.isSprite))return;const pe=F.material;if(pe)if(Array.isArray(pe))for(let Se=0;Se<pe.length;Se++){const ve=pe[Se];Fm(ve,H,F),z.add(ve)}else Fm(pe,H,F),z.add(pe)}),S=w.pop(),z},this.compileAsync=function(M,N,H=null){const z=this.compile(M,N,H);return new Promise(F=>{function pe(){if(z.forEach(function(Se){b.get(Se).currentProgram.isReady()&&z.delete(Se)}),z.size===0){F(M);return}setTimeout(pe,10)}at.get("KHR_parallel_shader_compile")!==null?pe():setTimeout(pe,10)})};let Fd=null;function kC(M){Fd&&Fd(M)}function Bm(){xs.stop()}function Vm(){xs.start()}const xs=new rh;xs.setAnimationLoop(kC),typeof self<"u"&&xs.setContext(self),this.setAnimationLoop=function(M){Fd=M,de.setAnimationLoop(M),M===null?xs.stop():xs.start()},de.addEventListener("sessionstart",Bm),de.addEventListener("sessionend",Vm),this.render=function(M,N){if(N!==void 0&&N.isCamera!==!0){tt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(x===!0)return;const H=de.enabled===!0&&de.isPresenting===!0,z=k!==null&&(U===null||H)&&k.begin(y,U);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),de.enabled===!0&&de.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(de.cameraAutoUpdate===!0&&de.updateCamera(N),N=de.getCamera()),M.isScene===!0&&M.onBeforeRender(y,M,N,U),S=fe.get(M,w.length),S.init(N),w.push(S),Xt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),Ge.setFromProjectionMatrix(Xt,Kn,N.reversedDepth),nt=this.localClippingEnabled,Ce=Ee.init(this.clippingPlanes,nt),_=se.get(M,E.length),_.init(),E.push(_),de.enabled===!0&&de.isPresenting===!0){const Se=y.xr.getDepthSensingMesh();Se!==null&&Bd(Se,N,-1/0,y.sortObjects)}Bd(M,N,0,y.sortObjects),_.finish(),y.sortObjects===!0&&_.sort(Tt,ft),We=de.enabled===!1||de.isPresenting===!1||de.hasDepthSensing()===!1,We&&he.addToRenderList(_,M),this.info.render.frame++,Ce===!0&&Ee.beginShadows();const F=S.state.shadowsArray;if(Ae.render(F,M,N),Ce===!0&&Ee.endShadows(),this.info.autoReset===!0&&this.info.reset(),(z&&k.hasRenderPass())===!1){const Se=_.opaque,ve=_.transmissive;if(S.setupLights(),N.isArrayCamera){const Te=N.cameras;if(ve.length>0)for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe];Gm(Se,ve,M,ke)}We&&he.render(M);for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe];zm(_,M,ke,ke.viewport)}}else ve.length>0&&Gm(Se,ve,M,N),We&&he.render(M),zm(_,M,N)}U!==null&&O===0&&(L.updateMultisampleRenderTarget(U),L.updateRenderTargetMipmap(U)),z&&k.end(y),M.isScene===!0&&M.onAfterRender(y,M,N),ye.resetDefaultState(),q=-1,$=null,w.pop(),w.length>0?(S=w[w.length-1],Ce===!0&&Ee.setGlobalState(y.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?_=E[E.length-1]:_=null};function Bd(M,N,H,z){if(M.visible===!1)return;if(M.layers.test(N.layers)){if(M.isGroup)H=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(N);else if(M.isLight)S.pushLight(M),M.castShadow&&S.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||Ge.intersectsSprite(M)){z&&lt.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Xt);const Se=ue.update(M),ve=M.material;ve.visible&&_.push(M,Se,ve,H,lt.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||Ge.intersectsObject(M))){const Se=ue.update(M),ve=M.material;if(z&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),lt.copy(M.boundingSphere.center)):(Se.boundingSphere===null&&Se.computeBoundingSphere(),lt.copy(Se.boundingSphere.center)),lt.applyMatrix4(M.matrixWorld).applyMatrix4(Xt)),Array.isArray(ve)){const Te=Se.groups;for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe],Xe=ve[ke.materialIndex];Xe&&Xe.visible&&_.push(M,Se,Xe,H,lt.z,ke)}}else ve.visible&&_.push(M,Se,ve,H,lt.z,null)}}const pe=M.children;for(let Se=0,ve=pe.length;Se<ve;Se++)Bd(pe[Se],N,H,z)}function zm(M,N,H,z){const{opaque:F,transmissive:pe,transparent:Se}=M;S.setupLightsView(H),Ce===!0&&Ee.setGlobalState(y.clippingPlanes,H),z&&we.viewport(G.copy(z)),F.length>0&&Eo(F,N,H),pe.length>0&&Eo(pe,N,H),Se.length>0&&Eo(Se,N,H),we.buffers.depth.setTest(!0),we.buffers.depth.setMask(!0),we.buffers.color.setMask(!0),we.setPolygonOffset(!1)}function Gm(M,N,H,z){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[z.id]===void 0){const Xe=at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[z.id]=new Yn(1,1,{generateMipmaps:!0,type:Xe?hi:Tn,minFilter:ss,samples:yt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ze.workingColorSpace})}const pe=S.state.transmissionRenderTarget[z.id],Se=z.viewport||G;pe.setSize(Se.z*y.transmissionResolutionScale,Se.w*y.transmissionResolutionScale);const ve=y.getRenderTarget(),Te=y.getActiveCubeFace(),Pe=y.getActiveMipmapLevel();y.setRenderTarget(pe),y.getClearColor(ge),le=y.getClearAlpha(),le<1&&y.setClearColor(16777215,.5),y.clear(),We&&he.render(H);const Le=y.toneMapping;y.toneMapping=jn;const ke=z.viewport;if(z.viewport!==void 0&&(z.viewport=void 0),S.setupLightsView(z),Ce===!0&&Ee.setGlobalState(y.clippingPlanes,z),Eo(M,H,z),L.updateMultisampleRenderTarget(pe),L.updateRenderTargetMipmap(pe),at.has("WEBGL_multisampled_render_to_texture")===!1){let Xe=!1;for(let pt=0,At=N.length;pt<At;pt++){const Rt=N[pt],{object:_t,geometry:Ie,material:ut,group:it}=Rt;if(ut.side===li&&_t.layers.test(z.layers)){const Sn=ut.side;ut.side=en,ut.needsUpdate=!0,Hm(_t,H,z,Ie,ut,it),ut.side=Sn,ut.needsUpdate=!0,Xe=!0}}Xe===!0&&(L.updateMultisampleRenderTarget(pe),L.updateRenderTargetMipmap(pe))}y.setRenderTarget(ve,Te,Pe),y.setClearColor(ge,le),ke!==void 0&&(z.viewport=ke),y.toneMapping=Le}function Eo(M,N,H){const z=N.isScene===!0?N.overrideMaterial:null;for(let F=0,pe=M.length;F<pe;F++){const Se=M[F],{object:ve,geometry:Te,group:Pe}=Se;let Le=Se.material;Le.allowOverride===!0&&z!==null&&(Le=z),ve.layers.test(H.layers)&&Hm(ve,N,H,Te,Le,Pe)}}function Hm(M,N,H,z,F,pe){M.onBeforeRender(y,N,H,z,F,pe),M.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),F.onBeforeRender(y,N,H,z,M,pe),F.transparent===!0&&F.side===li&&F.forceSinglePass===!1?(F.side=en,F.needsUpdate=!0,y.renderBufferDirect(H,N,z,F,M,pe),F.side=ci,F.needsUpdate=!0,y.renderBufferDirect(H,N,z,F,M,pe),F.side=li):y.renderBufferDirect(H,N,z,F,M,pe),M.onAfterRender(y,N,H,z,F,pe)}function Co(M,N,H){N.isScene!==!0&&(N=vt);const z=b.get(M),F=S.state.lights,pe=S.state.shadowsArray,Se=F.state.version,ve=Me.getParameters(M,F.state,pe,N,H),Te=Me.getProgramCacheKey(ve);let Pe=z.programs;z.environment=M.isMeshStandardMaterial?N.environment:null,z.fog=N.fog,z.envMap=(M.isMeshStandardMaterial?Q:X).get(M.envMap||z.environment),z.envMapRotation=z.environment!==null&&M.envMap===null?N.environmentRotation:M.envMapRotation,Pe===void 0&&(M.addEventListener("dispose",oi),Pe=new Map,z.programs=Pe);let Le=Pe.get(Te);if(Le!==void 0){if(z.currentProgram===Le&&z.lightsStateVersion===Se)return qm(M,ve),Le}else ve.uniforms=Me.getUniforms(M),M.onBeforeCompile(ve,y),Le=Me.acquireProgram(ve,Te),Pe.set(Te,Le),z.uniforms=ve.uniforms;const ke=z.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&(ke.clippingPlanes=Ee.uniform),qm(M,ve),z.needsLights=LC(M),z.lightsStateVersion=Se,z.needsLights&&(ke.ambientLightColor.value=F.state.ambient,ke.lightProbe.value=F.state.probe,ke.directionalLights.value=F.state.directional,ke.directionalLightShadows.value=F.state.directionalShadow,ke.spotLights.value=F.state.spot,ke.spotLightShadows.value=F.state.spotShadow,ke.rectAreaLights.value=F.state.rectArea,ke.ltc_1.value=F.state.rectAreaLTC1,ke.ltc_2.value=F.state.rectAreaLTC2,ke.pointLights.value=F.state.point,ke.pointLightShadows.value=F.state.pointShadow,ke.hemisphereLights.value=F.state.hemi,ke.directionalShadowMap.value=F.state.directionalShadowMap,ke.directionalShadowMatrix.value=F.state.directionalShadowMatrix,ke.spotShadowMap.value=F.state.spotShadowMap,ke.spotLightMatrix.value=F.state.spotLightMatrix,ke.spotLightMap.value=F.state.spotLightMap,ke.pointShadowMap.value=F.state.pointShadowMap,ke.pointShadowMatrix.value=F.state.pointShadowMatrix),z.currentProgram=Le,z.uniformsList=null,Le}function Wm(M){if(M.uniformsList===null){const N=M.currentProgram.getUniforms();M.uniformsList=Va.seqWithValue(N.seq,M.uniforms)}return M.uniformsList}function qm(M,N){const H=b.get(M);H.outputColorSpace=N.outputColorSpace,H.batching=N.batching,H.batchingColor=N.batchingColor,H.instancing=N.instancing,H.instancingColor=N.instancingColor,H.instancingMorph=N.instancingMorph,H.skinning=N.skinning,H.morphTargets=N.morphTargets,H.morphNormals=N.morphNormals,H.morphColors=N.morphColors,H.morphTargetsCount=N.morphTargetsCount,H.numClippingPlanes=N.numClippingPlanes,H.numIntersection=N.numClipIntersection,H.vertexAlphas=N.vertexAlphas,H.vertexTangents=N.vertexTangents,H.toneMapping=N.toneMapping}function IC(M,N,H,z,F){N.isScene!==!0&&(N=vt),L.resetTextureUnits();const pe=N.fog,Se=z.isMeshStandardMaterial?N.environment:null,ve=U===null?y.outputColorSpace:U.isXRRenderTarget===!0?U.texture.colorSpace:ks,Te=(z.isMeshStandardMaterial?Q:X).get(z.envMap||Se),Pe=z.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Le=!!H.attributes.tangent&&(!!z.normalMap||z.anisotropy>0),ke=!!H.morphAttributes.position,Xe=!!H.morphAttributes.normal,pt=!!H.morphAttributes.color;let At=jn;z.toneMapped&&(U===null||U.isXRRenderTarget===!0)&&(At=y.toneMapping);const Rt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,_t=Rt!==void 0?Rt.length:0,Ie=b.get(z),ut=S.state.lights;if(Ce===!0&&(nt===!0||M!==$)){const ln=M===$&&z.id===q;Ee.setState(z,M,ln)}let it=!1;z.version===Ie.__version?(Ie.needsLights&&Ie.lightsStateVersion!==ut.state.version||Ie.outputColorSpace!==ve||F.isBatchedMesh&&Ie.batching===!1||!F.isBatchedMesh&&Ie.batching===!0||F.isBatchedMesh&&Ie.batchingColor===!0&&F.colorTexture===null||F.isBatchedMesh&&Ie.batchingColor===!1&&F.colorTexture!==null||F.isInstancedMesh&&Ie.instancing===!1||!F.isInstancedMesh&&Ie.instancing===!0||F.isSkinnedMesh&&Ie.skinning===!1||!F.isSkinnedMesh&&Ie.skinning===!0||F.isInstancedMesh&&Ie.instancingColor===!0&&F.instanceColor===null||F.isInstancedMesh&&Ie.instancingColor===!1&&F.instanceColor!==null||F.isInstancedMesh&&Ie.instancingMorph===!0&&F.morphTexture===null||F.isInstancedMesh&&Ie.instancingMorph===!1&&F.morphTexture!==null||Ie.envMap!==Te||z.fog===!0&&Ie.fog!==pe||Ie.numClippingPlanes!==void 0&&(Ie.numClippingPlanes!==Ee.numPlanes||Ie.numIntersection!==Ee.numIntersection)||Ie.vertexAlphas!==Pe||Ie.vertexTangents!==Le||Ie.morphTargets!==ke||Ie.morphNormals!==Xe||Ie.morphColors!==pt||Ie.toneMapping!==At||Ie.morphTargetsCount!==_t)&&(it=!0):(it=!0,Ie.__version=z.version);let Sn=Ie.currentProgram;it===!0&&(Sn=Co(z,N,F));let hr=!1,xn=!1,na=!1;const xt=Sn.getUniforms(),mn=Ie.uniforms;if(we.useProgram(Sn.program)&&(hr=!0,xn=!0,na=!0),z.id!==q&&(q=z.id,xn=!0),hr||$!==M){we.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),xt.setValue(I,"projectionMatrix",M.projectionMatrix),xt.setValue(I,"viewMatrix",M.matrixWorldInverse);const gn=xt.map.cameraPosition;gn!==void 0&&gn.setValue(I,et.setFromMatrixPosition(M.matrixWorld)),yt.logarithmicDepthBuffer&&xt.setValue(I,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),(z.isMeshPhongMaterial||z.isMeshToonMaterial||z.isMeshLambertMaterial||z.isMeshBasicMaterial||z.isMeshStandardMaterial||z.isShaderMaterial)&&xt.setValue(I,"isOrthographic",M.isOrthographicCamera===!0),$!==M&&($=M,xn=!0,na=!0)}if(Ie.needsLights&&(ut.state.directionalShadowMap.length>0&&xt.setValue(I,"directionalShadowMap",ut.state.directionalShadowMap,L),ut.state.spotShadowMap.length>0&&xt.setValue(I,"spotShadowMap",ut.state.spotShadowMap,L),ut.state.pointShadowMap.length>0&&xt.setValue(I,"pointShadowMap",ut.state.pointShadowMap,L)),F.isSkinnedMesh){xt.setOptional(I,F,"bindMatrix"),xt.setOptional(I,F,"bindMatrixInverse");const ln=F.skeleton;ln&&(ln.boneTexture===null&&ln.computeBoneTexture(),xt.setValue(I,"boneTexture",ln.boneTexture,L))}F.isBatchedMesh&&(xt.setOptional(I,F,"batchingTexture"),xt.setValue(I,"batchingTexture",F._matricesTexture,L),xt.setOptional(I,F,"batchingIdTexture"),xt.setValue(I,"batchingIdTexture",F._indirectTexture,L),xt.setOptional(I,F,"batchingColorTexture"),F._colorsTexture!==null&&xt.setValue(I,"batchingColorTexture",F._colorsTexture,L));const kn=H.morphAttributes;if((kn.position!==void 0||kn.normal!==void 0||kn.color!==void 0)&&qe.update(F,H,Sn),(xn||Ie.receiveShadow!==F.receiveShadow)&&(Ie.receiveShadow=F.receiveShadow,xt.setValue(I,"receiveShadow",F.receiveShadow)),z.isMeshGouraudMaterial&&z.envMap!==null&&(mn.envMap.value=Te,mn.flipEnvMap.value=Te.isCubeTexture&&Te.isRenderTargetTexture===!1?-1:1),z.isMeshStandardMaterial&&z.envMap===null&&N.environment!==null&&(mn.envMapIntensity.value=N.environmentIntensity),mn.dfgLUT!==void 0&&(mn.dfgLUT.value=$y()),xn&&(xt.setValue(I,"toneMappingExposure",y.toneMappingExposure),Ie.needsLights&&DC(mn,na),pe&&z.fog===!0&&Ne.refreshFogUniforms(mn,pe),Ne.refreshMaterialUniforms(mn,z,Fe,Be,S.state.transmissionRenderTarget[M.id]),Va.upload(I,Wm(Ie),mn,L)),z.isShaderMaterial&&z.uniformsNeedUpdate===!0&&(Va.upload(I,Wm(Ie),mn,L),z.uniformsNeedUpdate=!1),z.isSpriteMaterial&&xt.setValue(I,"center",F.center),xt.setValue(I,"modelViewMatrix",F.modelViewMatrix),xt.setValue(I,"normalMatrix",F.normalMatrix),xt.setValue(I,"modelMatrix",F.matrixWorld),z.isShaderMaterial||z.isRawShaderMaterial){const ln=z.uniformsGroups;for(let gn=0,Vd=ln.length;gn<Vd;gn++){const Ts=ln[gn];ie.update(Ts,Sn),ie.bind(Ts,Sn)}}return Sn}function DC(M,N){M.ambientLightColor.needsUpdate=N,M.lightProbe.needsUpdate=N,M.directionalLights.needsUpdate=N,M.directionalLightShadows.needsUpdate=N,M.pointLights.needsUpdate=N,M.pointLightShadows.needsUpdate=N,M.spotLights.needsUpdate=N,M.spotLightShadows.needsUpdate=N,M.rectAreaLights.needsUpdate=N,M.hemisphereLights.needsUpdate=N}function LC(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return U},this.setRenderTargetTextures=function(M,N,H){const z=b.get(M);z.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,z.__autoAllocateDepthBuffer===!1&&(z.__useRenderToTexture=!1),b.get(M.texture).__webglTexture=N,b.get(M.depthTexture).__webglTexture=z.__autoAllocateDepthBuffer?void 0:H,z.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,N){const H=b.get(M);H.__webglFramebuffer=N,H.__useDefaultFramebuffer=N===void 0};const NC=I.createFramebuffer();this.setRenderTarget=function(M,N=0,H=0){U=M,R=N,O=H;let z=null,F=!1,pe=!1;if(M){const ve=b.get(M);if(ve.__useDefaultFramebuffer!==void 0){we.bindFramebuffer(I.FRAMEBUFFER,ve.__webglFramebuffer),G.copy(M.viewport),W.copy(M.scissor),ee=M.scissorTest,we.viewport(G),we.scissor(W),we.setScissorTest(ee),q=-1;return}else if(ve.__webglFramebuffer===void 0)L.setupRenderTarget(M);else if(ve.__hasExternalTextures)L.rebindTextures(M,b.get(M.texture).__webglTexture,b.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){const Le=M.depthTexture;if(ve.__boundDepthTexture!==Le){if(Le!==null&&b.has(Le)&&(M.width!==Le.image.width||M.height!==Le.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(M)}}const Te=M.texture;(Te.isData3DTexture||Te.isDataArrayTexture||Te.isCompressedArrayTexture)&&(pe=!0);const Pe=b.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(Pe[N])?z=Pe[N][H]:z=Pe[N],F=!0):M.samples>0&&L.useMultisampledRTT(M)===!1?z=b.get(M).__webglMultisampledFramebuffer:Array.isArray(Pe)?z=Pe[H]:z=Pe,G.copy(M.viewport),W.copy(M.scissor),ee=M.scissorTest}else G.copy(K).multiplyScalar(Fe).floor(),W.copy(ne).multiplyScalar(Fe).floor(),ee=xe;if(H!==0&&(z=NC),we.bindFramebuffer(I.FRAMEBUFFER,z)&&we.drawBuffers(M,z),we.viewport(G),we.scissor(W),we.setScissorTest(ee),F){const ve=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,ve.__webglTexture,H)}else if(pe){const ve=N;for(let Te=0;Te<M.textures.length;Te++){const Pe=b.get(M.textures[Te]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Te,Pe.__webglTexture,H,ve)}}else if(M!==null&&H!==0){const ve=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ve.__webglTexture,H)}q=-1},this.readRenderTargetPixels=function(M,N,H,z,F,pe,Se,ve=0){if(!(M&&M.isWebGLRenderTarget)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Te=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Se!==void 0&&(Te=Te[Se]),Te){we.bindFramebuffer(I.FRAMEBUFFER,Te);try{const Pe=M.textures[ve],Le=Pe.format,ke=Pe.type;if(!yt.textureFormatReadable(Le)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!yt.textureTypeReadable(ke)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=M.width-z&&H>=0&&H<=M.height-F&&(M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ve),I.readPixels(N,H,z,F,ae.convert(Le),ae.convert(ke),pe))}finally{const Pe=U!==null?b.get(U).__webglFramebuffer:null;we.bindFramebuffer(I.FRAMEBUFFER,Pe)}}},this.readRenderTargetPixelsAsync=async function(M,N,H,z,F,pe,Se,ve=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Te=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Se!==void 0&&(Te=Te[Se]),Te)if(N>=0&&N<=M.width-z&&H>=0&&H<=M.height-F){we.bindFramebuffer(I.FRAMEBUFFER,Te);const Pe=M.textures[ve],Le=Pe.format,ke=Pe.type;if(!yt.textureFormatReadable(Le))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!yt.textureTypeReadable(ke))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Xe=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,Xe),I.bufferData(I.PIXEL_PACK_BUFFER,pe.byteLength,I.STREAM_READ),M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ve),I.readPixels(N,H,z,F,ae.convert(Le),ae.convert(ke),0);const pt=U!==null?b.get(U).__webglFramebuffer:null;we.bindFramebuffer(I.FRAMEBUFFER,pt);const At=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await Jg(I,At,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,Xe),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,pe),I.deleteBuffer(Xe),I.deleteSync(At),pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,N=null,H=0){const z=Math.pow(2,-H),F=Math.floor(M.image.width*z),pe=Math.floor(M.image.height*z),Se=N!==null?N.x:0,ve=N!==null?N.y:0;L.setTexture2D(M,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Se,ve,F,pe),we.unbindTexture()};const OC=I.createFramebuffer(),UC=I.createFramebuffer();this.copyTextureToTexture=function(M,N,H=null,z=null,F=0,pe=null){pe===null&&(F!==0?(Er("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pe=F,F=0):pe=0);let Se,ve,Te,Pe,Le,ke,Xe,pt,At;const Rt=M.isCompressedTexture?M.mipmaps[pe]:M.image;if(H!==null)Se=H.max.x-H.min.x,ve=H.max.y-H.min.y,Te=H.isBox3?H.max.z-H.min.z:1,Pe=H.min.x,Le=H.min.y,ke=H.isBox3?H.min.z:0;else{const kn=Math.pow(2,-F);Se=Math.floor(Rt.width*kn),ve=Math.floor(Rt.height*kn),M.isDataArrayTexture?Te=Rt.depth:M.isData3DTexture?Te=Math.floor(Rt.depth*kn):Te=1,Pe=0,Le=0,ke=0}z!==null?(Xe=z.x,pt=z.y,At=z.z):(Xe=0,pt=0,At=0);const _t=ae.convert(N.format),Ie=ae.convert(N.type);let ut;N.isData3DTexture?(L.setTexture3D(N,0),ut=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),ut=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),ut=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const it=I.getParameter(I.UNPACK_ROW_LENGTH),Sn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),hr=I.getParameter(I.UNPACK_SKIP_PIXELS),xn=I.getParameter(I.UNPACK_SKIP_ROWS),na=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Rt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Rt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Pe),I.pixelStorei(I.UNPACK_SKIP_ROWS,Le),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ke);const xt=M.isDataArrayTexture||M.isData3DTexture,mn=N.isDataArrayTexture||N.isData3DTexture;if(M.isDepthTexture){const kn=b.get(M),ln=b.get(N),gn=b.get(kn.__renderTarget),Vd=b.get(ln.__renderTarget);we.bindFramebuffer(I.READ_FRAMEBUFFER,gn.__webglFramebuffer),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,Vd.__webglFramebuffer);for(let Ts=0;Ts<Te;Ts++)xt&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(M).__webglTexture,F,ke+Ts),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(N).__webglTexture,pe,At+Ts)),I.blitFramebuffer(Pe,Le,Se,ve,Xe,pt,Se,ve,I.DEPTH_BUFFER_BIT,I.NEAREST);we.bindFramebuffer(I.READ_FRAMEBUFFER,null),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(F!==0||M.isRenderTargetTexture||b.has(M)){const kn=b.get(M),ln=b.get(N);we.bindFramebuffer(I.READ_FRAMEBUFFER,OC),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,UC);for(let gn=0;gn<Te;gn++)xt?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,kn.__webglTexture,F,ke+gn):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,kn.__webglTexture,F),mn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,ln.__webglTexture,pe,At+gn):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ln.__webglTexture,pe),F!==0?I.blitFramebuffer(Pe,Le,Se,ve,Xe,pt,Se,ve,I.COLOR_BUFFER_BIT,I.NEAREST):mn?I.copyTexSubImage3D(ut,pe,Xe,pt,At+gn,Pe,Le,Se,ve):I.copyTexSubImage2D(ut,pe,Xe,pt,Pe,Le,Se,ve);we.bindFramebuffer(I.READ_FRAMEBUFFER,null),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else mn?M.isDataTexture||M.isData3DTexture?I.texSubImage3D(ut,pe,Xe,pt,At,Se,ve,Te,_t,Ie,Rt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(ut,pe,Xe,pt,At,Se,ve,Te,_t,Rt.data):I.texSubImage3D(ut,pe,Xe,pt,At,Se,ve,Te,_t,Ie,Rt):M.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,pe,Xe,pt,Se,ve,_t,Ie,Rt.data):M.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,pe,Xe,pt,Rt.width,Rt.height,_t,Rt.data):I.texSubImage2D(I.TEXTURE_2D,pe,Xe,pt,Se,ve,_t,Ie,Rt);I.pixelStorei(I.UNPACK_ROW_LENGTH,it),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Sn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,hr),I.pixelStorei(I.UNPACK_SKIP_ROWS,xn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,na),pe===0&&N.generateMipmaps&&I.generateMipmap(ut),we.unbindTexture()},this.initRenderTarget=function(M){b.get(M).__webglFramebuffer===void 0&&L.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?L.setTextureCube(M,0):M.isData3DTexture?L.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?L.setTexture2DArray(M,0):L.setTexture2D(M,0),we.unbindTexture()},this.resetState=function(){R=0,O=0,U=null,we.reset(),ye.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Kn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Ze._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ze._getUnpackColorSpace()}}const Dh=`
4057
+ }`;class Gy{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new nh(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Mn({vertexShader:Vy,fragmentShader:zy,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Fn(new Na(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Hy extends Is{constructor(e,t){super();const n=this;let s=null,r=1,o=null,a="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new Gy,p={},T=t.getContextAttributes();let C=null,_=null;const S=[],E=[],w=new st;let k=null;const y=new wn;y.viewport=new Pt;const x=new wn;x.viewport=new Pt;const R=[y,x],O=new Iv;let U=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getTargetRaySpace()},this.getControllerGrip=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getGripSpace()},this.getHand=function(K){let ne=S[K];return ne===void 0&&(ne=new ol,S[K]=ne),ne.getHandSpace()};function $(K){const ne=E.indexOf(K.inputSource);if(ne===-1)return;const xe=S[ne];xe!==void 0&&(xe.update(K.inputSource,K.frame,l||o),xe.dispatchEvent({type:K.type,data:K.inputSource}))}function G(){s.removeEventListener("select",$),s.removeEventListener("selectstart",$),s.removeEventListener("selectend",$),s.removeEventListener("squeeze",$),s.removeEventListener("squeezestart",$),s.removeEventListener("squeezeend",$),s.removeEventListener("end",G),s.removeEventListener("inputsourceschange",W);for(let K=0;K<S.length;K++){const ne=E[K];ne!==null&&(E[K]=null,S[K].disconnect(ne))}U=null,q=null,m.reset();for(const K in p)delete p[K];e.setRenderTarget(C),f=null,h=null,u=null,s=null,_=null,ht.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(w.width,w.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(K){r=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(K){a=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(K){l=K},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(K){if(s=K,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",$),s.addEventListener("selectstart",$),s.addEventListener("selectend",$),s.addEventListener("squeeze",$),s.addEventListener("squeezestart",$),s.addEventListener("squeezeend",$),s.addEventListener("end",G),s.addEventListener("inputsourceschange",W),T.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(w),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let xe=null,Ge=null,Ce=null;T.depth&&(Ce=T.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,xe=T.stencil?rs:fi,Ge=T.stencil?Tr:Xn);const nt={colorFormat:t.RGBA8,depthFormat:Ce,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(nt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new Yn(h.textureWidth,h.textureHeight,{format:In,type:Tn,depthTexture:new Lr(h.textureWidth,h.textureHeight,Ge,void 0,void 0,void 0,void 0,void 0,void 0,xe),stencilBuffer:T.stencil,colorSpace:e.outputColorSpace,samples:T.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const xe={antialias:T.antialias,alpha:!0,depth:T.depth,stencil:T.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,xe),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new Yn(f.framebufferWidth,f.framebufferHeight,{format:In,type:Tn,colorSpace:e.outputColorSpace,stencilBuffer:T.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await s.requestReferenceSpace(a),ht.setContext(s),ht.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(K){for(let ne=0;ne<K.removed.length;ne++){const xe=K.removed[ne],Ge=E.indexOf(xe);Ge>=0&&(E[Ge]=null,S[Ge].disconnect(xe))}for(let ne=0;ne<K.added.length;ne++){const xe=K.added[ne];let Ge=E.indexOf(xe);if(Ge===-1){for(let nt=0;nt<S.length;nt++)if(nt>=E.length){E.push(xe),Ge=nt;break}else if(E[nt]===null){E[nt]=xe,Ge=nt;break}if(Ge===-1)break}const Ce=S[Ge];Ce&&Ce.connect(xe)}}const ee=new V,ge=new V;function le(K,ne,xe){ee.setFromMatrixPosition(ne.matrixWorld),ge.setFromMatrixPosition(xe.matrixWorld);const Ge=ee.distanceTo(ge),Ce=ne.projectionMatrix.elements,nt=xe.projectionMatrix.elements,Xt=Ce[14]/(Ce[10]-1),et=Ce[14]/(Ce[10]+1),ct=(Ce[9]+1)/Ce[5],gt=(Ce[9]-1)/Ce[5],We=(Ce[8]-1)/Ce[0],Ot=(nt[8]+1)/nt[0],I=Xt*We,Ut=Xt*Ot,at=Ge/(-We+Ot),bt=at*-We;if(ne.matrixWorld.decompose(K.position,K.quaternion,K.scale),K.translateX(bt),K.translateZ(at),K.matrixWorld.compose(K.position,K.quaternion,K.scale),K.matrixWorldInverse.copy(K.matrixWorld).invert(),Ce[10]===-1)K.projectionMatrix.copy(ne.projectionMatrix),K.projectionMatrixInverse.copy(ne.projectionMatrixInverse);else{const we=Xt+at,A=et+at,b=I-bt,L=Ut+(Ge-bt),X=ct*et/A*we,Q=gt*et/A*we;K.projectionMatrix.makePerspective(b,L,X,Q,we,A),K.projectionMatrixInverse.copy(K.projectionMatrix).invert()}}function _e(K,ne){ne===null?K.matrixWorld.copy(K.matrix):K.matrixWorld.multiplyMatrices(ne.matrixWorld,K.matrix),K.matrixWorldInverse.copy(K.matrixWorld).invert()}this.updateCamera=function(K){if(s===null)return;let ne=K.near,xe=K.far;m.texture!==null&&(m.depthNear>0&&(ne=m.depthNear),m.depthFar>0&&(xe=m.depthFar)),O.near=x.near=y.near=ne,O.far=x.far=y.far=xe,(U!==O.near||q!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),U=O.near,q=O.far),O.layers.mask=K.layers.mask|6,y.layers.mask=O.layers.mask&3,x.layers.mask=O.layers.mask&5;const Ge=K.parent,Ce=O.cameras;_e(O,Ge);for(let nt=0;nt<Ce.length;nt++)_e(Ce[nt],Ge);Ce.length===2?le(O,y,x):O.projectionMatrix.copy(y.projectionMatrix),Be(K,O,Ge)};function Be(K,ne,xe){xe===null?K.matrix.copy(ne.matrixWorld):(K.matrix.copy(xe.matrixWorld),K.matrix.invert(),K.matrix.multiply(ne.matrixWorld)),K.matrix.decompose(K.position,K.quaternion,K.scale),K.updateMatrixWorld(!0),K.projectionMatrix.copy(ne.projectionMatrix),K.projectionMatrixInverse.copy(ne.projectionMatrixInverse),K.isPerspectiveCamera&&(K.fov=Uc*2*Math.atan(1/K.projectionMatrix.elements[5]),K.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(K){c=K,h!==null&&(h.fixedFoveation=K),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=K)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(K){return p[K]};let Fe=null;function Tt(K,ne){if(d=ne.getViewerPose(l||o),g=ne,d!==null){const xe=d.views;f!==null&&(e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_));let Ge=!1;xe.length!==O.cameras.length&&(O.cameras.length=0,Ge=!0);for(let et=0;et<xe.length;et++){const ct=xe[et];let gt=null;if(f!==null)gt=f.getViewport(ct);else{const Ot=u.getViewSubImage(h,ct);gt=Ot.viewport,et===0&&(e.setRenderTargetTextures(_,Ot.colorTexture,Ot.depthStencilTexture),e.setRenderTarget(_))}let We=R[et];We===void 0&&(We=new wn,We.layers.enable(et),We.viewport=new Pt,R[et]=We),We.matrix.fromArray(ct.transform.matrix),We.matrix.decompose(We.position,We.quaternion,We.scale),We.projectionMatrix.fromArray(ct.projectionMatrix),We.projectionMatrixInverse.copy(We.projectionMatrix).invert(),We.viewport.set(gt.x,gt.y,gt.width,gt.height),et===0&&(O.matrix.copy(We.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),Ge===!0&&O.cameras.push(We)}const Ce=s.enabledFeatures;if(Ce&&Ce.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const et=u.getDepthInformation(xe[0]);et&&et.isValid&&et.texture&&m.init(et,s.renderState)}if(Ce&&Ce.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let et=0;et<xe.length;et++){const ct=xe[et].camera;if(ct){let gt=p[ct];gt||(gt=new nh,p[ct]=gt);const We=u.getCameraImage(ct);gt.sourceTexture=We}}}}for(let xe=0;xe<S.length;xe++){const Ge=E[xe],Ce=S[xe];Ge!==null&&Ce!==void 0&&Ce.update(Ge,ne,l||o)}Fe&&Fe(K,ne),ne.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ne}),g=null}const ht=new rh;ht.setAnimationLoop(Tt),this.setAnimationLoop=function(K){Fe=K},this.dispose=function(){}}}const fs=new vi,Wy=new Dt;function qy(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,Ku(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,T,C,_){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,_)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(o(m,p),p.isLineDashedMaterial&&a(m,p)):p.isPointsMaterial?c(m,p,T,C):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===en&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===en&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const T=e.get(p),C=T.envMap,_=T.envMapRotation;C&&(m.envMap.value=C,fs.copy(_),fs.x*=-1,fs.y*=-1,fs.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(fs.y*=-1,fs.z*=-1),m.envMapRotation.value.setFromMatrix4(Wy.makeRotationFromEuler(fs)),m.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function o(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function a(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,T,C){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*T,m.scale.value=C*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,T){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===en&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=T.texture,m.transmissionSamplerSize.value.set(T.width,T.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const T=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(T.matrixWorld),m.nearDistance.value=T.shadow.camera.near,m.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function jy(i,e,t,n){let s={},r={},o=[];const a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(T,C){const _=C.program;n.uniformBlockBinding(T,_)}function l(T,C){let _=s[T.id];_===void 0&&(g(T),_=d(T),s[T.id]=_,T.addEventListener("dispose",m));const S=C.program;n.updateUBOMapping(T,S);const E=e.render.frame;r[T.id]!==E&&(h(T),r[T.id]=E)}function d(T){const C=u();T.__bindingPointIndex=C;const _=i.createBuffer(),S=T.__size,E=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,_),i.bufferData(i.UNIFORM_BUFFER,S,E),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,C,_),_}function u(){for(let T=0;T<a;T++)if(o.indexOf(T)===-1)return o.push(T),T;return tt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(T){const C=s[T.id],_=T.uniforms,S=T.__cache;i.bindBuffer(i.UNIFORM_BUFFER,C);for(let E=0,w=_.length;E<w;E++){const k=Array.isArray(_[E])?_[E]:[_[E]];for(let y=0,x=k.length;y<x;y++){const R=k[y];if(f(R,E,y,S)===!0){const O=R.__offset,U=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let $=0;$<U.length;$++){const G=U[$],W=v(G);typeof G=="number"||typeof G=="boolean"?(R.__data[0]=G,i.bufferSubData(i.UNIFORM_BUFFER,O+q,R.__data)):G.isMatrix3?(R.__data[0]=G.elements[0],R.__data[1]=G.elements[1],R.__data[2]=G.elements[2],R.__data[3]=0,R.__data[4]=G.elements[3],R.__data[5]=G.elements[4],R.__data[6]=G.elements[5],R.__data[7]=0,R.__data[8]=G.elements[6],R.__data[9]=G.elements[7],R.__data[10]=G.elements[8],R.__data[11]=0):(G.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(T,C,_,S){const E=T.value,w=C+"_"+_;if(S[w]===void 0)return typeof E=="number"||typeof E=="boolean"?S[w]=E:S[w]=E.clone(),!0;{const k=S[w];if(typeof E=="number"||typeof E=="boolean"){if(k!==E)return S[w]=E,!0}else if(k.equals(E)===!1)return k.copy(E),!0}return!1}function g(T){const C=T.uniforms;let _=0;const S=16;for(let w=0,k=C.length;w<k;w++){const y=Array.isArray(C[w])?C[w]:[C[w]];for(let x=0,R=y.length;x<R;x++){const O=y[x],U=Array.isArray(O.value)?O.value:[O.value];for(let q=0,$=U.length;q<$;q++){const G=U[q],W=v(G),ee=_%S,ge=ee%W.boundary,le=ee+ge;_+=ge,le!==0&&S-le<W.storage&&(_+=S-le),O.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=_,_+=W.storage}}}const E=_%S;return E>0&&(_+=S-E),T.__size=_,T.__cache={},this}function v(T){const C={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(C.boundary=4,C.storage=4):T.isVector2?(C.boundary=8,C.storage=8):T.isVector3||T.isColor?(C.boundary=16,C.storage=12):T.isVector4?(C.boundary=16,C.storage=16):T.isMatrix3?(C.boundary=48,C.storage=48):T.isMatrix4?(C.boundary=64,C.storage=64):T.isTexture?Oe("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Oe("WebGLRenderer: Unsupported uniform value type.",T),C}function m(T){const C=T.target;C.removeEventListener("dispose",m);const _=o.indexOf(C.__bindingPointIndex);o.splice(_,1),i.deleteBuffer(s[C.id]),delete s[C.id],delete r[C.id]}function p(){for(const T in s)i.deleteBuffer(s[T]);o=[],s={},r={}}return{bind:c,update:l,dispose:p}}const Xy=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Qn=null;function $y(){return Qn===null&&(Qn=new Ev(Xy,16,16,Rs,hi),Qn.name="DFG_LUT",Qn.minFilter=Jt,Qn.magFilter=Jt,Qn.wrapS=ui,Qn.wrapT=ui,Qn.generateMipmaps=!1,Qn.needsUpdate=!0),Qn}class Ky{constructor(e={}){const{canvas:t=Yg(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=Tn}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;const v=f,m=new Set([tc,ec,Qo]),p=new Set([Tn,Xn,xr,Tr,Jo,Zo]),T=new Uint32Array(4),C=new Int32Array(4);let _=null,S=null;const E=[],w=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=jn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const y=this;let x=!1;this._outputColorSpace=En;let R=0,O=0,U=null,q=-1,$=null;const G=new Pt,W=new Pt;let ee=null;const ge=new Je(0);let le=0,_e=t.width,Be=t.height,Fe=1,Tt=null,ht=null;const K=new Pt(0,0,_e,Be),ne=new Pt(0,0,_e,Be);let xe=!1;const Ge=new th;let Ce=!1,nt=!1;const Xt=new Dt,et=new V,ct=new Pt,gt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let We=!1;function Ot(){return U===null?Fe:1}let I=n;function Ut(M,N){return t.getContext(M,N)}try{const M={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Lo}`),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",yt,!1),t.addEventListener("webglcontextcreationerror",lt,!1),I===null){const N="webgl2";if(I=Ut(N,M),I===null)throw Ut(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(M){throw tt("WebGLRenderer: "+M.message),M}let at,bt,we,A,b,L,X,Q,j,Re,ue,Me,Ne,se,fe,Ee,Ae,he,qe,D,be,ae,ye,ie;function Z(){at=new $_(I),at.init(),ae=new By(I,at),bt=new B_(I,at,e,ae),we=new Uy(I,at),bt.reversedDepthBuffer&&h&&we.buffers.depth.setReversed(!0),A=new J_(I),b=new xy,L=new Fy(I,at,we,b,bt,ae,A),X=new z_(y),Q=new X_(y),j=new Nv(I),ye=new U_(I,j),Re=new K_(I,j,A,ye),ue=new Q_(I,Re,j,A),qe=new Z_(I,bt,L),Ee=new V_(b),Me=new Sy(y,X,Q,at,bt,ye,Ee),Ne=new qy(y,b),se=new Ey,fe=new Py(at),he=new O_(y,X,Q,we,ue,g,c),Ae=new Ny(y,ue,bt),ie=new jy(I,A,bt,we),D=new F_(I,at,A),be=new Y_(I,at,A),A.programs=Me.programs,y.capabilities=bt,y.extensions=at,y.properties=b,y.renderLists=se,y.shadowMap=Ae,y.state=we,y.info=A}Z(),v!==Tn&&(k=new tb(v,t.width,t.height,s,r));const de=new Hy(y,I);this.xr=de,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const M=at.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){const M=at.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return Fe},this.setPixelRatio=function(M){M!==void 0&&(Fe=M,this.setSize(_e,Be,!1))},this.getSize=function(M){return M.set(_e,Be)},this.setSize=function(M,N,H=!0){if(de.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=M,Be=N,t.width=Math.floor(M*Fe),t.height=Math.floor(N*Fe),H===!0&&(t.style.width=M+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,M,N)},this.getDrawingBufferSize=function(M){return M.set(_e*Fe,Be*Fe).floor()},this.setDrawingBufferSize=function(M,N,H){_e=M,Be=N,Fe=H,t.width=Math.floor(M*H),t.height=Math.floor(N*H),this.setViewport(0,0,M,N)},this.setEffects=function(M){if(v===Tn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let N=0;N<M.length;N++)if(M[N].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(G)},this.getViewport=function(M){return M.copy(K)},this.setViewport=function(M,N,H,z){M.isVector4?K.set(M.x,M.y,M.z,M.w):K.set(M,N,H,z),we.viewport(G.copy(K).multiplyScalar(Fe).round())},this.getScissor=function(M){return M.copy(ne)},this.setScissor=function(M,N,H,z){M.isVector4?ne.set(M.x,M.y,M.z,M.w):ne.set(M,N,H,z),we.scissor(W.copy(ne).multiplyScalar(Fe).round())},this.getScissorTest=function(){return xe},this.setScissorTest=function(M){we.setScissorTest(xe=M)},this.setOpaqueSort=function(M){Tt=M},this.setTransparentSort=function(M){ht=M},this.getClearColor=function(M){return M.copy(he.getClearColor())},this.setClearColor=function(){he.setClearColor(...arguments)},this.getClearAlpha=function(){return he.getClearAlpha()},this.setClearAlpha=function(){he.setClearAlpha(...arguments)},this.clear=function(M=!0,N=!0,H=!0){let z=0;if(M){let F=!1;if(U!==null){const pe=U.texture.format;F=m.has(pe)}if(F){const pe=U.texture.type,Se=p.has(pe),ve=he.getClearColor(),Te=he.getClearAlpha(),Pe=ve.r,Le=ve.g,ke=ve.b;Se?(T[0]=Pe,T[1]=Le,T[2]=ke,T[3]=Te,I.clearBufferuiv(I.COLOR,0,T)):(C[0]=Pe,C[1]=Le,C[2]=ke,C[3]=Te,I.clearBufferiv(I.COLOR,0,C))}else z|=I.COLOR_BUFFER_BIT}N&&(z|=I.DEPTH_BUFFER_BIT),H&&(z|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(z)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",yt,!1),t.removeEventListener("webglcontextcreationerror",lt,!1),he.dispose(),se.dispose(),fe.dispose(),b.dispose(),X.dispose(),Q.dispose(),ue.dispose(),ye.dispose(),ie.dispose(),Me.dispose(),de.dispose(),de.removeEventListener("sessionstart",Bm),de.removeEventListener("sessionend",Vm),Ss.stop()};function Ue(M){M.preventDefault(),Au("WebGLRenderer: Context Lost."),x=!0}function yt(){Au("WebGLRenderer: Context Restored."),x=!1;const M=A.autoReset,N=Ae.enabled,H=Ae.autoUpdate,z=Ae.needsUpdate,F=Ae.type;Z(),A.autoReset=M,Ae.enabled=N,Ae.autoUpdate=H,Ae.needsUpdate=z,Ae.type=F}function lt(M){tt("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function oi(M){const N=M.target;N.removeEventListener("dispose",oi),Ai(N)}function Ai(M){RC(M),b.remove(M)}function RC(M){const N=b.get(M).programs;N!==void 0&&(N.forEach(function(H){Me.releaseProgram(H)}),M.isShaderMaterial&&Me.releaseShaderCache(M))}this.renderBufferDirect=function(M,N,H,z,F,pe){N===null&&(N=gt);const Se=F.isMesh&&F.matrixWorld.determinant()<0,ve=kC(M,N,H,z,F);we.setMaterial(z,Se);let Te=H.index,Pe=1;if(z.wireframe===!0){if(Te=Re.getWireframeAttribute(H),Te===void 0)return;Pe=2}const Le=H.drawRange,ke=H.attributes.position;let Xe=Le.start*Pe,ft=(Le.start+Le.count)*Pe;pe!==null&&(Xe=Math.max(Xe,pe.start*Pe),ft=Math.min(ft,(pe.start+pe.count)*Pe)),Te!==null?(Xe=Math.max(Xe,0),ft=Math.min(ft,Te.count)):ke!=null&&(Xe=Math.max(Xe,0),ft=Math.min(ft,ke.count));const At=ft-Xe;if(At<0||At===1/0)return;ye.setup(F,z,ve,H,Te);let Rt,vt=D;if(Te!==null&&(Rt=j.get(Te),vt=be,vt.setIndex(Rt)),F.isMesh)z.wireframe===!0?(we.setLineWidth(z.wireframeLinewidth*Ot()),vt.setMode(I.LINES)):vt.setMode(I.TRIANGLES);else if(F.isLine){let Ie=z.linewidth;Ie===void 0&&(Ie=1),we.setLineWidth(Ie*Ot()),F.isLineSegments?vt.setMode(I.LINES):F.isLineLoop?vt.setMode(I.LINE_LOOP):vt.setMode(I.LINE_STRIP)}else F.isPoints?vt.setMode(I.POINTS):F.isSprite&&vt.setMode(I.TRIANGLES);if(F.isBatchedMesh)if(F._multiDrawInstances!==null)Er("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),vt.renderMultiDrawInstances(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount,F._multiDrawInstances);else if(at.get("WEBGL_multi_draw"))vt.renderMultiDraw(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount);else{const Ie=F._multiDrawStarts,dt=F._multiDrawCounts,it=F._multiDrawCount,Sn=Te?j.get(Te).bytesPerElement:1,hr=b.get(z).currentProgram.getUniforms();for(let xn=0;xn<it;xn++)hr.setValue(I,"_gl_DrawID",xn),vt.render(Ie[xn]/Sn,dt[xn])}else if(F.isInstancedMesh)vt.renderInstances(Xe,At,F.count);else if(H.isInstancedBufferGeometry){const Ie=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,dt=Math.min(H.instanceCount,Ie);vt.renderInstances(Xe,At,dt)}else vt.render(Xe,At)};function Fm(M,N,H){M.transparent===!0&&M.side===li&&M.forceSinglePass===!1?(M.side=en,M.needsUpdate=!0,Eo(M,N,H),M.side=ci,M.needsUpdate=!0,Eo(M,N,H),M.side=li):Eo(M,N,H)}this.compile=function(M,N,H=null){H===null&&(H=M),S=fe.get(H),S.init(N),w.push(S),H.traverseVisible(function(F){F.isLight&&F.layers.test(N.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),M!==H&&M.traverseVisible(function(F){F.isLight&&F.layers.test(N.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),S.setupLights();const z=new Set;return M.traverse(function(F){if(!(F.isMesh||F.isPoints||F.isLine||F.isSprite))return;const pe=F.material;if(pe)if(Array.isArray(pe))for(let Se=0;Se<pe.length;Se++){const ve=pe[Se];Fm(ve,H,F),z.add(ve)}else Fm(pe,H,F),z.add(pe)}),S=w.pop(),z},this.compileAsync=function(M,N,H=null){const z=this.compile(M,N,H);return new Promise(F=>{function pe(){if(z.forEach(function(Se){b.get(Se).currentProgram.isReady()&&z.delete(Se)}),z.size===0){F(M);return}setTimeout(pe,10)}at.get("KHR_parallel_shader_compile")!==null?pe():setTimeout(pe,10)})};let Fd=null;function PC(M){Fd&&Fd(M)}function Bm(){Ss.stop()}function Vm(){Ss.start()}const Ss=new rh;Ss.setAnimationLoop(PC),typeof self<"u"&&Ss.setContext(self),this.setAnimationLoop=function(M){Fd=M,de.setAnimationLoop(M),M===null?Ss.stop():Ss.start()},de.addEventListener("sessionstart",Bm),de.addEventListener("sessionend",Vm),this.render=function(M,N){if(N!==void 0&&N.isCamera!==!0){tt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(x===!0)return;const H=de.enabled===!0&&de.isPresenting===!0,z=k!==null&&(U===null||H)&&k.begin(y,U);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),de.enabled===!0&&de.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(de.cameraAutoUpdate===!0&&de.updateCamera(N),N=de.getCamera()),M.isScene===!0&&M.onBeforeRender(y,M,N,U),S=fe.get(M,w.length),S.init(N),w.push(S),Xt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),Ge.setFromProjectionMatrix(Xt,Kn,N.reversedDepth),nt=this.localClippingEnabled,Ce=Ee.init(this.clippingPlanes,nt),_=se.get(M,E.length),_.init(),E.push(_),de.enabled===!0&&de.isPresenting===!0){const Se=y.xr.getDepthSensingMesh();Se!==null&&Bd(Se,N,-1/0,y.sortObjects)}Bd(M,N,0,y.sortObjects),_.finish(),y.sortObjects===!0&&_.sort(Tt,ht),We=de.enabled===!1||de.isPresenting===!1||de.hasDepthSensing()===!1,We&&he.addToRenderList(_,M),this.info.render.frame++,Ce===!0&&Ee.beginShadows();const F=S.state.shadowsArray;if(Ae.render(F,M,N),Ce===!0&&Ee.endShadows(),this.info.autoReset===!0&&this.info.reset(),(z&&k.hasRenderPass())===!1){const Se=_.opaque,ve=_.transmissive;if(S.setupLights(),N.isArrayCamera){const Te=N.cameras;if(ve.length>0)for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe];Gm(Se,ve,M,ke)}We&&he.render(M);for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe];zm(_,M,ke,ke.viewport)}}else ve.length>0&&Gm(Se,ve,M,N),We&&he.render(M),zm(_,M,N)}U!==null&&O===0&&(L.updateMultisampleRenderTarget(U),L.updateRenderTargetMipmap(U)),z&&k.end(y),M.isScene===!0&&M.onAfterRender(y,M,N),ye.resetDefaultState(),q=-1,$=null,w.pop(),w.length>0?(S=w[w.length-1],Ce===!0&&Ee.setGlobalState(y.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?_=E[E.length-1]:_=null};function Bd(M,N,H,z){if(M.visible===!1)return;if(M.layers.test(N.layers)){if(M.isGroup)H=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(N);else if(M.isLight)S.pushLight(M),M.castShadow&&S.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||Ge.intersectsSprite(M)){z&&ct.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Xt);const Se=ue.update(M),ve=M.material;ve.visible&&_.push(M,Se,ve,H,ct.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||Ge.intersectsObject(M))){const Se=ue.update(M),ve=M.material;if(z&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),ct.copy(M.boundingSphere.center)):(Se.boundingSphere===null&&Se.computeBoundingSphere(),ct.copy(Se.boundingSphere.center)),ct.applyMatrix4(M.matrixWorld).applyMatrix4(Xt)),Array.isArray(ve)){const Te=Se.groups;for(let Pe=0,Le=Te.length;Pe<Le;Pe++){const ke=Te[Pe],Xe=ve[ke.materialIndex];Xe&&Xe.visible&&_.push(M,Se,Xe,H,ct.z,ke)}}else ve.visible&&_.push(M,Se,ve,H,ct.z,null)}}const pe=M.children;for(let Se=0,ve=pe.length;Se<ve;Se++)Bd(pe[Se],N,H,z)}function zm(M,N,H,z){const{opaque:F,transmissive:pe,transparent:Se}=M;S.setupLightsView(H),Ce===!0&&Ee.setGlobalState(y.clippingPlanes,H),z&&we.viewport(G.copy(z)),F.length>0&&To(F,N,H),pe.length>0&&To(pe,N,H),Se.length>0&&To(Se,N,H),we.buffers.depth.setTest(!0),we.buffers.depth.setMask(!0),we.buffers.color.setMask(!0),we.setPolygonOffset(!1)}function Gm(M,N,H,z){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[z.id]===void 0){const Xe=at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[z.id]=new Yn(1,1,{generateMipmaps:!0,type:Xe?hi:Tn,minFilter:ss,samples:bt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ze.workingColorSpace})}const pe=S.state.transmissionRenderTarget[z.id],Se=z.viewport||G;pe.setSize(Se.z*y.transmissionResolutionScale,Se.w*y.transmissionResolutionScale);const ve=y.getRenderTarget(),Te=y.getActiveCubeFace(),Pe=y.getActiveMipmapLevel();y.setRenderTarget(pe),y.getClearColor(ge),le=y.getClearAlpha(),le<1&&y.setClearColor(16777215,.5),y.clear(),We&&he.render(H);const Le=y.toneMapping;y.toneMapping=jn;const ke=z.viewport;if(z.viewport!==void 0&&(z.viewport=void 0),S.setupLightsView(z),Ce===!0&&Ee.setGlobalState(y.clippingPlanes,z),To(M,H,z),L.updateMultisampleRenderTarget(pe),L.updateRenderTargetMipmap(pe),at.has("WEBGL_multisampled_render_to_texture")===!1){let Xe=!1;for(let ft=0,At=N.length;ft<At;ft++){const Rt=N[ft],{object:vt,geometry:Ie,material:dt,group:it}=Rt;if(dt.side===li&&vt.layers.test(z.layers)){const Sn=dt.side;dt.side=en,dt.needsUpdate=!0,Hm(vt,H,z,Ie,dt,it),dt.side=Sn,dt.needsUpdate=!0,Xe=!0}}Xe===!0&&(L.updateMultisampleRenderTarget(pe),L.updateRenderTargetMipmap(pe))}y.setRenderTarget(ve,Te,Pe),y.setClearColor(ge,le),ke!==void 0&&(z.viewport=ke),y.toneMapping=Le}function To(M,N,H){const z=N.isScene===!0?N.overrideMaterial:null;for(let F=0,pe=M.length;F<pe;F++){const Se=M[F],{object:ve,geometry:Te,group:Pe}=Se;let Le=Se.material;Le.allowOverride===!0&&z!==null&&(Le=z),ve.layers.test(H.layers)&&Hm(ve,N,H,Te,Le,Pe)}}function Hm(M,N,H,z,F,pe){M.onBeforeRender(y,N,H,z,F,pe),M.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),F.onBeforeRender(y,N,H,z,M,pe),F.transparent===!0&&F.side===li&&F.forceSinglePass===!1?(F.side=en,F.needsUpdate=!0,y.renderBufferDirect(H,N,z,F,M,pe),F.side=ci,F.needsUpdate=!0,y.renderBufferDirect(H,N,z,F,M,pe),F.side=li):y.renderBufferDirect(H,N,z,F,M,pe),M.onAfterRender(y,N,H,z,F,pe)}function Eo(M,N,H){N.isScene!==!0&&(N=gt);const z=b.get(M),F=S.state.lights,pe=S.state.shadowsArray,Se=F.state.version,ve=Me.getParameters(M,F.state,pe,N,H),Te=Me.getProgramCacheKey(ve);let Pe=z.programs;z.environment=M.isMeshStandardMaterial?N.environment:null,z.fog=N.fog,z.envMap=(M.isMeshStandardMaterial?Q:X).get(M.envMap||z.environment),z.envMapRotation=z.environment!==null&&M.envMap===null?N.environmentRotation:M.envMapRotation,Pe===void 0&&(M.addEventListener("dispose",oi),Pe=new Map,z.programs=Pe);let Le=Pe.get(Te);if(Le!==void 0){if(z.currentProgram===Le&&z.lightsStateVersion===Se)return qm(M,ve),Le}else ve.uniforms=Me.getUniforms(M),M.onBeforeCompile(ve,y),Le=Me.acquireProgram(ve,Te),Pe.set(Te,Le),z.uniforms=ve.uniforms;const ke=z.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&(ke.clippingPlanes=Ee.uniform),qm(M,ve),z.needsLights=DC(M),z.lightsStateVersion=Se,z.needsLights&&(ke.ambientLightColor.value=F.state.ambient,ke.lightProbe.value=F.state.probe,ke.directionalLights.value=F.state.directional,ke.directionalLightShadows.value=F.state.directionalShadow,ke.spotLights.value=F.state.spot,ke.spotLightShadows.value=F.state.spotShadow,ke.rectAreaLights.value=F.state.rectArea,ke.ltc_1.value=F.state.rectAreaLTC1,ke.ltc_2.value=F.state.rectAreaLTC2,ke.pointLights.value=F.state.point,ke.pointLightShadows.value=F.state.pointShadow,ke.hemisphereLights.value=F.state.hemi,ke.directionalShadowMap.value=F.state.directionalShadowMap,ke.directionalShadowMatrix.value=F.state.directionalShadowMatrix,ke.spotShadowMap.value=F.state.spotShadowMap,ke.spotLightMatrix.value=F.state.spotLightMatrix,ke.spotLightMap.value=F.state.spotLightMap,ke.pointShadowMap.value=F.state.pointShadowMap,ke.pointShadowMatrix.value=F.state.pointShadowMatrix),z.currentProgram=Le,z.uniformsList=null,Le}function Wm(M){if(M.uniformsList===null){const N=M.currentProgram.getUniforms();M.uniformsList=Ba.seqWithValue(N.seq,M.uniforms)}return M.uniformsList}function qm(M,N){const H=b.get(M);H.outputColorSpace=N.outputColorSpace,H.batching=N.batching,H.batchingColor=N.batchingColor,H.instancing=N.instancing,H.instancingColor=N.instancingColor,H.instancingMorph=N.instancingMorph,H.skinning=N.skinning,H.morphTargets=N.morphTargets,H.morphNormals=N.morphNormals,H.morphColors=N.morphColors,H.morphTargetsCount=N.morphTargetsCount,H.numClippingPlanes=N.numClippingPlanes,H.numIntersection=N.numClipIntersection,H.vertexAlphas=N.vertexAlphas,H.vertexTangents=N.vertexTangents,H.toneMapping=N.toneMapping}function kC(M,N,H,z,F){N.isScene!==!0&&(N=gt),L.resetTextureUnits();const pe=N.fog,Se=z.isMeshStandardMaterial?N.environment:null,ve=U===null?y.outputColorSpace:U.isXRRenderTarget===!0?U.texture.colorSpace:Ps,Te=(z.isMeshStandardMaterial?Q:X).get(z.envMap||Se),Pe=z.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Le=!!H.attributes.tangent&&(!!z.normalMap||z.anisotropy>0),ke=!!H.morphAttributes.position,Xe=!!H.morphAttributes.normal,ft=!!H.morphAttributes.color;let At=jn;z.toneMapped&&(U===null||U.isXRRenderTarget===!0)&&(At=y.toneMapping);const Rt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,vt=Rt!==void 0?Rt.length:0,Ie=b.get(z),dt=S.state.lights;if(Ce===!0&&(nt===!0||M!==$)){const ln=M===$&&z.id===q;Ee.setState(z,M,ln)}let it=!1;z.version===Ie.__version?(Ie.needsLights&&Ie.lightsStateVersion!==dt.state.version||Ie.outputColorSpace!==ve||F.isBatchedMesh&&Ie.batching===!1||!F.isBatchedMesh&&Ie.batching===!0||F.isBatchedMesh&&Ie.batchingColor===!0&&F.colorTexture===null||F.isBatchedMesh&&Ie.batchingColor===!1&&F.colorTexture!==null||F.isInstancedMesh&&Ie.instancing===!1||!F.isInstancedMesh&&Ie.instancing===!0||F.isSkinnedMesh&&Ie.skinning===!1||!F.isSkinnedMesh&&Ie.skinning===!0||F.isInstancedMesh&&Ie.instancingColor===!0&&F.instanceColor===null||F.isInstancedMesh&&Ie.instancingColor===!1&&F.instanceColor!==null||F.isInstancedMesh&&Ie.instancingMorph===!0&&F.morphTexture===null||F.isInstancedMesh&&Ie.instancingMorph===!1&&F.morphTexture!==null||Ie.envMap!==Te||z.fog===!0&&Ie.fog!==pe||Ie.numClippingPlanes!==void 0&&(Ie.numClippingPlanes!==Ee.numPlanes||Ie.numIntersection!==Ee.numIntersection)||Ie.vertexAlphas!==Pe||Ie.vertexTangents!==Le||Ie.morphTargets!==ke||Ie.morphNormals!==Xe||Ie.morphColors!==ft||Ie.toneMapping!==At||Ie.morphTargetsCount!==vt)&&(it=!0):(it=!0,Ie.__version=z.version);let Sn=Ie.currentProgram;it===!0&&(Sn=Eo(z,N,F));let hr=!1,xn=!1,na=!1;const St=Sn.getUniforms(),mn=Ie.uniforms;if(we.useProgram(Sn.program)&&(hr=!0,xn=!0,na=!0),z.id!==q&&(q=z.id,xn=!0),hr||$!==M){we.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),St.setValue(I,"projectionMatrix",M.projectionMatrix),St.setValue(I,"viewMatrix",M.matrixWorldInverse);const gn=St.map.cameraPosition;gn!==void 0&&gn.setValue(I,et.setFromMatrixPosition(M.matrixWorld)),bt.logarithmicDepthBuffer&&St.setValue(I,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),(z.isMeshPhongMaterial||z.isMeshToonMaterial||z.isMeshLambertMaterial||z.isMeshBasicMaterial||z.isMeshStandardMaterial||z.isShaderMaterial)&&St.setValue(I,"isOrthographic",M.isOrthographicCamera===!0),$!==M&&($=M,xn=!0,na=!0)}if(Ie.needsLights&&(dt.state.directionalShadowMap.length>0&&St.setValue(I,"directionalShadowMap",dt.state.directionalShadowMap,L),dt.state.spotShadowMap.length>0&&St.setValue(I,"spotShadowMap",dt.state.spotShadowMap,L),dt.state.pointShadowMap.length>0&&St.setValue(I,"pointShadowMap",dt.state.pointShadowMap,L)),F.isSkinnedMesh){St.setOptional(I,F,"bindMatrix"),St.setOptional(I,F,"bindMatrixInverse");const ln=F.skeleton;ln&&(ln.boneTexture===null&&ln.computeBoneTexture(),St.setValue(I,"boneTexture",ln.boneTexture,L))}F.isBatchedMesh&&(St.setOptional(I,F,"batchingTexture"),St.setValue(I,"batchingTexture",F._matricesTexture,L),St.setOptional(I,F,"batchingIdTexture"),St.setValue(I,"batchingIdTexture",F._indirectTexture,L),St.setOptional(I,F,"batchingColorTexture"),F._colorsTexture!==null&&St.setValue(I,"batchingColorTexture",F._colorsTexture,L));const kn=H.morphAttributes;if((kn.position!==void 0||kn.normal!==void 0||kn.color!==void 0)&&qe.update(F,H,Sn),(xn||Ie.receiveShadow!==F.receiveShadow)&&(Ie.receiveShadow=F.receiveShadow,St.setValue(I,"receiveShadow",F.receiveShadow)),z.isMeshGouraudMaterial&&z.envMap!==null&&(mn.envMap.value=Te,mn.flipEnvMap.value=Te.isCubeTexture&&Te.isRenderTargetTexture===!1?-1:1),z.isMeshStandardMaterial&&z.envMap===null&&N.environment!==null&&(mn.envMapIntensity.value=N.environmentIntensity),mn.dfgLUT!==void 0&&(mn.dfgLUT.value=$y()),xn&&(St.setValue(I,"toneMappingExposure",y.toneMappingExposure),Ie.needsLights&&IC(mn,na),pe&&z.fog===!0&&Ne.refreshFogUniforms(mn,pe),Ne.refreshMaterialUniforms(mn,z,Fe,Be,S.state.transmissionRenderTarget[M.id]),Ba.upload(I,Wm(Ie),mn,L)),z.isShaderMaterial&&z.uniformsNeedUpdate===!0&&(Ba.upload(I,Wm(Ie),mn,L),z.uniformsNeedUpdate=!1),z.isSpriteMaterial&&St.setValue(I,"center",F.center),St.setValue(I,"modelViewMatrix",F.modelViewMatrix),St.setValue(I,"normalMatrix",F.normalMatrix),St.setValue(I,"modelMatrix",F.matrixWorld),z.isShaderMaterial||z.isRawShaderMaterial){const ln=z.uniformsGroups;for(let gn=0,Vd=ln.length;gn<Vd;gn++){const xs=ln[gn];ie.update(xs,Sn),ie.bind(xs,Sn)}}return Sn}function IC(M,N){M.ambientLightColor.needsUpdate=N,M.lightProbe.needsUpdate=N,M.directionalLights.needsUpdate=N,M.directionalLightShadows.needsUpdate=N,M.pointLights.needsUpdate=N,M.pointLightShadows.needsUpdate=N,M.spotLights.needsUpdate=N,M.spotLightShadows.needsUpdate=N,M.rectAreaLights.needsUpdate=N,M.hemisphereLights.needsUpdate=N}function DC(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return U},this.setRenderTargetTextures=function(M,N,H){const z=b.get(M);z.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,z.__autoAllocateDepthBuffer===!1&&(z.__useRenderToTexture=!1),b.get(M.texture).__webglTexture=N,b.get(M.depthTexture).__webglTexture=z.__autoAllocateDepthBuffer?void 0:H,z.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,N){const H=b.get(M);H.__webglFramebuffer=N,H.__useDefaultFramebuffer=N===void 0};const LC=I.createFramebuffer();this.setRenderTarget=function(M,N=0,H=0){U=M,R=N,O=H;let z=null,F=!1,pe=!1;if(M){const ve=b.get(M);if(ve.__useDefaultFramebuffer!==void 0){we.bindFramebuffer(I.FRAMEBUFFER,ve.__webglFramebuffer),G.copy(M.viewport),W.copy(M.scissor),ee=M.scissorTest,we.viewport(G),we.scissor(W),we.setScissorTest(ee),q=-1;return}else if(ve.__webglFramebuffer===void 0)L.setupRenderTarget(M);else if(ve.__hasExternalTextures)L.rebindTextures(M,b.get(M.texture).__webglTexture,b.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){const Le=M.depthTexture;if(ve.__boundDepthTexture!==Le){if(Le!==null&&b.has(Le)&&(M.width!==Le.image.width||M.height!==Le.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(M)}}const Te=M.texture;(Te.isData3DTexture||Te.isDataArrayTexture||Te.isCompressedArrayTexture)&&(pe=!0);const Pe=b.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(Pe[N])?z=Pe[N][H]:z=Pe[N],F=!0):M.samples>0&&L.useMultisampledRTT(M)===!1?z=b.get(M).__webglMultisampledFramebuffer:Array.isArray(Pe)?z=Pe[H]:z=Pe,G.copy(M.viewport),W.copy(M.scissor),ee=M.scissorTest}else G.copy(K).multiplyScalar(Fe).floor(),W.copy(ne).multiplyScalar(Fe).floor(),ee=xe;if(H!==0&&(z=LC),we.bindFramebuffer(I.FRAMEBUFFER,z)&&we.drawBuffers(M,z),we.viewport(G),we.scissor(W),we.setScissorTest(ee),F){const ve=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,ve.__webglTexture,H)}else if(pe){const ve=N;for(let Te=0;Te<M.textures.length;Te++){const Pe=b.get(M.textures[Te]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Te,Pe.__webglTexture,H,ve)}}else if(M!==null&&H!==0){const ve=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ve.__webglTexture,H)}q=-1},this.readRenderTargetPixels=function(M,N,H,z,F,pe,Se,ve=0){if(!(M&&M.isWebGLRenderTarget)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Te=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Se!==void 0&&(Te=Te[Se]),Te){we.bindFramebuffer(I.FRAMEBUFFER,Te);try{const Pe=M.textures[ve],Le=Pe.format,ke=Pe.type;if(!bt.textureFormatReadable(Le)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!bt.textureTypeReadable(ke)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=M.width-z&&H>=0&&H<=M.height-F&&(M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ve),I.readPixels(N,H,z,F,ae.convert(Le),ae.convert(ke),pe))}finally{const Pe=U!==null?b.get(U).__webglFramebuffer:null;we.bindFramebuffer(I.FRAMEBUFFER,Pe)}}},this.readRenderTargetPixelsAsync=async function(M,N,H,z,F,pe,Se,ve=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Te=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Se!==void 0&&(Te=Te[Se]),Te)if(N>=0&&N<=M.width-z&&H>=0&&H<=M.height-F){we.bindFramebuffer(I.FRAMEBUFFER,Te);const Pe=M.textures[ve],Le=Pe.format,ke=Pe.type;if(!bt.textureFormatReadable(Le))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!bt.textureTypeReadable(ke))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Xe=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,Xe),I.bufferData(I.PIXEL_PACK_BUFFER,pe.byteLength,I.STREAM_READ),M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ve),I.readPixels(N,H,z,F,ae.convert(Le),ae.convert(ke),0);const ft=U!==null?b.get(U).__webglFramebuffer:null;we.bindFramebuffer(I.FRAMEBUFFER,ft);const At=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await Jg(I,At,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,Xe),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,pe),I.deleteBuffer(Xe),I.deleteSync(At),pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,N=null,H=0){const z=Math.pow(2,-H),F=Math.floor(M.image.width*z),pe=Math.floor(M.image.height*z),Se=N!==null?N.x:0,ve=N!==null?N.y:0;L.setTexture2D(M,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Se,ve,F,pe),we.unbindTexture()};const NC=I.createFramebuffer(),OC=I.createFramebuffer();this.copyTextureToTexture=function(M,N,H=null,z=null,F=0,pe=null){pe===null&&(F!==0?(Er("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pe=F,F=0):pe=0);let Se,ve,Te,Pe,Le,ke,Xe,ft,At;const Rt=M.isCompressedTexture?M.mipmaps[pe]:M.image;if(H!==null)Se=H.max.x-H.min.x,ve=H.max.y-H.min.y,Te=H.isBox3?H.max.z-H.min.z:1,Pe=H.min.x,Le=H.min.y,ke=H.isBox3?H.min.z:0;else{const kn=Math.pow(2,-F);Se=Math.floor(Rt.width*kn),ve=Math.floor(Rt.height*kn),M.isDataArrayTexture?Te=Rt.depth:M.isData3DTexture?Te=Math.floor(Rt.depth*kn):Te=1,Pe=0,Le=0,ke=0}z!==null?(Xe=z.x,ft=z.y,At=z.z):(Xe=0,ft=0,At=0);const vt=ae.convert(N.format),Ie=ae.convert(N.type);let dt;N.isData3DTexture?(L.setTexture3D(N,0),dt=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),dt=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),dt=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const it=I.getParameter(I.UNPACK_ROW_LENGTH),Sn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),hr=I.getParameter(I.UNPACK_SKIP_PIXELS),xn=I.getParameter(I.UNPACK_SKIP_ROWS),na=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Rt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Rt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Pe),I.pixelStorei(I.UNPACK_SKIP_ROWS,Le),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ke);const St=M.isDataArrayTexture||M.isData3DTexture,mn=N.isDataArrayTexture||N.isData3DTexture;if(M.isDepthTexture){const kn=b.get(M),ln=b.get(N),gn=b.get(kn.__renderTarget),Vd=b.get(ln.__renderTarget);we.bindFramebuffer(I.READ_FRAMEBUFFER,gn.__webglFramebuffer),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,Vd.__webglFramebuffer);for(let xs=0;xs<Te;xs++)St&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(M).__webglTexture,F,ke+xs),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(N).__webglTexture,pe,At+xs)),I.blitFramebuffer(Pe,Le,Se,ve,Xe,ft,Se,ve,I.DEPTH_BUFFER_BIT,I.NEAREST);we.bindFramebuffer(I.READ_FRAMEBUFFER,null),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(F!==0||M.isRenderTargetTexture||b.has(M)){const kn=b.get(M),ln=b.get(N);we.bindFramebuffer(I.READ_FRAMEBUFFER,NC),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,OC);for(let gn=0;gn<Te;gn++)St?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,kn.__webglTexture,F,ke+gn):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,kn.__webglTexture,F),mn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,ln.__webglTexture,pe,At+gn):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ln.__webglTexture,pe),F!==0?I.blitFramebuffer(Pe,Le,Se,ve,Xe,ft,Se,ve,I.COLOR_BUFFER_BIT,I.NEAREST):mn?I.copyTexSubImage3D(dt,pe,Xe,ft,At+gn,Pe,Le,Se,ve):I.copyTexSubImage2D(dt,pe,Xe,ft,Pe,Le,Se,ve);we.bindFramebuffer(I.READ_FRAMEBUFFER,null),we.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else mn?M.isDataTexture||M.isData3DTexture?I.texSubImage3D(dt,pe,Xe,ft,At,Se,ve,Te,vt,Ie,Rt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(dt,pe,Xe,ft,At,Se,ve,Te,vt,Rt.data):I.texSubImage3D(dt,pe,Xe,ft,At,Se,ve,Te,vt,Ie,Rt):M.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,pe,Xe,ft,Se,ve,vt,Ie,Rt.data):M.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,pe,Xe,ft,Rt.width,Rt.height,vt,Rt.data):I.texSubImage2D(I.TEXTURE_2D,pe,Xe,ft,Se,ve,vt,Ie,Rt);I.pixelStorei(I.UNPACK_ROW_LENGTH,it),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Sn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,hr),I.pixelStorei(I.UNPACK_SKIP_ROWS,xn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,na),pe===0&&N.generateMipmaps&&I.generateMipmap(dt),we.unbindTexture()},this.initRenderTarget=function(M){b.get(M).__webglFramebuffer===void 0&&L.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?L.setTextureCube(M,0):M.isData3DTexture?L.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?L.setTexture2DArray(M,0):L.setTexture2D(M,0),we.unbindTexture()},this.resetState=function(){R=0,O=0,U=null,we.reset(),ye.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Kn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Ze._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ze._getUnpackColorSpace()}}const Dh=`
4058
4058
  uniform float uTime;
4059
4059
  uniform float uAudioBass;
4060
4060
  uniform float uAudioMid;
@@ -4466,8 +4466,8 @@ void main() {
4466
4466
 
4467
4467
  gl_FragColor = vec4(color, alpha * 0.4);
4468
4468
  }
4469
- `,ps={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},Zy={size:1,segments:128,colors:ps,morphStrength:1,noiseScale:1.5,noiseSpeed:.3,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:3,audioSmoothing:.9,idleMorphMultiplier:.25,colorContrast:1.5};class yl{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.canvasPadding=3,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const a=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=a,this.orbMaterial.uniforms.uAudioBass.value=this.audioValues.bass,this.orbMaterial.uniforms.uAudioMid.value=this.audioValues.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.audioValues.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const c=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,l=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(c-l)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=a,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const c=this.isActive?this.config.glowIntensity*1.2:this.config.glowIntensity*this.config.idleGlowMultiplier,l=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(c-l)*.05}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const a=this.container.clientWidth*this.canvasPadding,c=this.container.clientHeight*this.canvasPadding;this.camera.aspect=a/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,c)},this.handleMouseMove=a=>{const c=this.container.getBoundingClientRect(),l=(a.clientX-c.left)/c.width*2-1,d=-((a.clientY-c.top)/c.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=l*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...Zy,...t},this.clock=new Dv,this.scene=new Tv;const n=e.clientWidth*this.canvasPadding,s=e.clientHeight*this.canvasPadding,r=n/s;this.camera=new wn(45,r,.1,100),this.camera.position.z=9,this.renderer=new Ky({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(n,s),this.renderer.setClearColor(0,0);const o=this.renderer.domElement;o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.transform="translate(-50%, -50%)",o.style.pointerEvents="none",e.appendChild(o),this.createOrb(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}createOrb(){const e={...ps,...this.config.colors},t=new dl(this.config.size,this.config.segments/4);this.orbMaterial=new Mn({vertexShader:Dh,fragmentShader:Lh,uniforms:{uTime:{value:0},uAudioBass:{value:0},uAudioMid:{value:0},uAudioTreble:{value:0},uAudioLevel:{value:0},uMorphStrength:{value:this.config.morphStrength},uNoiseScale:{value:this.config.noiseScale},uNoiseSpeed:{value:this.config.noiseSpeed},uAudioReactivity:{value:this.config.audioReactivity},uColorPrimary:{value:new Je(e.primary)},uColorSecondary:{value:new Je(e.secondary)},uColorAccent:{value:new Je(e.accent)},uColorDepth:{value:new Je(e.depth||ps.depth)},uColorHighlight:{value:new Je(e.highlight||ps.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:ci}),this.orb=new Fn(t,this.orbMaterial),this.scene.add(this.orb);const n=new ul(this.config.size,64,64);this.glowMaterial=new Mn({vertexShader:Nh,fragmentShader:Oh,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Je(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:en,blending:No,depthWrite:!1}),this.glowMesh=new Fn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...ps,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||ps.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||ps.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb)),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh)),this.orbMaterial&&this.orbMaterial.dispose(),this.glowMaterial&&this.glowMaterial.dispose(),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}class Uh{constructor(e={}){this.audioContext=null,this.analyser=null,this.source=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async connectStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect(),this.source=this.audioContext.createMediaStreamSource(e),this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,this.source.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}async connectAudioElement(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect();const t=this.audioContext.createMediaElementSource(e);this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,t.connect(this.analyser),this.analyser.connect(this.audioContext.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let o=0,a=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?o+=f:h<r?a+=f:c+=f}const l=s>0?o/s:0,d=r-s>0?a/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){this.source&&(this.source.disconnect(),this.source=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}function Qy(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var eS=Object.defineProperty,tS=(i,e,t)=>e in i?eS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Fh=(i,e,t)=>tS(i,typeof e!="symbol"?e+"":e,t);class rn{constructor(){Fh(this,"_locking"),Fh(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Ct(i,e){if(!i)throw new Error(e)}const nS=34028234663852886e22,iS=-34028234663852886e22,sS=4294967295,rS=2147483647,aS=-2147483648;function Ga(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>rS||i<aS)throw new Error("invalid int 32: "+i)}function Sl(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>sS||i<0)throw new Error("invalid uint 32: "+i)}function Bh(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>nS||i<iS))throw new Error("invalid float 32: "+i)}const Vh=Symbol("@bufbuild/protobuf/enum-type");function oS(i){const e=i[Vh];return Ct(e,"missing enum type on enum object"),e}function zh(i,e,t,n){i[Vh]=Gh(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Gh(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=Hh(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function cS(i,e,t){const n={};for(const s of e){const r=Hh(s);n[r.localName]=r.no,n[r.no]=r.localName}return zh(n,i,e),n}function Hh(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class xl{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function lS(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new xl),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function dS(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Tl(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Ha=4294967296;function Wh(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Ha&&(s=s+(n/Ha|0),n=n%Ha)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?jh(n,s):El(n,s)}function uS(i,e){let t=El(i,e);const n=t.hi&2147483648;n&&(t=jh(t.lo,t.hi));const s=qh(t.lo,t.hi);return n?"-"+s:s}function qh(i,e){if({lo:i,hi:e}=hS(i,e),e<=2097151)return String(Ha*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Xh(o)+Xh(r)}function hS(i,e){return{lo:i>>>0,hi:e>>>0}}function El(i,e){return{lo:i|0,hi:e|0}}function jh(i,e){return e=~e,i?i=~i+1:e+=1,El(i,e)}const Xh=i=>{const e=String(i);return"0000000".slice(e.length)+e};function $h(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function fS(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function pS(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Ct(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Ct(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Wh(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Wh(s)},dec(s,r){return uS(s,r)},uDec(s,r){return qh(s,r)}}}const Et=pS();var Y;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(Y||(Y={}));var Vi;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Vi||(Vi={}));function zi(i,e,t){if(e===t)return!0;if(i==Y.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==t}return!1}function Ys(i,e){switch(i){case Y.BOOL:return!1;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==0?Et.zero:"0";case Y.DOUBLE:case Y.FLOAT:return 0;case Y.BYTES:return new Uint8Array(0);case Y.STRING:return"";default:return 0}}function Kh(i,e){switch(i){case Y.BOOL:return e===!1;case Y.STRING:return e==="";case Y.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var kt;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(kt||(kt={}));class mS{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Sl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ga(e),$h(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){Bh(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){Sl(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ga(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ga(e),e=(e<<1^e>>31)>>>0,$h(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Et.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Et.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Et.enc(e);return Tl(t.lo,t.hi,this.buf),this}sint64(e){let t=Et.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Tl(s,r,this.buf),this}uint64(e){let t=Et.uEnc(e);return Tl(t.lo,t.hi,this.buf),this}}class gS{constructor(e,t){this.varint64=dS,this.uint32=fS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case kt.Varint:for(;this.buf[this.pos++]&128;);break;case kt.Bit64:this.pos+=4;case kt.Bit32:this.pos+=4;break;case kt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case kt.StartGroup:for(;;){const[r,o]=this.tag();if(o===kt.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Et.dec(...this.varint64())}uint64(){return Et.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Et.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Et.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Et.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 vS(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function Yh(i){const e=i.field.localName,t=Object.create(null);return t[e]=_S(i),[t,()=>t[e]]}function _S(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Ys(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function bS(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let Si="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Wa=[];for(let i=0;i<Si.length;i++)Wa[Si[i].charCodeAt(0)]=i;Wa[45]=Si.indexOf("+"),Wa[95]=Si.indexOf("/");const Jh={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=Wa[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
4470
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=Si[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=Si[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=Si[s|n>>6],e+=Si[n&63],t=0;break}return t&&(e+=Si[s],e+="=",t==1&&(e+="=")),e}};function yS(i,e,t){Qh(e,i);const n=e.runtime.bin.makeReadOptions(t),s=bS(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,o]=Yh(e);for(const a of s)e.runtime.bin.readField(r,n.readerFactory(a.data),e.field,a.wireType,n);return o()}function SS(i,e,t,n){Qh(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Zh(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Zh(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Qh(i,e){Ct(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function ef(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!Kh(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function tf(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Ys(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function xi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(xl.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function nf(i,e){return xi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}Y.DOUBLE,Y.FLOAT,Y.INT64,Y.UINT64,Y.INT32,Y.UINT32,Y.BOOL,Y.STRING,Y.BYTES;const sf={ignoreUnknownFields:!1},rf={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function xS(i){return i?Object.assign(Object.assign({},sf),i):sf}function TS(i){return i?Object.assign(Object.assign({},rf),i):rf}const qa=Symbol(),ja=Symbol();function ES(){return{makeReadOptions:xS,makeWriteOptions:TS,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(ei(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=i.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));s.set(c.oneof,o)}af(n,a,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=r.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=Yh(d);af(u,a,d.field,t,d),SS(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!ef(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!MS(s))continue}const o=s.oneof?i[s.oneof.localName].value:i[s.localName],a=of(s,o,e);a!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(i)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Zh(i,a)){const c=yS(i,a,e),l=of(a.field,c,e);l!==void 0&&(n[a.field.jsonName]=l)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return n},readScalar(i,e,t){return Fr(i,e,t??Vi.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Kh(i,e)))return Xa(i,e)},debug:ei}}function ei(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function af(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Ct(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e)));const o=i[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,n));break;case"enum":const c=Cl(t.T,a,n.ignoreUnknownFields,!0);c!==ja&&o.push(c);break;case"scalar":try{o.push(Fr(t.T,a,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e)));const o=i[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=CS(t.K,a)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":o[l]=t.V.T.fromJson(c,n);break;case"enum":const d=Cl(t.V.T,c,n.ignoreUnknownFields,!0);d!==ja&&(o[l]=d);break;case"scalar":try{o[l]=Fr(t.V.T,c,Vi.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=i[r];xi(a)?a.fromJson(e,n):(i[r]=a=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Cl(t.T,e,n.ignoreUnknownFields,!1);switch(c){case qa:tf(t,i);break;case ja:break;default:i[r]=c;break}break;case"scalar":try{const l=Fr(t.T,e,t.L,!1);switch(l){case qa:tf(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function CS(i,e){if(i===Y.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Fr(i,e,Vi.BIGINT,!0).toString()}function Fr(i,e,t,n){if(e===null)return n?Ys(i,t):qa;switch(i){case Y.DOUBLE:case Y.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==Y.FLOAT&&Bh(s),s;case Y.INT32:case Y.FIXED32:case Y.SFIXED32:case Y.SINT32:case Y.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==Y.UINT32||i==Y.FIXED32?Sl(r):Ga(r),r;case Y.INT64:case Y.SFIXED64:case Y.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Et.parse(e);return t?o.toString():o;case Y.FIXED64:case Y.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Et.uParse(e);return t?a.toString():a;case Y.BOOL:if(typeof e!="boolean")break;return e;case Y.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case Y.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Jh.dec(e)}throw new Error}function Cl(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:qa;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return ja;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(ei(e)))}function MS(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function of(i,e,t){if(i.kind=="map"){Ct(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[o,a]of s)n[o.toString()]=Xa(i.V.T,a);break;case"message":for(const[o,a]of s)n[o.toString()]=a.toJson(t);break;case"enum":const r=i.V.T;for(const[o,a]of s)n[o.toString()]=Ml(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Ct(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(Xa(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Ml(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return Xa(i.T,e);case"enum":return Ml(i.T,e,t.enumAsInteger);case"message":return nf(i.T,e).toJson(t)}}function Ml(i,e,t){var n;if(Ct(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function Xa(i,e){switch(i){case Y.INT32:case Y.SFIXED32:case Y.SINT32:case Y.FIXED32:case Y.UINT32:return Ct(typeof e=="number"),e;case Y.FLOAT:case Y.DOUBLE:return Ct(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case Y.STRING:return Ct(typeof e=="string"),e;case Y.BOOL:return Ct(typeof e=="boolean"),e;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return Ct(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case Y.BYTES:return Ct(e instanceof Uint8Array),Jh.enc(e)}}const Js=Symbol("@bufbuild/protobuf/unknown-fields"),cf={readUnknownFields:!0,readerFactory:i=>new gS(i)},lf={writeUnknownFields:!0,writerFactory:()=>new mS};function wS(i){return i?Object.assign(Object.assign({},cf),i):cf}function AS(i){return i?Object.assign(Object.assign({},lf),i):lf}function RS(){return{makeReadOptions:wS,makeWriteOptions:AS,listUnknownFields(i){var e;return(e=i[Js])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Js]},writeUnknownFields(i,e){const n=i[Js];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Js])||(s[Js]=[]),s[Js].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==kt.EndGroup));){const l=r.fields.find(a);if(!l){const d=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(i,a,c,d);continue}df(i,e,l,c,n)}if(s&&(c!=kt.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:df,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!ef(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];uf(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&uf(i,e,t,n)}}}function df(i,e,t,n,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?Y.INT32:t.T;let c=Ka;if(t.kind=="scalar"&&t.L>0&&(c=kS),r){let h=i[o];if(n==kt.LengthDelimited&&a!=Y.STRING&&a!=Y.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else i[o]=c(e,a);break;case"message":const l=t.T;r?i[o].push($a(e,new l,s,t)):xi(i[o])?$a(e,i[o],s,t):(i[o]=$a(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=l.fieldWrapper.unwrapField(i[o])));break;case"map":let[d,u]=PS(t,e,s);i[o][d]=u;break}}function $a(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function PS(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=Ka(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=Ka(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=$a(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ys(i.K,Vi.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Ys(i.V.T,Vi.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[r,o]}function kS(i,e){const t=Ka(i,e);return typeof t=="bigint"?t.toString():t}function Ka(i,e){switch(e){case Y.STRING:return i.string();case Y.BOOL:return i.bool();case Y.DOUBLE:return i.double();case Y.FLOAT:return i.float();case Y.INT32:return i.int32();case Y.INT64:return i.int64();case Y.UINT64:return i.uint64();case Y.FIXED64:return i.fixed64();case Y.BYTES:return i.bytes();case Y.FIXED32:return i.fixed32();case Y.SFIXED32:return i.sfixed32();case Y.SFIXED64:return i.sfixed64();case Y.SINT64:return i.sint64();case Y.UINT32:return i.uint32();case Y.SINT32:return i.sint32()}}function uf(i,e,t,n){Ct(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?Y.INT32:i.T;if(s)if(Ct(Array.isArray(e)),i.packed)DS(t,r,i.no,e);else for(const o of e)Br(t,r,i.no,o);else Br(t,r,i.no,e);break;case"message":if(s){Ct(Array.isArray(e));for(const o of e)hf(t,n,i,o)}else hf(t,n,i,e);break;case"map":Ct(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))IS(t,n,i,o,a);break}}function IS(i,e,t,n,s){i.tag(t.no,kt.LengthDelimited),i.fork();let r=n;switch(t.K){case Y.INT32:case Y.FIXED32:case Y.UINT32:case Y.SFIXED32:case Y.SINT32:r=Number.parseInt(n);break;case Y.BOOL:Ct(n=="true"||n=="false"),r=n=="true";break}switch(Br(i,t.K,1,r),t.V.kind){case"scalar":Br(i,t.V.T,2,s);break;case"enum":Br(i,Y.INT32,2,s);break;case"message":Ct(s!==void 0),i.tag(2,kt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function hf(i,e,t,n){const s=nf(t.T,n);t.delimited?i.tag(t.no,kt.StartGroup).raw(s.toBinary(e)).tag(t.no,kt.EndGroup):i.tag(t.no,kt.LengthDelimited).bytes(s.toBinary(e))}function Br(i,e,t,n){Ct(n!==void 0);let[s,r]=ff(e);i.tag(t,s)[r](n)}function DS(i,e,t,n){if(!n.length)return;i.tag(t,kt.LengthDelimited).fork();let[,s]=ff(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function ff(i){let e=kt.Varint;switch(i){case Y.BYTES:case Y.STRING:e=kt.LengthDelimited;break;case Y.DOUBLE:case Y.FIXED64:case Y.SFIXED64:e=kt.Bit64;break;case Y.FIXED32:case Y.SFIXED32:case Y.FLOAT:e=kt.Bit32;break}const t=Y[i].toLowerCase();return[e,t]}function LS(){return{setEnumType:zh,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!=null)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let l=o[s].value;c&&c.kind=="message"&&!xi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===Y.BYTES&&(l=Vr(l)),r[s]={case:a,value:l};break;case"scalar":case"enum":let d=o[s];n.T===Y.BYTES&&(d=n.repeated?d.map(Vr):Vr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Y.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=Vr(g);else Object.assign(r[s],o[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=o[s].map(h=>xi(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Vr(h):r[s]=h:r[s]=xi(h,u)?h:new u(h)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>zi(n.T,o,r[a]));case"enum":return s.every((o,a)=>zi(Y.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let o=s,a=r;return n.T.fieldWrapper&&(o!==void 0&&!xi(o)&&(o=n.T.fieldWrapper.wrapField(o)),a!==void 0&&!xi(a)&&(a=n.T.fieldWrapper.wrapField(a))),n.T.equals(o,a);case"enum":return zi(Y.INT32,s,r);case"scalar":return zi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return zi(Y.INT32,s.value,r.value);case"scalar":return zi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>zi(Y.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>zi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Ya);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Ya(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Ya(r.value)}:{case:void 0}:o=Ya(r);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ya(i){if(i===void 0)return i;if(xi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Vr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function NS(i,e,t){return{syntax:i,json:ES(),bin:RS(),util:Object.assign(Object.assign({},LS()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return lS(this,n,s,r)},makeEnum:cS,makeEnumType:Gh,getEnumType:oS,makeExtension(n,s,r){return vS(this,n,s,r)}}}class OS{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function pf(i,e){const t=mf(i);return e?t:GS(zS(t))}function US(i){return pf(i,!1)}const FS=mf;function mf(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const BS=new Set(["constructor","toString","toJSON","valueOf"]),VS=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),gf=i=>"".concat(i,"$"),zS=i=>VS.has(i)?gf(i):i,GS=i=>BS.has(i)?gf(i):i;class HS{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=US(e)}addField(e){Ct(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function WS(i,e){var t,n,s,r,o,a;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=pf(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:FS(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Vi.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=Y.BYTES&&d.T!=Y.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new HS(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const B=NS("proto3",i=>new OS(i,e=>WS(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Ys(e.T,e.L);break}}});class un extends xl{constructor(e){super(),this.seconds=Et.zero,this.nanos=0,B.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(B.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=Et.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return un.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new un({seconds:Et.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new un().fromBinary(e,t)}static fromJson(e,t){return new un().fromJson(e,t)}static fromJsonString(e,t){return new un().fromJsonString(e,t)}static equals(e,t){return B.util.equals(un,e,t)}}un.runtime=B,un.typeName="google.protobuf.Timestamp",un.fields=B.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const qS=B.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:jS,repeated:!0},{no:5,name:"events",kind:"message",T:$S,repeated:!0}]),jS=B.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:XS,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),XS=B.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"value",kind:"scalar",T:2}]),$S=B.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:un},{no:7,name:"normalized_end_timestamp",kind:"message",T:un,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),vf=B.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Bn=B.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Nt=B.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"}]),wl=B.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),zr=B.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Gr=B.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Vn=B.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),ms=B.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"}]),KS=B.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),qt=B.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),Ja=B.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:Za,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:kf}]),Za=B.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),YS=B.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:B.getEnumType(Nt),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}]),gs=B.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:B.getEnumType(Zs)},{no:4,name:"tracks",kind:"message",T:Qs,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:YS},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:B.getEnumType(Hr)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:B.getEnumType(Vn)},{no:18,name:"kind_details",kind:"enum",T:B.getEnumType(JS),repeated:!0}]),Zs=B.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Hr=B.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),JS=B.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Gt=B.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ZS=B.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:Gi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:B.getEnumType(_f)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Qs=B.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:B.getEnumType(Bn)},{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:B.getEnumType(Nt)},{no:10,name:"layers",kind:"message",T:Gi,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:ZS,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:B.getEnumType(Gt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:kf},{no:19,name:"audio_features",kind:"enum",T:B.getEnumType(qt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:B.getEnumType(vf)}]),Gi=B.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:B.getEnumType(wl)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),_f=B.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),an=B.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:B.getEnumType(je)},{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:Al,oneof:"value"},{no:3,name:"speaker",kind:"message",T:QS,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:xf,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ex,oneof:"value"},{no:8,name:"metrics",kind:"message",T:qS,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Qa,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Rl,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Pl,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:kl,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:eo,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:to,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:no,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:bf,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),je=B.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),bf=B.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:B.getEnumType(Gt)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),yf=B.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Al,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Qa,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Rl,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Pl,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:kl,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:eo,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:to,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:no,oneof:"value"}]),QS=B.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Sf,repeated:!0}]),Sf=B.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}]),Al=B.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}]),xf=B.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),ex=B.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:tx,repeated:!0}]),tx=B.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}]),Qa=B.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}]),Rl=B.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}]),Pl=B.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),kl=B.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:Tf,oneof:"value"}]),Tf=B.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}]),Ef=B.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Cf=B.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:B.getEnumType(Mf)},{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}]),Mf=B.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),wf=B.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:B.getEnumType(Af)},{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}]),Af=B.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Rf=B.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Pf},{no:2,name:"screen",kind:"message",T:Pf},{no:3,name:"resume_connection",kind:"enum",T:B.getEnumType(Gr)},{no:4,name:"disabled_codecs",kind:"message",T:nx},{no:5,name:"force_relay",kind:"enum",T:B.getEnumType(Gr)}]),Pf=B.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:B.getEnumType(Gr)}]),nx=B.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Za,repeated:!0},{no:2,name:"publish",kind:"message",T:Za,repeated:!0}]),kf=B.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Il=B.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),If=B.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:B.getEnumType(Il)},{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"}),Df=B.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),eo=B.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:B.getEnumType(Gt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:If,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Df,oneof:"content_header"}],{localName:"DataStream_Header"}),to=B.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"}),no=B.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"}),ix=B.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),zn=B.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Dl=B.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),sx=B.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),rx=B.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Hi,oneof:"message"},{no:2,name:"answer",kind:"message",T:Hi,oneof:"message"},{no:3,name:"trickle",kind:"message",T:io,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Wr,oneof:"message"},{no:5,name:"mute",kind:"message",T:so,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ro,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Nf,oneof:"message"},{no:8,name:"leave",kind:"message",T:ao,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Uf,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Vf,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Bl,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ti,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ul,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Hf,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Ol,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Of,oneof:"message"}]),Lf=B.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:ax,oneof:"message"},{no:2,name:"answer",kind:"message",T:Hi,oneof:"message"},{no:3,name:"offer",kind:"message",T:Hi,oneof:"message"},{no:4,name:"trickle",kind:"message",T:io,oneof:"message"},{no:5,name:"update",kind:"message",T:lx,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Nl,oneof:"message"},{no:8,name:"leave",kind:"message",T:ao,oneof:"message"},{no:9,name:"mute",kind:"message",T:so,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:dx,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ux,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:fx,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:mx,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:vx,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:bx,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:cx,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ox,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Sx,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ex,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Cx,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Mx,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:yx,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Px,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:_x,oneof:"message"}]),Ll=B.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Gi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:B.getEnumType(_f)}]),Wr=B.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:B.getEnumType(Bn)},{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:B.getEnumType(Nt)},{no:9,name:"layers",kind:"message",T:Gi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Ll,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:B.getEnumType(Gt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:B.getEnumType(vf)},{no:17,name:"audio_features",kind:"enum",T:B.getEnumType(qt),repeated:!0}]),io=B.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:B.getEnumType(zn)},{no:3,name:"final",kind:"scalar",T:8}]),so=B.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),ax=B.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ja},{no:2,name:"participant",kind:"message",T:gs},{no:3,name:"other_participants",kind:"message",T:gs,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ff,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:Rf},{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:Cf},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Za,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ox=B.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Ff,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Rf},{no:3,name:"server_info",kind:"message",T:Cf},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Nl=B.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Qs}]),cx=B.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Hi=B.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),lx=B.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:gs,repeated:!0}]),ro=B.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:Ef,repeated:!0}]),Nf=B.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:B.getEnumType(wl)},{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}]),Ol=B.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:B.getEnumType(qt),repeated:!0}]),Of=B.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}]),ao=B.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:B.getEnumType(Vn)},{no:3,name:"action",kind:"enum",T:B.getEnumType(er)},{no:4,name:"regions",kind:"message",T:xx}]),er=B.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Uf=B.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Gi,repeated:!0}]),Ul=B.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}]),Ff=B.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}]),dx=B.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Sf,repeated:!0}]),ux=B.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ja}]),hx=B.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:B.getEnumType(zr)},{no:3,name:"score",kind:"scalar",T:2}]),fx=B.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:hx,repeated:!0}]),px=B.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:B.getEnumType(Dl)}]),mx=B.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:px,repeated:!0}]),Fl=B.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:B.getEnumType(wl)},{no:2,name:"enabled",kind:"scalar",T:8}]),gx=B.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Fl,repeated:!0}]),vx=B.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Fl,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:gx,repeated:!0}]),_x=B.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:ix,repeated:!0}]),Bf=B.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}]),Vf=B.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Bf,repeated:!0}]),bx=B.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}]),yx=B.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Ja},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:gs},{no:4,name:"other_participants",kind:"message",T:gs,repeated:!0}]),Bl=B.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Hi},{no:2,name:"subscription",kind:"message",T:ro},{no:3,name:"publish_tracks",kind:"message",T:Nl,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Gf,repeated:!0},{no:5,name:"offer",kind:"message",T:Hi},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:zf,repeated:!0}]),zf=B.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Gf=B.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:B.getEnumType(zn)}]),ti=B.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:B.getEnumType(sx),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"}]),Hf=B.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Sx=B.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),xx=B.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Tx,repeated:!0}]),Tx=B.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}]),Ex=B.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:B.getEnumType(KS)}]),Cx=B.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:B.getEnumType(Vl)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:io,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Wr,oneof:"request"},{no:6,name:"mute",kind:"message",T:so,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Ul,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Ol,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Of,oneof:"request"}]),Vl=B.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),Mx=B.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Wf=B.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),wx=B.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:wf},{no:2,name:"connection_settings",kind:"message",T:Wf},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Wr,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Hi},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:B.getEnumType(ms)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Bl}]),Ax=B.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:B.getEnumType(Rx)},{no:2,name:"join_request",kind:"scalar",T:12}]),Rx=B.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Px=B.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function kx(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var oo={exports:{}},Ix=oo.exports,qf;function Dx(){return qf||(qf=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Ix,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,T,C,_,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function E(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function w(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,U=encodeURIComponent(S),q=O.indexOf(U+"=");q!==-1&&(R=/^([^;]+)/.exec(O.slice(q+U.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function y(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return _??C??T},p.setLevel=function(R,O){return _=y(R),O!==!1&&E(_),d.call(p)},p.setDefaultLevel=function(R){C=y(R),w()||p.setLevel(R,!1)},p.resetLevel=function(){_=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(o!==p&&(T=y(o.getLevel())),d.call(p),o===p)for(var R in r)r[R].rebuild()},T=y(o?o.getLevel():"WARN");var x=w();x!=null&&(_=y(x)),d.call(p)}o=new f,o.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,o.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(oo)),oo.exports}var co=Dx(),zl;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(zl||(zl={}));var Gn;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(Gn||(Gn={}));let ze=co.getLogger("livekit");Object.values(Gn).map(i=>co.getLogger(i)),ze.setDefaultLevel(zl.info);function Ti(i){const e=co.getLogger(i);return e.setDefaultLevel(ze.getLevel()),e}const Lx=co.getLogger("lk-e2ee"),qr=7e3,Nx=[0,300,4*300,9*300,16*300,qr,qr,qr,qr,qr];class Ox{constructor(e){this._retryDelays=e!==void 0?[...e]:Nx}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Ux(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function P(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?r(d.value):s(d.value).then(a,c)}l((n=n.apply(i,e||[])).next())})}function jf(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ei(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof jf=="function"?jf(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(l){r({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var lo={exports:{}},Xf;function Fx(){if(Xf)return lo.exports;Xf=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,E,w){return Function.prototype.apply.call(S,E,w)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(_){console&&console.warn&&console.warn(_)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}lo.exports=r,lo.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(_){if(typeof _!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof _)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(_){if(typeof _!="number"||_<0||s(_))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+_+".");o=_}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(_){return _._maxListeners===void 0?r.defaultMaxListeners:_._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var E=[],w=1;w<arguments.length;w++)E.push(arguments[w]);var k=S==="error",y=this._events;if(y!==void 0)k=k&&y.error===void 0;else if(!k)return!1;if(k){var x;if(E.length>0&&(x=E[0]),x instanceof Error)throw x;var R=new Error("Unhandled error."+(x?" ("+x.message+")":""));throw R.context=x,R}var O=y[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,E);else for(var U=O.length,q=g(O,U),w=0;w<U;++w)e(q[w],this,E);return!0};function l(_,S,E,w){var k,y,x;if(a(E),y=_._events,y===void 0?(y=_._events=Object.create(null),_._eventsCount=0):(y.newListener!==void 0&&(_.emit("newListener",S,E.listener?E.listener:E),y=_._events),x=y[S]),x===void 0)x=y[S]=E,++_._eventsCount;else if(typeof x=="function"?x=y[S]=w?[E,x]:[x,E]:w?x.unshift(E):x.push(E),k=c(_),k>0&&x.length>k&&!x.warned){x.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=_,R.type=S,R.count=x.length,n(R)}return _}r.prototype.addListener=function(S,E){return l(this,S,E,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,E){return l(this,S,E,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(_,S,E){var w={fired:!1,wrapFn:void 0,target:_,type:S,listener:E},k=d.bind(w);return k.listener=E,w.wrapFn=k,k}r.prototype.once=function(S,E){return a(E),this.on(S,u(this,S,E)),this},r.prototype.prependOnceListener=function(S,E){return a(E),this.prependListener(S,u(this,S,E)),this},r.prototype.removeListener=function(S,E){var w,k,y,x,R;if(a(E),k=this._events,k===void 0)return this;if(w=k[S],w===void 0)return this;if(w===E||w.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,w.listener||E));else if(typeof w!="function"){for(y=-1,x=w.length-1;x>=0;x--)if(w[x]===E||w[x].listener===E){R=w[x].listener,y=x;break}if(y<0)return this;y===0?w.shift():v(w,y),w.length===1&&(k[S]=w[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var E,w,k;if(w=this._events,w===void 0)return this;if(w.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):w[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete w[S]),this;if(arguments.length===0){var y=Object.keys(w),x;for(k=0;k<y.length;++k)x=y[k],x!=="removeListener"&&this.removeAllListeners(x);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=w[S],typeof E=="function")this.removeListener(S,E);else if(E!==void 0)for(k=E.length-1;k>=0;k--)this.removeListener(S,E[k]);return this};function h(_,S,E){var w=_._events;if(w===void 0)return[];var k=w[S];return k===void 0?[]:typeof k=="function"?E?[k.listener||k]:[k]:E?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(_,S){return typeof _.listenerCount=="function"?_.listenerCount(S):f.call(_,S)},r.prototype.listenerCount=f;function f(_){var S=this._events;if(S!==void 0){var E=S[_];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(_,S){for(var E=new Array(S),w=0;w<S;++w)E[w]=_[w];return E}function v(_,S){for(;S+1<_.length;S++)_[S]=_[S+1];_.pop()}function m(_){for(var S=new Array(_.length),E=0;E<S.length;++E)S[E]=_[E].listener||_[E];return S}function p(_,S){return new Promise(function(E,w){function k(x){_.removeListener(S,y),w(x)}function y(){typeof _.removeListener=="function"&&_.removeListener("error",k),E([].slice.call(arguments))}C(_,S,y,{once:!0}),S!=="error"&&T(_,k,{once:!0})})}function T(_,S,E){typeof _.on=="function"&&C(_,"error",S,E)}function C(_,S,E,w){if(typeof _.on=="function")w.once?_.once(S,E):_.on(S,E);else if(typeof _.addEventListener=="function")_.addEventListener(S,function k(y){w.once&&_.removeEventListener(S,k),E(y)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof _)}return lo.exports}var ni=Fx();let $f=!0,Kf=!0;function jr(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function vs(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Bx(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):($f=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Vx(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Kf=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Yf(){if(typeof window=="object"){if($f)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gl(i,e){Kf&&console.warn(i+" is deprecated, please use "+e+" instead.")}function zx(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(jr(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(jr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(jr(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=jr(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Jf(i){return Object.prototype.toString.call(i)==="[object Object]"}function Zf(i){return Jf(i)?Object.keys(i).reduce(function(e,t){const n=Jf(i[t]),s=n?Zf(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function Hl(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Hl(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{Hl(i,i.get(s),t)})}))}function Qf(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&Hl(i,a,s)})}),s}const ep=Yf;function tp(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),ep("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return ep("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){s(a,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function np(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function ip(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else vs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function sp(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function rp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Qf(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),vs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Qf(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function ap(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function op(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ap(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Wl(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function cp(i,e){vs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var lp=Object.freeze({__proto__:null,fixNegotiationNeeded:cp,shimAddTrackRemoveTrack:op,shimAddTrackRemoveTrackWithNative:ap,shimGetSendersWithDtmf:sp,shimGetUserMedia:tp,shimMediaStream:np,shimOnTrack:ip,shimPeerConnection:Wl,shimSenderReceiverGetStats:rp});function dp(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Gl("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Gx(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function up(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ql(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(o,a)}}function hp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function fp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),vs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function pp(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Gl("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function mp(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function gp(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function vp(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function _p(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function bp(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var yp=Object.freeze({__proto__:null,shimAddTransceiver:gp,shimCreateAnswer:bp,shimCreateOffer:_p,shimGetDisplayMedia:Gx,shimGetParameters:vp,shimGetUserMedia:dp,shimOnTrack:up,shimPeerConnection:ql,shimRTCDataChannel:mp,shimReceiverGetStats:fp,shimRemoveStream:pp,shimSenderGetStats:hp});function Sp(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function xp(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function Tp(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Ep(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Cp(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Cp(i){return i&&i.video!==void 0?Object.assign({},i,{video:Zf(i.video)}):i}function Mp(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Gl("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function wp(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ap(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Rp(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Pp=Object.freeze({__proto__:null,shimAudioContext:Rp,shimCallbacksAPI:Tp,shimConstraints:Cp,shimCreateOfferLegacy:Ap,shimGetUserMedia:Ep,shimLocalStreamsAPI:Sp,shimRTCIceServerUrls:Mp,shimRemoteStreamsAPI:xp,shimTrackEventTransceiver:wp}),jl={exports:{}},kp;function Hx(){return kp||(kp=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
4469
+ `,ps={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},Zy={size:1,segments:128,colors:ps,morphStrength:1,noiseScale:1.5,noiseSpeed:.3,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:3,audioSmoothing:.9,idleMorphMultiplier:.25,colorContrast:1.5};class yl{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.canvasPadding=3,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const a=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=a,this.orbMaterial.uniforms.uAudioBass.value=this.audioValues.bass,this.orbMaterial.uniforms.uAudioMid.value=this.audioValues.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.audioValues.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const c=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,l=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(c-l)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=a,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const c=this.isActive?this.config.glowIntensity*1.2:this.config.glowIntensity*this.config.idleGlowMultiplier,l=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(c-l)*.05}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const a=this.container.clientWidth*this.canvasPadding,c=this.container.clientHeight*this.canvasPadding;this.camera.aspect=a/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,c)},this.handleMouseMove=a=>{const c=this.container.getBoundingClientRect(),l=(a.clientX-c.left)/c.width*2-1,d=-((a.clientY-c.top)/c.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=l*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...Zy,...t},this.clock=new Dv,this.scene=new Tv;const n=e.clientWidth*this.canvasPadding,s=e.clientHeight*this.canvasPadding,r=n/s;this.camera=new wn(45,r,.1,100),this.camera.position.z=9,this.renderer=new Ky({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(n,s),this.renderer.setClearColor(0,0);const o=this.renderer.domElement;o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.transform="translate(-50%, -50%)",o.style.pointerEvents="none",e.appendChild(o),this.createOrb(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}createOrb(){const e={...ps,...this.config.colors},t=new dl(this.config.size,this.config.segments/4);this.orbMaterial=new Mn({vertexShader:Dh,fragmentShader:Lh,uniforms:{uTime:{value:0},uAudioBass:{value:0},uAudioMid:{value:0},uAudioTreble:{value:0},uAudioLevel:{value:0},uMorphStrength:{value:this.config.morphStrength},uNoiseScale:{value:this.config.noiseScale},uNoiseSpeed:{value:this.config.noiseSpeed},uAudioReactivity:{value:this.config.audioReactivity},uColorPrimary:{value:new Je(e.primary)},uColorSecondary:{value:new Je(e.secondary)},uColorAccent:{value:new Je(e.accent)},uColorDepth:{value:new Je(e.depth||ps.depth)},uColorHighlight:{value:new Je(e.highlight||ps.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:ci}),this.orb=new Fn(t,this.orbMaterial),this.scene.add(this.orb);const n=new ul(this.config.size,64,64);this.glowMaterial=new Mn({vertexShader:Nh,fragmentShader:Oh,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Je(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:en,blending:No,depthWrite:!1}),this.glowMesh=new Fn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...ps,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||ps.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||ps.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb)),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh)),this.orbMaterial&&this.orbMaterial.dispose(),this.glowMaterial&&this.glowMaterial.dispose(),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}class Uh{constructor(e={}){this.audioContext=null,this.analyser=null,this.source=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async connectStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect(),this.source=this.audioContext.createMediaStreamSource(e),this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,this.source.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}async connectAudioElement(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect();const t=this.audioContext.createMediaElementSource(e);this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,t.connect(this.analyser),this.analyser.connect(this.audioContext.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let o=0,a=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?o+=f:h<r?a+=f:c+=f}const l=s>0?o/s:0,d=r-s>0?a/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){this.source&&(this.source.disconnect(),this.source=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}function Qy(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var eS=Object.defineProperty,tS=(i,e,t)=>e in i?eS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Fh=(i,e,t)=>tS(i,typeof e!="symbol"?e+"":e,t);class rn{constructor(){Fh(this,"_locking"),Fh(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Ct(i,e){if(!i)throw new Error(e)}const nS=34028234663852886e22,iS=-34028234663852886e22,sS=4294967295,rS=2147483647,aS=-2147483648;function za(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>rS||i<aS)throw new Error("invalid int 32: "+i)}function Sl(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>sS||i<0)throw new Error("invalid uint 32: "+i)}function Bh(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>nS||i<iS))throw new Error("invalid float 32: "+i)}const Vh=Symbol("@bufbuild/protobuf/enum-type");function oS(i){const e=i[Vh];return Ct(e,"missing enum type on enum object"),e}function zh(i,e,t,n){i[Vh]=Gh(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Gh(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=Hh(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function cS(i,e,t){const n={};for(const s of e){const r=Hh(s);n[r.localName]=r.no,n[r.no]=r.localName}return zh(n,i,e),n}function Hh(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class xl{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function lS(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new xl),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function dS(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Tl(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Ga=4294967296;function Wh(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Ga&&(s=s+(n/Ga|0),n=n%Ga)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?jh(n,s):El(n,s)}function uS(i,e){let t=El(i,e);const n=t.hi&2147483648;n&&(t=jh(t.lo,t.hi));const s=qh(t.lo,t.hi);return n?"-"+s:s}function qh(i,e){if({lo:i,hi:e}=hS(i,e),e<=2097151)return String(Ga*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Xh(o)+Xh(r)}function hS(i,e){return{lo:i>>>0,hi:e>>>0}}function El(i,e){return{lo:i|0,hi:e|0}}function jh(i,e){return e=~e,i?i=~i+1:e+=1,El(i,e)}const Xh=i=>{const e=String(i);return"0000000".slice(e.length)+e};function $h(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function fS(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function pS(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Ct(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Ct(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Wh(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Wh(s)},dec(s,r){return uS(s,r)},uDec(s,r){return qh(s,r)}}}const Et=pS();var Y;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(Y||(Y={}));var Vi;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Vi||(Vi={}));function zi(i,e,t){if(e===t)return!0;if(i==Y.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==t}return!1}function Ks(i,e){switch(i){case Y.BOOL:return!1;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==0?Et.zero:"0";case Y.DOUBLE:case Y.FLOAT:return 0;case Y.BYTES:return new Uint8Array(0);case Y.STRING:return"";default:return 0}}function Kh(i,e){switch(i){case Y.BOOL:return e===!1;case Y.STRING:return e==="";case Y.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var kt;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(kt||(kt={}));class mS{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Sl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return za(e),$h(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){Bh(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){Sl(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){za(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return za(e),e=(e<<1^e>>31)>>>0,$h(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Et.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Et.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Et.enc(e);return Tl(t.lo,t.hi,this.buf),this}sint64(e){let t=Et.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Tl(s,r,this.buf),this}uint64(e){let t=Et.uEnc(e);return Tl(t.lo,t.hi,this.buf),this}}class gS{constructor(e,t){this.varint64=dS,this.uint32=fS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case kt.Varint:for(;this.buf[this.pos++]&128;);break;case kt.Bit64:this.pos+=4;case kt.Bit32:this.pos+=4;break;case kt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case kt.StartGroup:for(;;){const[r,o]=this.tag();if(o===kt.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Et.dec(...this.varint64())}uint64(){return Et.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Et.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Et.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Et.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 vS(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function Yh(i){const e=i.field.localName,t=Object.create(null);return t[e]=_S(i),[t,()=>t[e]]}function _S(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Ks(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function bS(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let Si="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ha=[];for(let i=0;i<Si.length;i++)Ha[Si[i].charCodeAt(0)]=i;Ha[45]=Si.indexOf("+"),Ha[95]=Si.indexOf("/");const Jh={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=Ha[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
4470
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=Si[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=Si[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=Si[s|n>>6],e+=Si[n&63],t=0;break}return t&&(e+=Si[s],e+="=",t==1&&(e+="=")),e}};function yS(i,e,t){Qh(e,i);const n=e.runtime.bin.makeReadOptions(t),s=bS(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,o]=Yh(e);for(const a of s)e.runtime.bin.readField(r,n.readerFactory(a.data),e.field,a.wireType,n);return o()}function SS(i,e,t,n){Qh(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Zh(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Zh(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Qh(i,e){Ct(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function ef(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!Kh(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function tf(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Ks(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function xi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(xl.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function nf(i,e){return xi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}Y.DOUBLE,Y.FLOAT,Y.INT64,Y.UINT64,Y.INT32,Y.UINT32,Y.BOOL,Y.STRING,Y.BYTES;const sf={ignoreUnknownFields:!1},rf={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function xS(i){return i?Object.assign(Object.assign({},sf),i):sf}function TS(i){return i?Object.assign(Object.assign({},rf),i):rf}const Wa=Symbol(),qa=Symbol();function ES(){return{makeReadOptions:xS,makeWriteOptions:TS,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(ei(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=i.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));s.set(c.oneof,o)}af(n,a,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=r.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=Yh(d);af(u,a,d.field,t,d),SS(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!ef(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!MS(s))continue}const o=s.oneof?i[s.oneof.localName].value:i[s.localName],a=of(s,o,e);a!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(i)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Zh(i,a)){const c=yS(i,a,e),l=of(a.field,c,e);l!==void 0&&(n[a.field.jsonName]=l)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return n},readScalar(i,e,t){return Fr(i,e,t??Vi.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Kh(i,e)))return ja(i,e)},debug:ei}}function ei(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function af(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Ct(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e)));const o=i[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,n));break;case"enum":const c=Cl(t.T,a,n.ignoreUnknownFields,!0);c!==qa&&o.push(c);break;case"scalar":try{o.push(Fr(t.T,a,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e)));const o=i[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=CS(t.K,a)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":o[l]=t.V.T.fromJson(c,n);break;case"enum":const d=Cl(t.V.T,c,n.ignoreUnknownFields,!0);d!==qa&&(o[l]=d);break;case"scalar":try{o[l]=Fr(t.V.T,c,Vi.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=i[r];xi(a)?a.fromJson(e,n):(i[r]=a=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Cl(t.T,e,n.ignoreUnknownFields,!1);switch(c){case Wa:tf(t,i);break;case qa:break;default:i[r]=c;break}break;case"scalar":try{const l=Fr(t.T,e,t.L,!1);switch(l){case Wa:tf(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(ei(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function CS(i,e){if(i===Y.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Fr(i,e,Vi.BIGINT,!0).toString()}function Fr(i,e,t,n){if(e===null)return n?Ks(i,t):Wa;switch(i){case Y.DOUBLE:case Y.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==Y.FLOAT&&Bh(s),s;case Y.INT32:case Y.FIXED32:case Y.SFIXED32:case Y.SINT32:case Y.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==Y.UINT32||i==Y.FIXED32?Sl(r):za(r),r;case Y.INT64:case Y.SFIXED64:case Y.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Et.parse(e);return t?o.toString():o;case Y.FIXED64:case Y.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Et.uParse(e);return t?a.toString():a;case Y.BOOL:if(typeof e!="boolean")break;return e;case Y.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case Y.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Jh.dec(e)}throw new Error}function Cl(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:Wa;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return qa;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(ei(e)))}function MS(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function of(i,e,t){if(i.kind=="map"){Ct(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[o,a]of s)n[o.toString()]=ja(i.V.T,a);break;case"message":for(const[o,a]of s)n[o.toString()]=a.toJson(t);break;case"enum":const r=i.V.T;for(const[o,a]of s)n[o.toString()]=Ml(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Ct(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(ja(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Ml(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return ja(i.T,e);case"enum":return Ml(i.T,e,t.enumAsInteger);case"message":return nf(i.T,e).toJson(t)}}function Ml(i,e,t){var n;if(Ct(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function ja(i,e){switch(i){case Y.INT32:case Y.SFIXED32:case Y.SINT32:case Y.FIXED32:case Y.UINT32:return Ct(typeof e=="number"),e;case Y.FLOAT:case Y.DOUBLE:return Ct(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case Y.STRING:return Ct(typeof e=="string"),e;case Y.BOOL:return Ct(typeof e=="boolean"),e;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return Ct(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case Y.BYTES:return Ct(e instanceof Uint8Array),Jh.enc(e)}}const Ys=Symbol("@bufbuild/protobuf/unknown-fields"),cf={readUnknownFields:!0,readerFactory:i=>new gS(i)},lf={writeUnknownFields:!0,writerFactory:()=>new mS};function wS(i){return i?Object.assign(Object.assign({},cf),i):cf}function AS(i){return i?Object.assign(Object.assign({},lf),i):lf}function RS(){return{makeReadOptions:wS,makeWriteOptions:AS,listUnknownFields(i){var e;return(e=i[Ys])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Ys]},writeUnknownFields(i,e){const n=i[Ys];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Ys])||(s[Ys]=[]),s[Ys].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==kt.EndGroup));){const l=r.fields.find(a);if(!l){const d=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(i,a,c,d);continue}df(i,e,l,c,n)}if(s&&(c!=kt.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:df,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!ef(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];uf(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&uf(i,e,t,n)}}}function df(i,e,t,n,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?Y.INT32:t.T;let c=$a;if(t.kind=="scalar"&&t.L>0&&(c=kS),r){let h=i[o];if(n==kt.LengthDelimited&&a!=Y.STRING&&a!=Y.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else i[o]=c(e,a);break;case"message":const l=t.T;r?i[o].push(Xa(e,new l,s,t)):xi(i[o])?Xa(e,i[o],s,t):(i[o]=Xa(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=l.fieldWrapper.unwrapField(i[o])));break;case"map":let[d,u]=PS(t,e,s);i[o][d]=u;break}}function Xa(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function PS(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=$a(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=$a(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Xa(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ks(i.K,Vi.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Ks(i.V.T,Vi.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[r,o]}function kS(i,e){const t=$a(i,e);return typeof t=="bigint"?t.toString():t}function $a(i,e){switch(e){case Y.STRING:return i.string();case Y.BOOL:return i.bool();case Y.DOUBLE:return i.double();case Y.FLOAT:return i.float();case Y.INT32:return i.int32();case Y.INT64:return i.int64();case Y.UINT64:return i.uint64();case Y.FIXED64:return i.fixed64();case Y.BYTES:return i.bytes();case Y.FIXED32:return i.fixed32();case Y.SFIXED32:return i.sfixed32();case Y.SFIXED64:return i.sfixed64();case Y.SINT64:return i.sint64();case Y.UINT32:return i.uint32();case Y.SINT32:return i.sint32()}}function uf(i,e,t,n){Ct(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?Y.INT32:i.T;if(s)if(Ct(Array.isArray(e)),i.packed)DS(t,r,i.no,e);else for(const o of e)Br(t,r,i.no,o);else Br(t,r,i.no,e);break;case"message":if(s){Ct(Array.isArray(e));for(const o of e)hf(t,n,i,o)}else hf(t,n,i,e);break;case"map":Ct(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))IS(t,n,i,o,a);break}}function IS(i,e,t,n,s){i.tag(t.no,kt.LengthDelimited),i.fork();let r=n;switch(t.K){case Y.INT32:case Y.FIXED32:case Y.UINT32:case Y.SFIXED32:case Y.SINT32:r=Number.parseInt(n);break;case Y.BOOL:Ct(n=="true"||n=="false"),r=n=="true";break}switch(Br(i,t.K,1,r),t.V.kind){case"scalar":Br(i,t.V.T,2,s);break;case"enum":Br(i,Y.INT32,2,s);break;case"message":Ct(s!==void 0),i.tag(2,kt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function hf(i,e,t,n){const s=nf(t.T,n);t.delimited?i.tag(t.no,kt.StartGroup).raw(s.toBinary(e)).tag(t.no,kt.EndGroup):i.tag(t.no,kt.LengthDelimited).bytes(s.toBinary(e))}function Br(i,e,t,n){Ct(n!==void 0);let[s,r]=ff(e);i.tag(t,s)[r](n)}function DS(i,e,t,n){if(!n.length)return;i.tag(t,kt.LengthDelimited).fork();let[,s]=ff(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function ff(i){let e=kt.Varint;switch(i){case Y.BYTES:case Y.STRING:e=kt.LengthDelimited;break;case Y.DOUBLE:case Y.FIXED64:case Y.SFIXED64:e=kt.Bit64;break;case Y.FIXED32:case Y.SFIXED32:case Y.FLOAT:e=kt.Bit32;break}const t=Y[i].toLowerCase();return[e,t]}function LS(){return{setEnumType:zh,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!=null)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let l=o[s].value;c&&c.kind=="message"&&!xi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===Y.BYTES&&(l=Vr(l)),r[s]={case:a,value:l};break;case"scalar":case"enum":let d=o[s];n.T===Y.BYTES&&(d=n.repeated?d.map(Vr):Vr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Y.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=Vr(g);else Object.assign(r[s],o[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=o[s].map(h=>xi(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Vr(h):r[s]=h:r[s]=xi(h,u)?h:new u(h)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>zi(n.T,o,r[a]));case"enum":return s.every((o,a)=>zi(Y.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let o=s,a=r;return n.T.fieldWrapper&&(o!==void 0&&!xi(o)&&(o=n.T.fieldWrapper.wrapField(o)),a!==void 0&&!xi(a)&&(a=n.T.fieldWrapper.wrapField(a))),n.T.equals(o,a);case"enum":return zi(Y.INT32,s,r);case"scalar":return zi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return zi(Y.INT32,s.value,r.value);case"scalar":return zi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>zi(Y.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>zi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Ka);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Ka(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Ka(r.value)}:{case:void 0}:o=Ka(r);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ka(i){if(i===void 0)return i;if(xi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Vr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function NS(i,e,t){return{syntax:i,json:ES(),bin:RS(),util:Object.assign(Object.assign({},LS()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return lS(this,n,s,r)},makeEnum:cS,makeEnumType:Gh,getEnumType:oS,makeExtension(n,s,r){return vS(this,n,s,r)}}}class OS{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function pf(i,e){const t=mf(i);return e?t:GS(zS(t))}function US(i){return pf(i,!1)}const FS=mf;function mf(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const BS=new Set(["constructor","toString","toJSON","valueOf"]),VS=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),gf=i=>"".concat(i,"$"),zS=i=>VS.has(i)?gf(i):i,GS=i=>BS.has(i)?gf(i):i;class HS{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=US(e)}addField(e){Ct(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function WS(i,e){var t,n,s,r,o,a;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=pf(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:FS(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Vi.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=Y.BYTES&&d.T!=Y.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new HS(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const B=NS("proto3",i=>new OS(i,e=>WS(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Ks(e.T,e.L);break}}});class un extends xl{constructor(e){super(),this.seconds=Et.zero,this.nanos=0,B.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(B.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=Et.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return un.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new un({seconds:Et.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new un().fromBinary(e,t)}static fromJson(e,t){return new un().fromJson(e,t)}static fromJsonString(e,t){return new un().fromJsonString(e,t)}static equals(e,t){return B.util.equals(un,e,t)}}un.runtime=B,un.typeName="google.protobuf.Timestamp",un.fields=B.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const qS=B.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:jS,repeated:!0},{no:5,name:"events",kind:"message",T:$S,repeated:!0}]),jS=B.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:XS,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),XS=B.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"value",kind:"scalar",T:2}]),$S=B.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:un},{no:7,name:"normalized_end_timestamp",kind:"message",T:un,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),vf=B.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Bn=B.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Nt=B.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"}]),wl=B.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),zr=B.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Gr=B.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Vn=B.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),ms=B.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"}]),KS=B.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),qt=B.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),Ya=B.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:Ja,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:kf}]),Ja=B.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),YS=B.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:B.getEnumType(Nt),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}]),gs=B.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:B.getEnumType(Js)},{no:4,name:"tracks",kind:"message",T:Zs,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:YS},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:B.getEnumType(Hr)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:B.getEnumType(Vn)},{no:18,name:"kind_details",kind:"enum",T:B.getEnumType(JS),repeated:!0}]),Js=B.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Hr=B.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),JS=B.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),zt=B.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ZS=B.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:Gi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:B.getEnumType(_f)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Zs=B.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:B.getEnumType(Bn)},{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:B.getEnumType(Nt)},{no:10,name:"layers",kind:"message",T:Gi,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:ZS,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:B.getEnumType(zt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:kf},{no:19,name:"audio_features",kind:"enum",T:B.getEnumType(qt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:B.getEnumType(vf)}]),Gi=B.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:B.getEnumType(wl)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),_f=B.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),an=B.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:B.getEnumType(je)},{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:Al,oneof:"value"},{no:3,name:"speaker",kind:"message",T:QS,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:xf,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ex,oneof:"value"},{no:8,name:"metrics",kind:"message",T:qS,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Za,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Rl,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Pl,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:kl,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Qa,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:eo,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:to,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:bf,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),je=B.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),bf=B.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:B.getEnumType(zt)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),yf=B.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Al,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Za,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Rl,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Pl,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:kl,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Qa,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:eo,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:to,oneof:"value"}]),QS=B.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Sf,repeated:!0}]),Sf=B.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}]),Al=B.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}]),xf=B.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),ex=B.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:tx,repeated:!0}]),tx=B.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}]),Za=B.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}]),Rl=B.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}]),Pl=B.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),kl=B.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:Tf,oneof:"value"}]),Tf=B.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}]),Ef=B.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Cf=B.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:B.getEnumType(Mf)},{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}]),Mf=B.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),wf=B.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:B.getEnumType(Af)},{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}]),Af=B.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Rf=B.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Pf},{no:2,name:"screen",kind:"message",T:Pf},{no:3,name:"resume_connection",kind:"enum",T:B.getEnumType(Gr)},{no:4,name:"disabled_codecs",kind:"message",T:nx},{no:5,name:"force_relay",kind:"enum",T:B.getEnumType(Gr)}]),Pf=B.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:B.getEnumType(Gr)}]),nx=B.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ja,repeated:!0},{no:2,name:"publish",kind:"message",T:Ja,repeated:!0}]),kf=B.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Il=B.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),If=B.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:B.getEnumType(Il)},{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"}),Df=B.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Qa=B.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:B.getEnumType(zt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:If,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Df,oneof:"content_header"}],{localName:"DataStream_Header"}),eo=B.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=B.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"}),ix=B.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),zn=B.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Dl=B.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),sx=B.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),rx=B.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Hi,oneof:"message"},{no:2,name:"answer",kind:"message",T:Hi,oneof:"message"},{no:3,name:"trickle",kind:"message",T:no,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Wr,oneof:"message"},{no:5,name:"mute",kind:"message",T:io,oneof:"message"},{no:6,name:"subscription",kind:"message",T:so,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Nf,oneof:"message"},{no:8,name:"leave",kind:"message",T:ro,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Uf,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Vf,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Bl,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ti,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ul,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Hf,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Ol,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Of,oneof:"message"}]),Lf=B.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:ax,oneof:"message"},{no:2,name:"answer",kind:"message",T:Hi,oneof:"message"},{no:3,name:"offer",kind:"message",T:Hi,oneof:"message"},{no:4,name:"trickle",kind:"message",T:no,oneof:"message"},{no:5,name:"update",kind:"message",T:lx,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Nl,oneof:"message"},{no:8,name:"leave",kind:"message",T:ro,oneof:"message"},{no:9,name:"mute",kind:"message",T:io,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:dx,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ux,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:fx,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:mx,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:vx,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:bx,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:cx,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ox,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Sx,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ex,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Cx,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Mx,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:yx,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Px,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:_x,oneof:"message"}]),Ll=B.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Gi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:B.getEnumType(_f)}]),Wr=B.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:B.getEnumType(Bn)},{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:B.getEnumType(Nt)},{no:9,name:"layers",kind:"message",T:Gi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Ll,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:B.getEnumType(zt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:B.getEnumType(vf)},{no:17,name:"audio_features",kind:"enum",T:B.getEnumType(qt),repeated:!0}]),no=B.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:B.getEnumType(zn)},{no:3,name:"final",kind:"scalar",T:8}]),io=B.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),ax=B.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ya},{no:2,name:"participant",kind:"message",T:gs},{no:3,name:"other_participants",kind:"message",T:gs,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ff,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:Rf},{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:Cf},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ja,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ox=B.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Ff,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Rf},{no:3,name:"server_info",kind:"message",T:Cf},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Nl=B.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Zs}]),cx=B.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Hi=B.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),lx=B.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:gs,repeated:!0}]),so=B.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:Ef,repeated:!0}]),Nf=B.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:B.getEnumType(wl)},{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}]),Ol=B.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:B.getEnumType(qt),repeated:!0}]),Of=B.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}]),ro=B.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:B.getEnumType(Vn)},{no:3,name:"action",kind:"enum",T:B.getEnumType(Qs)},{no:4,name:"regions",kind:"message",T:xx}]),Qs=B.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Uf=B.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Gi,repeated:!0}]),Ul=B.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}]),Ff=B.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}]),dx=B.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Sf,repeated:!0}]),ux=B.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ya}]),hx=B.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:B.getEnumType(zr)},{no:3,name:"score",kind:"scalar",T:2}]),fx=B.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:hx,repeated:!0}]),px=B.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:B.getEnumType(Dl)}]),mx=B.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:px,repeated:!0}]),Fl=B.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:B.getEnumType(wl)},{no:2,name:"enabled",kind:"scalar",T:8}]),gx=B.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Fl,repeated:!0}]),vx=B.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Fl,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:gx,repeated:!0}]),_x=B.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:ix,repeated:!0}]),Bf=B.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}]),Vf=B.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Bf,repeated:!0}]),bx=B.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}]),yx=B.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Ya},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:gs},{no:4,name:"other_participants",kind:"message",T:gs,repeated:!0}]),Bl=B.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Hi},{no:2,name:"subscription",kind:"message",T:so},{no:3,name:"publish_tracks",kind:"message",T:Nl,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Gf,repeated:!0},{no:5,name:"offer",kind:"message",T:Hi},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:zf,repeated:!0}]),zf=B.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Gf=B.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:B.getEnumType(zn)}]),ti=B.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:B.getEnumType(sx),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"}]),Hf=B.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Sx=B.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),xx=B.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Tx,repeated:!0}]),Tx=B.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}]),Ex=B.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:B.getEnumType(KS)}]),Cx=B.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:B.getEnumType(Vl)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:no,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Wr,oneof:"request"},{no:6,name:"mute",kind:"message",T:io,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Ul,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Ol,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Of,oneof:"request"}]),Vl=B.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),Mx=B.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Wf=B.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),wx=B.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:wf},{no:2,name:"connection_settings",kind:"message",T:Wf},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Wr,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Hi},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:B.getEnumType(ms)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Bl}]),Ax=B.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:B.getEnumType(Rx)},{no:2,name:"join_request",kind:"scalar",T:12}]),Rx=B.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Px=B.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function kx(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ao={exports:{}},Ix=ao.exports,qf;function Dx(){return qf||(qf=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Ix,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,T,C,_,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function E(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function w(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,U=encodeURIComponent(S),q=O.indexOf(U+"=");q!==-1&&(R=/^([^;]+)/.exec(O.slice(q+U.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function y(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return _??C??T},p.setLevel=function(R,O){return _=y(R),O!==!1&&E(_),d.call(p)},p.setDefaultLevel=function(R){C=y(R),w()||p.setLevel(R,!1)},p.resetLevel=function(){_=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(o!==p&&(T=y(o.getLevel())),d.call(p),o===p)for(var R in r)r[R].rebuild()},T=y(o?o.getLevel():"WARN");var x=w();x!=null&&(_=y(x)),d.call(p)}o=new f,o.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,o.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(ao)),ao.exports}var oo=Dx(),zl;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(zl||(zl={}));var Gn;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(Gn||(Gn={}));let ze=oo.getLogger("livekit");Object.values(Gn).map(i=>oo.getLogger(i)),ze.setDefaultLevel(zl.info);function Ti(i){const e=oo.getLogger(i);return e.setDefaultLevel(ze.getLevel()),e}const Lx=oo.getLogger("lk-e2ee"),qr=7e3,Nx=[0,300,4*300,9*300,16*300,qr,qr,qr,qr,qr];class Ox{constructor(e){this._retryDelays=e!==void 0?[...e]:Nx}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Ux(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function P(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?r(d.value):s(d.value).then(a,c)}l((n=n.apply(i,e||[])).next())})}function jf(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ei(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof jf=="function"?jf(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(l){r({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var co={exports:{}},Xf;function Fx(){if(Xf)return co.exports;Xf=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,E,w){return Function.prototype.apply.call(S,E,w)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(_){console&&console.warn&&console.warn(_)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}co.exports=r,co.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(_){if(typeof _!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof _)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(_){if(typeof _!="number"||_<0||s(_))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+_+".");o=_}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(_){return _._maxListeners===void 0?r.defaultMaxListeners:_._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var E=[],w=1;w<arguments.length;w++)E.push(arguments[w]);var k=S==="error",y=this._events;if(y!==void 0)k=k&&y.error===void 0;else if(!k)return!1;if(k){var x;if(E.length>0&&(x=E[0]),x instanceof Error)throw x;var R=new Error("Unhandled error."+(x?" ("+x.message+")":""));throw R.context=x,R}var O=y[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,E);else for(var U=O.length,q=g(O,U),w=0;w<U;++w)e(q[w],this,E);return!0};function l(_,S,E,w){var k,y,x;if(a(E),y=_._events,y===void 0?(y=_._events=Object.create(null),_._eventsCount=0):(y.newListener!==void 0&&(_.emit("newListener",S,E.listener?E.listener:E),y=_._events),x=y[S]),x===void 0)x=y[S]=E,++_._eventsCount;else if(typeof x=="function"?x=y[S]=w?[E,x]:[x,E]:w?x.unshift(E):x.push(E),k=c(_),k>0&&x.length>k&&!x.warned){x.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=_,R.type=S,R.count=x.length,n(R)}return _}r.prototype.addListener=function(S,E){return l(this,S,E,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,E){return l(this,S,E,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(_,S,E){var w={fired:!1,wrapFn:void 0,target:_,type:S,listener:E},k=d.bind(w);return k.listener=E,w.wrapFn=k,k}r.prototype.once=function(S,E){return a(E),this.on(S,u(this,S,E)),this},r.prototype.prependOnceListener=function(S,E){return a(E),this.prependListener(S,u(this,S,E)),this},r.prototype.removeListener=function(S,E){var w,k,y,x,R;if(a(E),k=this._events,k===void 0)return this;if(w=k[S],w===void 0)return this;if(w===E||w.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,w.listener||E));else if(typeof w!="function"){for(y=-1,x=w.length-1;x>=0;x--)if(w[x]===E||w[x].listener===E){R=w[x].listener,y=x;break}if(y<0)return this;y===0?w.shift():v(w,y),w.length===1&&(k[S]=w[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var E,w,k;if(w=this._events,w===void 0)return this;if(w.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):w[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete w[S]),this;if(arguments.length===0){var y=Object.keys(w),x;for(k=0;k<y.length;++k)x=y[k],x!=="removeListener"&&this.removeAllListeners(x);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=w[S],typeof E=="function")this.removeListener(S,E);else if(E!==void 0)for(k=E.length-1;k>=0;k--)this.removeListener(S,E[k]);return this};function h(_,S,E){var w=_._events;if(w===void 0)return[];var k=w[S];return k===void 0?[]:typeof k=="function"?E?[k.listener||k]:[k]:E?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(_,S){return typeof _.listenerCount=="function"?_.listenerCount(S):f.call(_,S)},r.prototype.listenerCount=f;function f(_){var S=this._events;if(S!==void 0){var E=S[_];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(_,S){for(var E=new Array(S),w=0;w<S;++w)E[w]=_[w];return E}function v(_,S){for(;S+1<_.length;S++)_[S]=_[S+1];_.pop()}function m(_){for(var S=new Array(_.length),E=0;E<S.length;++E)S[E]=_[E].listener||_[E];return S}function p(_,S){return new Promise(function(E,w){function k(x){_.removeListener(S,y),w(x)}function y(){typeof _.removeListener=="function"&&_.removeListener("error",k),E([].slice.call(arguments))}C(_,S,y,{once:!0}),S!=="error"&&T(_,k,{once:!0})})}function T(_,S,E){typeof _.on=="function"&&C(_,"error",S,E)}function C(_,S,E,w){if(typeof _.on=="function")w.once?_.once(S,E):_.on(S,E);else if(typeof _.addEventListener=="function")_.addEventListener(S,function k(y){w.once&&_.removeEventListener(S,k),E(y)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof _)}return co.exports}var ni=Fx();let $f=!0,Kf=!0;function jr(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function vs(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Bx(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):($f=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Vx(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Kf=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Yf(){if(typeof window=="object"){if($f)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gl(i,e){Kf&&console.warn(i+" is deprecated, please use "+e+" instead.")}function zx(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(jr(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(jr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(jr(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=jr(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Jf(i){return Object.prototype.toString.call(i)==="[object Object]"}function Zf(i){return Jf(i)?Object.keys(i).reduce(function(e,t){const n=Jf(i[t]),s=n?Zf(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function Hl(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Hl(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{Hl(i,i.get(s),t)})}))}function Qf(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&Hl(i,a,s)})}),s}const ep=Yf;function tp(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),ep("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return ep("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){s(a,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function np(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function ip(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else vs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function sp(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function rp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Qf(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),vs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Qf(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function ap(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function op(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ap(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Wl(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function cp(i,e){vs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var lp=Object.freeze({__proto__:null,fixNegotiationNeeded:cp,shimAddTrackRemoveTrack:op,shimAddTrackRemoveTrackWithNative:ap,shimGetSendersWithDtmf:sp,shimGetUserMedia:tp,shimMediaStream:np,shimOnTrack:ip,shimPeerConnection:Wl,shimSenderReceiverGetStats:rp});function dp(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Gl("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Gx(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function up(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ql(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(o,a)}}function hp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function fp(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),vs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function pp(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Gl("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function mp(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function gp(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function vp(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function _p(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function bp(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var yp=Object.freeze({__proto__:null,shimAddTransceiver:gp,shimCreateAnswer:bp,shimCreateOffer:_p,shimGetDisplayMedia:Gx,shimGetParameters:vp,shimGetUserMedia:dp,shimOnTrack:up,shimPeerConnection:ql,shimRTCDataChannel:mp,shimReceiverGetStats:fp,shimRemoveStream:pp,shimSenderGetStats:hp});function Sp(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function xp(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function Tp(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Ep(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Cp(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Cp(i){return i&&i.video!==void 0?Object.assign({},i,{video:Zf(i.video)}):i}function Mp(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Gl("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function wp(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ap(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Rp(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Pp=Object.freeze({__proto__:null,shimAudioContext:Rp,shimCallbacksAPI:Tp,shimConstraints:Cp,shimCreateOfferLegacy:Ap,shimGetUserMedia:Ep,shimLocalStreamsAPI:Sp,shimRTCIceServerUrls:Mp,shimRemoteStreamsAPI:xp,shimTrackEventTransceiver:wp}),jl={exports:{}},kp;function Hx(){return kp||(kp=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
4471
4471
  `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
4472
4472
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
4473
4473
  `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let r=8;r<n.length;r+=2)switch(n[r]){case"raddr":s.relatedAddress=n[r+1];break;case"rport":s.relatedPort=parseInt(n[r+1],10);break;case"tcptype":s.tcpType=n[r+1];break;case"ufrag":s.ufrag=n[r+1],s.usernameFragment=n[r+1];break;default:s[n[r]]===void 0&&(s[n[r]]=n[r+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const r=t.type;return n.push("typ"),n.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
@@ -4498,12 +4498,12 @@ a=ice-pwd:`+t.password+`\r
4498
4498
  o=`+(s||"thisisadapterortc")+" "+r+" "+o+` IN IP4 127.0.0.1\r
4499
4499
  s=-\r
4500
4500
  t=0 0\r
4501
- `},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(jl)),jl.exports}var Ip=Hx(),tr=kx(Ip),Wx=Qy({__proto__:null,default:tr},[Ip]);function uo(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),r=tr.parseCandidate(n.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,vs(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Xl(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||vs(i,"icecandidate",e=>{if(e.candidate){const t=tr.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ho(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=tr.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=tr.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=tr.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),l=s(c),d=r(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function fo(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},vs(i,"datachannel",n=>(e(n.channel,n.target),n))}function $l(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Kl(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
4501
+ `},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(jl)),jl.exports}var Ip=Hx(),er=kx(Ip),Wx=Qy({__proto__:null,default:er},[Ip]);function lo(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),r=er.parseCandidate(n.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,vs(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Xl(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||vs(i,"icecandidate",e=>{if(e.candidate){const t=er.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function uo(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=er.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=er.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=er.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),l=s(c),d=r(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function ho(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},vs(i,"datachannel",n=>(e(n.channel,n.target),n))}function $l(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Kl(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
4502
4502
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
4503
4503
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
4504
- `);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function po(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function mo(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var qx=Object.freeze({__proto__:null,removeExtmapAllowMixed:Kl,shimAddIceCandidateNullOrEmpty:po,shimConnectionState:$l,shimMaxMessageSize:ho,shimParameterlessSetLocalDescription:mo,shimRTCIceCandidate:uo,shimRTCIceCandidateRelayProtocol:Xl,shimSendThrowTypeError:fo});function jx(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Yf,n=zx(i),s={browserDetails:n,commonShim:qx,extractVersion:jr,disableLog:Bx,disableWarnings:Vx,sdp:Wx};switch(n.browser){case"chrome":if(!lp||!Wl||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=lp,po(i,n),mo(i),tp(i,n),np(i),Wl(i,n),ip(i),op(i,n),sp(i),rp(i),cp(i,n),uo(i),Xl(i),$l(i),ho(i,n),fo(i),Kl(i,n);break;case"firefox":if(!yp||!ql||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=yp,po(i,n),mo(i),dp(i,n),ql(i,n),up(i),pp(i),hp(i),fp(i),mp(i),gp(i),vp(i),_p(i),bp(i),uo(i),$l(i),ho(i,n),fo(i);break;case"safari":if(!Pp||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Pp,po(i,n),mo(i),Mp(i),Ap(i),Tp(i),Sp(i),xp(i),wp(i),Ep(i),Rp(i),uo(i),Xl(i),ho(i,n),fo(i),Kl(i,n);break;default:t("Unsupported browser!");break}return s}jx({window:typeof window>"u"?void 0:window});class hn extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const Xx=/version\/(\d+(\.?_?\d+)+)/i;let Yl;function fn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Yl===void 0||e){const n=$x.find(s=>{let{test:r}=s;return r.test(t)});Yl=n==null?void 0:n.describe(t)}return Yl}const $x=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:go(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Jl(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:go(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Jl(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:go(Xx,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Jl(i)}}}];function go(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function Jl(i){return i.includes("mac os")?go(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Kx="2.17.0";const Yx=Kx,Jx=16;class ii extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var mt;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(mt||(mt={}));class De extends ii{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=mt[t]}static notAllowed(e,t,n){return new De(e,mt.NotAllowed,t,n)}static timeout(e){return new De(e,mt.Timeout)}static leaveRequest(e,t){return new De(e,mt.LeaveRequest,void 0,t)}static internal(e,t){return new De(e,mt.InternalError,void 0,t)}static cancelled(e){return new De(e,mt.Cancelled)}static serverUnreachable(e,t){return new De(e,mt.ServerUnreachable,t)}static websocket(e,t,n){return new De(e,mt.WebSocket,t,n)}static serviceNotFound(e,t){return new De(e,mt.ServiceNotFound,void 0,t)}}class Zl extends ii{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ci extends ii{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Zx extends ii{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class It extends ii{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class nr extends ii{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Dp extends ii{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Lp extends ii{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Vl[t]}}var on;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(on||(on={}));class An extends ii{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=on[t]}}class ir extends ii{constructor(e){super(18,e),this.name="SignalReconnectError"}}var vo;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(vo||(vo={})),(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(vo||(vo={}));class Kt{}Kt.setTimeout=function(){return setTimeout(...arguments)},Kt.setInterval=function(){return setInterval(...arguments)},Kt.clearTimeout=function(){return clearTimeout(...arguments)},Kt.clearInterval=function(){return clearInterval(...arguments)};var te;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(te||(te={}));var ce;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(ce||(ce={}));var oe;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved"})(oe||(oe={}));var re;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(re||(re={}));function Qx(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}class ht{constructor(e,t,n,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const eT=["vp8","h264"],tT=["vp8","h264","vp9","av1","h265"];function nT(i){return!!eT.find(e=>e===i)}const iT=nT;var Np;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(Np||(Np={}));var Ql;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Ql||(Ql={}));const Xr={h90:new ht(160,90,9e4,20),h180:new ht(320,180,16e4,20),h216:new ht(384,216,18e4,20),h360:new ht(640,360,45e4,20),h540:new ht(960,540,8e5,25),h720:new ht(1280,720,17e5,30),h1080:new ht(1920,1080,3e6,30),h1440:new ht(2560,1440,5e6,30),h2160:new ht(3840,2160,8e6,30)},ed={h120:new ht(160,120,7e4,20),h180:new ht(240,180,125e3,20),h240:new ht(320,240,14e4,20),h360:new ht(480,360,33e4,20),h480:new ht(640,480,5e5,20),h540:new ht(720,540,6e5,25),h720:new ht(960,720,13e5,30),h1080:new ht(1440,1080,23e5,30),h1440:new ht(1920,1440,38e5,30)},td={h360fps3:new ht(640,360,2e5,3,"medium"),h360fps15:new ht(640,360,4e5,15,"medium"),h720fps5:new ht(1280,720,8e5,5,"medium"),h720fps15:new ht(1280,720,15e5,15,"medium"),h720fps30:new ht(1280,720,2e6,30,"medium"),h1080fps15:new ht(1920,1080,25e5,15,"medium"),h1080fps30:new ht(1920,1080,5e6,30,"medium"),original:new ht(0,0,7e6,30,"medium")};function Op(i,e,t){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=Bp(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(nd(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(nd(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function nd(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function id(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const o={},a=o,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":nd(a,c.resolution);break;default:a[l]=c[l]}}),r.video=o,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=i.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Up(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Fp();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Yt(t),s.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return n.close(),!c}return!1})()})}function Fp(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>P(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function sT(i){return i==="audioinput"?J.Source.Microphone:i==="videoinput"?J.Source.Camera:J.Source.Unknown}function sd(i){return i===J.Source.Microphone?"audioinput":i===J.Source.Camera?"videoinput":void 0}function rT(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,bs()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function $r(i){return i.split("/")[1].toLowerCase()}function aT(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Nl({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function $e(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?$e(i.track):{})}}function oT(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function cT(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Bp(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:Qx(e)}}function lT(i){switch(i){case Nt.CAMERA:return J.Source.Camera;case Nt.MICROPHONE:return J.Source.Microphone;case Nt.SCREEN_SHARE:return J.Source.ScreenShare;case Nt.SCREEN_SHARE_AUDIO:return J.Source.ScreenShareAudio;default:return J.Source.Unknown}}function Vp(i,e){return i.width*i.height<e.width*e.height}function dT(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const uT=5e3,Kr=[];var yn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(yn||(yn={}));class J extends ni.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=J.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ze,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),uT):this.handleAppVisibilityChanged()},this.log=Ti((s=n.loggerName)!==null&&s!==void 0?s:Gn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=J.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),$e(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===J.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===J.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Kr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Kr.splice(Kr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),sr(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?re.AudioPlaybackStarted:re.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?re.AudioPlaybackFailed:re.VideoPlaybackFailed,r):r.name==="AbortError"?ze.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):ze.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(re.ElementAttached,e),e}detach(e){try{if(e){rr(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(re.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{rr(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(re.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ti(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kr.forEach(n=>{n.parentElement||(t=!1)}),t&&Kr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===J.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){pn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){pn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function sr(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!bs()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(bs()||_s())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function rr(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return Bn.AUDIO;case e.Video:return Bn.VIDEO;default:return Bn.DATA}}i.kindToProto=s;function r(l){switch(l){case Bn.AUDIO:return e.Audio;case Bn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(l){switch(l){case t.Camera:return Nt.CAMERA;case t.Microphone:return Nt.MICROPHONE;case t.ScreenShare:return Nt.SCREEN_SHARE;case t.ScreenShareAudio:return Nt.SCREEN_SHARE_AUDIO;default:return Nt.UNKNOWN}}i.sourceToProto=o;function a(l){switch(l){case Nt.CAMERA:return t.Camera;case Nt.MICROPHONE:return t.Microphone;case Nt.SCREEN_SHARE:return t.ScreenShare;case Nt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(l){switch(l){case Dl.ACTIVE:return n.Active;case Dl.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(J||(J={}));const hT="|",zp="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function fT(i){const e=i.split(hT);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Yt(i){return new hn(e=>Kt.setTimeout(e,i))}function rd(){return"addTransceiver"in RTCPeerConnection.prototype}function ad(){return"addTrack"in RTCPeerConnection.prototype}function pT(){if(!("getCapabilities"in RTCRtpSender)||bs()||_s())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function mT(){if(!("getCapabilities"in RTCRtpSender)||_s())return!1;if(bs()){const t=fn();if(t!=null&&t.version&&ri(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&ri(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Hn(i){return i==="av1"||i==="vp9"}function od(i){return!document||Yr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function gT(){return typeof RTCPeerConnection>"u"?!1:rd()||ad()}function _s(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Firefox"}function Gp(){const i=fn();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function bs(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Safari"}function Yr(){const i=fn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function vT(){const i=fn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ri(i.osVersion,"17")>=0}function _T(i){return i||(i=fn()),(i==null?void 0:i.name)==="Safari"&&ri(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ri(i.osVersion,"18.3")>0}function Hp(){var i,e;return pn()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function bT(){const i=fn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&ri(i.osVersion,e)>=0?!0:i.name==="Safari"&&ri(i.version,e)>=0}function pn(){return typeof document<"u"}function si(){return navigator.product=="ReactNative"}function ar(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function cd(i){return ar(i)?i.hostname.split(".")[0]:null}function Wp(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function qp(){if(!si())return;let i=Wp();if(i)return i.platform}function jp(){if(pn())return window.devicePixelRatio;if(si()){let i=Wp();if(i)return i.devicePixelRatio}return 1}function ri(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function yT(i){for(const e of i)e.target.handleResize(e)}function ST(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ld=null;const Xp=()=>(ld||(ld=new ResizeObserver(yT)),ld);let dd=null;const $p=()=>(dd||(dd=new IntersectionObserver(ST,{root:null,rootMargin:"0px"})),dd);function xT(){var i;const e=new wf({sdk:Af.JS,protocol:Jx,version:Yx});return si()&&(e.os=(i=qp())!==null&&i!==void 0?i:""),e}function Kp(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let Jr;function ud(){if(!Jr){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Jr]=n.stream.getAudioTracks(),!Jr)throw Error("Could not get empty media stream audio track");Jr.enabled=!1}return Jr.clone()}class Rn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function TT(i){return tT.includes(i)}function Wi(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function ET(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Zr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function CT(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:o,endTime:a,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function MT(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function Yp(i){switch(i.reason){case mt.LeaveRequest:return i.context;case mt.Cancelled:return Vn.CLIENT_INITIATED;case mt.NotAllowed:return Vn.USER_REJECTED;case mt.ServerUnreachable:return Vn.JOIN_FAILURE;default:return Vn.UNKNOWN_REASON}}function _o(i){return i!==void 0?Number(i):void 0}function ys(i){return i!==void 0?BigInt(i):void 0}function or(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function ai(i){return!!i&&i.kind==J.Kind.Audio}function qi(i){return!!i&&i.kind==J.Kind.Video}function ji(i){return or(i)&&qi(i)}function Mi(i){return or(i)&&ai(i)}function hd(i){return!!i&&!i.isLocal}function wT(i){return!!i&&!i.isLocal}function fd(i){return hd(i)&&qi(i)}function AT(i){return i.isLocal}function RT(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function PT(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function kT(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=IT(i,e);return t?n:pd(n,"v1")}function IT(i,e){const t=new URL(ET(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),pd(t,"rtc")}function DT(i){const e=new URL(Zr(i));return pd(e,"validate")}function Jp(i){return i.endsWith("/")?i:"".concat(i,"/")}function pd(i,e){return i.pathname="".concat(Jp(i.pathname)).concat(e),i}function Zp(i){if(typeof i=="string")return Lf.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return Lf.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function LT(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;const t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const NT=10,Qr="lk_e2ee",OT={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:NT,keyringSize:16};var Xi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Xi||(Xi={}));var Qp;(function(i){i.KeyRatcheted="keyRatcheted"})(Qp||(Qp={}));var $i;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})($i||($i={}));var em;(function(i){i.Error="cryptorError"})(em||(em={}));function UT(){return FT()||md()}function md(){return typeof window.RTCRtpScriptTransform<"u"}function FT(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function BT(i){var e,t,n,s,r;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new yf({value:i.value})}class bM extends ni.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{ze.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},OT),e),this.on(Xi.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(Xi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Xi.RatchetRequest,e,t)}}var tm;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(tm||(tm={}));class VT extends ni.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var s,r;const{kind:o,data:a}=n.data;switch(o){case"error":if(ze.error(a.error.message),a.uuid){const d=this.decryptDataRequests.get(a.uuid);if(d!=null&&d.reject){d.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit($i.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const d=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!d)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,d)}break;case"ratchetKey":this.keyProvider.emit(Xi.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(a.uuid);l!=null&&l.resolve&&l.resolve(a);break}},this.onWorkerError=n=>{ze.error("e2ee worker encountered an error:",{error:n.error}),this.emit($i.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!UT())throw new Zl("tried to setup end-to-end encryption on an unsupported browser");if(ze.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:Lx.getLevel()}};this.worker&&(ze.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ze.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ze.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(oe.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(te.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Gt.NONE,s.identity)),e.on(te.ConnectionStateChanged,n=>{n===rt.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Gt.NONE,s.identity)})})}).on(te.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(te.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(te.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ce.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(ce.LocalTrackPublished,n=>{if(!qi(n.track)||!Yr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:$r(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Xi.SetKey,n=>this.postKey(n)).on(Xi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}encryptData(e){return P(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Rn;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(n),s.promise})}handleEncryptedData(e,t,n,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:s}},a=new Rn;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?$r(n.mimeType):void 0)}}setupE2EESender(e,t){if(!or(e)||!t){t||ze.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(md()&&!Gp()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Qr in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:Qr in e}};this.worker.postMessage(a,[o,r])}e[Qr]=!0}})}handleSender(e,t,n){var s;if(!(Qr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(md()&&!Gp()){ze.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{ze.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[Qr]=!0}}}const zT=500,GT=15e3;class cr{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new cr),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),s=cd(n);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Yt(Math.min(zT*Math.pow(2,r),GT)))}getBackOffPromise(e){const t=new URL(e),n=t&&cd(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&cd(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}cr._instance=null;const gd="default";class jt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new jt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=jt.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){ze.debug("awaiting getUserMedia promise");try{t?yield jt.userMediaPromiseMap.get(t):yield Promise.all(jt.userMediaPromiseMap.values())}catch{ze.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(bs()&&n.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==gd)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===gd);if(!r){ze.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==gd&&a.groupId===(n??r.groupId));if(!o){ze.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?jt.userMediaPromiseMap.has(e):jt.userMediaPromiseMap.size>0}}jt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],jt.userMediaPromiseMap=new Map;var ea;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(ea||(ea={}));class HT{constructor(){this.pendingTasks=new Map,this.taskMutex=new rn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ea.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ea.RUNNING,yield e()}finally{t.status=ea.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class WT{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,s;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new hn((a,c)=>{const l=()=>{c(De.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(d){r.onmessage=u=>{let{data:h}=u;return d.enqueue(h)},r.onerror=u=>d.error(u)},cancel:o}),writable:new WritableStream({write(d){r.send(d)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new hn((a,c)=>{const l=()=>P(this,void 0,void 0,function*(){const d=new hn(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield hn.race([Yt(250),d]);u?a(u):c(De.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=d=>{let{code:u,reason:h}=d;a({closeCode:u,reason:h}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const qT=["syncState","trickle","offer","answer","simulate","leave"];function jT(i){const e=qT.indexOf(i.case)>=0;return ze.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var gt;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(gt||(gt={}));const XT=250;class vd{get currentState(){return this.state}get isDisconnected(){return this.state===gt.DISCONNECTING||this.state===gt.DISCONNECTED}get isEstablishingConnection(){return this.state===gt.CONNECTING||this.state===gt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=gt.DISCONNECTED,this.log=ze,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ti((n=t.loggerName)!==null&&n!==void 0?n:Gn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new HT,this.queuedRequests=[],this.closingLock=new rn,this.connectionLock=new rn,this.state=gt.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=gt.CONNECTING,l.options=a,yield l.connect(r,o,a,c,d)})()})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=gt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=d;const h=xT(),f=d?$T(o,h,a):KT(o,h,a),g=kT(r,f,d).toString(),v=DT(g).toString();return new Promise((m,p)=>P(l,void 0,void 0,function*(){var T,C;try{let _=!1;const S=x=>P(this,void 0,void 0,function*(){if(_)return;_=!0;const R=x instanceof Event?x.currentTarget:x,O=LT(R,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(O)).catch(U=>{this.log.error(U),this.close()}):this.close(),E(),p(De.cancelled(O))});c==null||c.addEventListener("abort",S);const E=()=>{clearTimeout(w),c==null||c.removeEventListener("abort",S)},w=setTimeout(()=>{S(De.timeout("room connection has timed out (signal)"))},a.websocketTimeout),k=(x,R)=>{this.handleSignalConnected(x,w,R)},y=new URL(g);y.searchParams.has("access_token")&&y.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(y),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WT(g);try{this.ws.closed.then(G=>{var W;this.isEstablishingConnection&&p(De.internal("Websocket got closed during a (re)connection attempt: ".concat(G.reason))),G.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:G.reason,code:G.closeCode,wasClean:G.closeCode===1e3,state:this.state})),this.state===gt.CONNECTED&&this.handleOnClose((W=G.reason)!==null&&W!==void 0?W:"Unexpected WS error"))}).catch(G=>{this.isEstablishingConnection&&p(De.internal("Websocket error during a (re)connection attempt: ".concat(G)))});const x=yield this.ws.opened.catch(G=>P(this,void 0,void 0,function*(){if(this.state!==gt.CONNECTED){this.state=gt.DISCONNECTED,clearTimeout(w);const W=yield this.handleConnectionError(G,v);p(W);return}this.handleWSError(G),p(G)}));if(clearTimeout(w),!x)return;const R=x.readable.getReader();this.streamWriter=x.writable.getWriter();const O=yield R.read();if(R.releaseLock(),!O.value)throw De.internal("no message received as first message");const U=Zp(O.value),q=this.validateFirstMessage(U,(T=a.reconnect)!==null&&T!==void 0?T:!1);if(!q.isValid){p(q.error);return}((C=U.message)===null||C===void 0?void 0:C.case)==="join"&&(this.pingTimeoutDuration=U.message.value.pingTimeout,this.pingIntervalDuration=U.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})));const $=q.shouldProcessFirstMessage?U:void 0;k(x,$),m(q.response)}catch(x){p(x)}finally{E()}}finally{u()}}))})()})}startReadingLoop(e,t){return P(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Yt(this.signalLatency));const{done:n,value:s}=yield e.read();if(n)break;const r=Zp(s);this.handleSignalResponse(r)}})}close(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([gt.DISCONNECTING||gt.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=gt.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Yt(XT)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=gt.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:lr(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:lr(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new io({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new so({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Ul({requestId:a,metadata:n,name:s,attributes:o})}),a})()})}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 Uf({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Vf({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Et.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Hf({timestamp:Et.parse(Date.now()),rtt:Et.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Ol({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ao({reason:Vn.CLIENT_INITIATED,action:er.DISCONNECT})})}sendRequest(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!jT(t)&&n.state===gt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Yt(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const o=new rx({message:t});try{n.useJSON?yield n.streamWriter.write(o.toJsonString()):yield n.streamWriter.write(o.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=nm(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=nm(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return P(this,void 0,void 0,function*(){if(this.state===gt.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Kt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Kt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Kt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Kt.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=gt.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,s,r,o,a;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===gt.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:De.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:De.internal("Unexpected first message")}:{isValid:!1,error:De.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return P(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:return De.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield n.text();return De.notAllowed(s,n.status);default:break}return e instanceof De?e:De.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof De?n:De.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function nm(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function lr(i,e){return new Hi({sdp:i.sdp,type:i.type,id:e})}function $T(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",si()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}function KT(i,e,t){const n=new URLSearchParams;n.set("access_token",i);const s=new wx({clientInfo:e,connectionSettings:new Wf({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new Ax({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}class im{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class YT{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const s=n+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Wn={},_d={},bd={exports:{}},sm;function yd(){if(sm)return bd.exports;sm=1;var i=bd.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),bd.exports}var rm;function JT(){return rm||(rm=1,(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},n=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;t(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=yd(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(_d)),_d}var Sd,am;function ZT(){if(am)return Sd;am=1;var i=yd(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Sd=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||s,l=a.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(n(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(n(u,h,f))})})}),o.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
4504
+ `);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function fo(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function po(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var qx=Object.freeze({__proto__:null,removeExtmapAllowMixed:Kl,shimAddIceCandidateNullOrEmpty:fo,shimConnectionState:$l,shimMaxMessageSize:uo,shimParameterlessSetLocalDescription:po,shimRTCIceCandidate:lo,shimRTCIceCandidateRelayProtocol:Xl,shimSendThrowTypeError:ho});function jx(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Yf,n=zx(i),s={browserDetails:n,commonShim:qx,extractVersion:jr,disableLog:Bx,disableWarnings:Vx,sdp:Wx};switch(n.browser){case"chrome":if(!lp||!Wl||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=lp,fo(i,n),po(i),tp(i,n),np(i),Wl(i,n),ip(i),op(i,n),sp(i),rp(i),cp(i,n),lo(i),Xl(i),$l(i),uo(i,n),ho(i),Kl(i,n);break;case"firefox":if(!yp||!ql||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=yp,fo(i,n),po(i),dp(i,n),ql(i,n),up(i),pp(i),hp(i),fp(i),mp(i),gp(i),vp(i),_p(i),bp(i),lo(i),$l(i),uo(i,n),ho(i);break;case"safari":if(!Pp||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Pp,fo(i,n),po(i),Mp(i),Ap(i),Tp(i),Sp(i),xp(i),wp(i),Ep(i),Rp(i),lo(i),Xl(i),uo(i,n),ho(i),Kl(i,n);break;default:t("Unsupported browser!");break}return s}jx({window:typeof window>"u"?void 0:window});class hn extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const Xx=/version\/(\d+(\.?_?\d+)+)/i;let Yl;function fn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Yl===void 0||e){const n=$x.find(s=>{let{test:r}=s;return r.test(t)});Yl=n==null?void 0:n.describe(t)}return Yl}const $x=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:mo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Jl(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:mo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Jl(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:mo(Xx,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Jl(i)}}}];function mo(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function Jl(i){return i.includes("mac os")?mo(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Kx="2.17.0";const Yx=Kx,Jx=16;class ii extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var pt;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(pt||(pt={}));class De extends ii{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=pt[t]}static notAllowed(e,t,n){return new De(e,pt.NotAllowed,t,n)}static timeout(e){return new De(e,pt.Timeout)}static leaveRequest(e,t){return new De(e,pt.LeaveRequest,void 0,t)}static internal(e,t){return new De(e,pt.InternalError,void 0,t)}static cancelled(e){return new De(e,pt.Cancelled)}static serverUnreachable(e,t){return new De(e,pt.ServerUnreachable,t)}static websocket(e,t,n){return new De(e,pt.WebSocket,t,n)}static serviceNotFound(e,t){return new De(e,pt.ServiceNotFound,void 0,t)}}class Zl extends ii{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ci extends ii{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Zx extends ii{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class It extends ii{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class tr extends ii{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Dp extends ii{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Lp extends ii{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Vl[t]}}var on;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(on||(on={}));class An extends ii{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=on[t]}}class nr extends ii{constructor(e){super(18,e),this.name="SignalReconnectError"}}var go;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(go||(go={})),(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(go||(go={}));class Kt{}Kt.setTimeout=function(){return setTimeout(...arguments)},Kt.setInterval=function(){return setInterval(...arguments)},Kt.clearTimeout=function(){return clearTimeout(...arguments)},Kt.clearInterval=function(){return clearInterval(...arguments)};var te;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(te||(te={}));var ce;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(ce||(ce={}));var oe;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved"})(oe||(oe={}));var re;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(re||(re={}));function Qx(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}class ut{constructor(e,t,n,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const eT=["vp8","h264"],tT=["vp8","h264","vp9","av1","h265"];function nT(i){return!!eT.find(e=>e===i)}const iT=nT;var Np;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(Np||(Np={}));var Ql;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Ql||(Ql={}));const Xr={h90:new ut(160,90,9e4,20),h180:new ut(320,180,16e4,20),h216:new ut(384,216,18e4,20),h360:new ut(640,360,45e4,20),h540:new ut(960,540,8e5,25),h720:new ut(1280,720,17e5,30),h1080:new ut(1920,1080,3e6,30),h1440:new ut(2560,1440,5e6,30),h2160:new ut(3840,2160,8e6,30)},ed={h120:new ut(160,120,7e4,20),h180:new ut(240,180,125e3,20),h240:new ut(320,240,14e4,20),h360:new ut(480,360,33e4,20),h480:new ut(640,480,5e5,20),h540:new ut(720,540,6e5,25),h720:new ut(960,720,13e5,30),h1080:new ut(1440,1080,23e5,30),h1440:new ut(1920,1440,38e5,30)},td={h360fps3:new ut(640,360,2e5,3,"medium"),h360fps15:new ut(640,360,4e5,15,"medium"),h720fps5:new ut(1280,720,8e5,5,"medium"),h720fps15:new ut(1280,720,15e5,15,"medium"),h720fps30:new ut(1280,720,2e6,30,"medium"),h1080fps15:new ut(1920,1080,25e5,15,"medium"),h1080fps30:new ut(1920,1080,5e6,30,"medium"),original:new ut(0,0,7e6,30,"medium")};function Op(i,e,t){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=Bp(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(nd(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(nd(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function nd(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function id(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const o={},a=o,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":nd(a,c.resolution);break;default:a[l]=c[l]}}),r.video=o,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=i.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Up(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Fp();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Yt(t),s.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return n.close(),!c}return!1})()})}function Fp(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>P(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function sT(i){return i==="audioinput"?J.Source.Microphone:i==="videoinput"?J.Source.Camera:J.Source.Unknown}function sd(i){return i===J.Source.Microphone?"audioinput":i===J.Source.Camera?"videoinput":void 0}function rT(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,bs()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function $r(i){return i.split("/")[1].toLowerCase()}function aT(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Nl({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function $e(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?$e(i.track):{})}}function oT(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function cT(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Bp(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:Qx(e)}}function lT(i){switch(i){case Nt.CAMERA:return J.Source.Camera;case Nt.MICROPHONE:return J.Source.Microphone;case Nt.SCREEN_SHARE:return J.Source.ScreenShare;case Nt.SCREEN_SHARE_AUDIO:return J.Source.ScreenShareAudio;default:return J.Source.Unknown}}function Vp(i,e){return i.width*i.height<e.width*e.height}function dT(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const uT=5e3,Kr=[];var yn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(yn||(yn={}));class J extends ni.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=J.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ze,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),uT):this.handleAppVisibilityChanged()},this.log=Ti((s=n.loggerName)!==null&&s!==void 0?s:Gn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=J.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),$e(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===J.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===J.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Kr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Kr.splice(Kr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ir(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?re.AudioPlaybackStarted:re.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?re.AudioPlaybackFailed:re.VideoPlaybackFailed,r):r.name==="AbortError"?ze.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):ze.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(re.ElementAttached,e),e}detach(e){try{if(e){sr(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(re.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{sr(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(re.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ti(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kr.forEach(n=>{n.parentElement||(t=!1)}),t&&Kr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===J.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){pn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){pn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ir(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!bs()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(bs()||_s())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function sr(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return Bn.AUDIO;case e.Video:return Bn.VIDEO;default:return Bn.DATA}}i.kindToProto=s;function r(l){switch(l){case Bn.AUDIO:return e.Audio;case Bn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(l){switch(l){case t.Camera:return Nt.CAMERA;case t.Microphone:return Nt.MICROPHONE;case t.ScreenShare:return Nt.SCREEN_SHARE;case t.ScreenShareAudio:return Nt.SCREEN_SHARE_AUDIO;default:return Nt.UNKNOWN}}i.sourceToProto=o;function a(l){switch(l){case Nt.CAMERA:return t.Camera;case Nt.MICROPHONE:return t.Microphone;case Nt.SCREEN_SHARE:return t.ScreenShare;case Nt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(l){switch(l){case Dl.ACTIVE:return n.Active;case Dl.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(J||(J={}));const hT="|",zp="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function fT(i){const e=i.split(hT);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Yt(i){return new hn(e=>Kt.setTimeout(e,i))}function rd(){return"addTransceiver"in RTCPeerConnection.prototype}function ad(){return"addTrack"in RTCPeerConnection.prototype}function pT(){if(!("getCapabilities"in RTCRtpSender)||bs()||_s())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function mT(){if(!("getCapabilities"in RTCRtpSender)||_s())return!1;if(bs()){const t=fn();if(t!=null&&t.version&&ri(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&ri(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Hn(i){return i==="av1"||i==="vp9"}function od(i){return!document||Yr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function gT(){return typeof RTCPeerConnection>"u"?!1:rd()||ad()}function _s(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Firefox"}function Gp(){const i=fn();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function bs(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Safari"}function Yr(){const i=fn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function vT(){const i=fn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ri(i.osVersion,"17")>=0}function _T(i){return i||(i=fn()),(i==null?void 0:i.name)==="Safari"&&ri(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ri(i.osVersion,"18.3")>0}function Hp(){var i,e;return pn()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function bT(){const i=fn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&ri(i.osVersion,e)>=0?!0:i.name==="Safari"&&ri(i.version,e)>=0}function pn(){return typeof document<"u"}function si(){return navigator.product=="ReactNative"}function rr(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function cd(i){return rr(i)?i.hostname.split(".")[0]:null}function Wp(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function qp(){if(!si())return;let i=Wp();if(i)return i.platform}function jp(){if(pn())return window.devicePixelRatio;if(si()){let i=Wp();if(i)return i.devicePixelRatio}return 1}function ri(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function yT(i){for(const e of i)e.target.handleResize(e)}function ST(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ld=null;const Xp=()=>(ld||(ld=new ResizeObserver(yT)),ld);let dd=null;const $p=()=>(dd||(dd=new IntersectionObserver(ST,{root:null,rootMargin:"0px"})),dd);function xT(){var i;const e=new wf({sdk:Af.JS,protocol:Jx,version:Yx});return si()&&(e.os=(i=qp())!==null&&i!==void 0?i:""),e}function Kp(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let Jr;function ud(){if(!Jr){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Jr]=n.stream.getAudioTracks(),!Jr)throw Error("Could not get empty media stream audio track");Jr.enabled=!1}return Jr.clone()}class Rn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function TT(i){return tT.includes(i)}function Wi(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function ET(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Zr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function CT(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:o,endTime:a,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function MT(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function Yp(i){switch(i.reason){case pt.LeaveRequest:return i.context;case pt.Cancelled:return Vn.CLIENT_INITIATED;case pt.NotAllowed:return Vn.USER_REJECTED;case pt.ServerUnreachable:return Vn.JOIN_FAILURE;default:return Vn.UNKNOWN_REASON}}function vo(i){return i!==void 0?Number(i):void 0}function ys(i){return i!==void 0?BigInt(i):void 0}function ar(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function ai(i){return!!i&&i.kind==J.Kind.Audio}function qi(i){return!!i&&i.kind==J.Kind.Video}function ji(i){return ar(i)&&qi(i)}function Mi(i){return ar(i)&&ai(i)}function hd(i){return!!i&&!i.isLocal}function wT(i){return!!i&&!i.isLocal}function fd(i){return hd(i)&&qi(i)}function AT(i){return i.isLocal}function RT(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function PT(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function kT(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=IT(i,e);return t?n:pd(n,"v1")}function IT(i,e){const t=new URL(ET(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),pd(t,"rtc")}function DT(i){const e=new URL(Zr(i));return pd(e,"validate")}function Jp(i){return i.endsWith("/")?i:"".concat(i,"/")}function pd(i,e){return i.pathname="".concat(Jp(i.pathname)).concat(e),i}function Zp(i){if(typeof i=="string")return Lf.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return Lf.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function LT(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;const t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const NT=10,Qr="lk_e2ee",OT={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:NT,keyringSize:16};var Xi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Xi||(Xi={}));var Qp;(function(i){i.KeyRatcheted="keyRatcheted"})(Qp||(Qp={}));var $i;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})($i||($i={}));var em;(function(i){i.Error="cryptorError"})(em||(em={}));function UT(){return FT()||md()}function md(){return typeof window.RTCRtpScriptTransform<"u"}function FT(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function BT(i){var e,t,n,s,r;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new yf({value:i.value})}class _M extends ni.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{ze.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},OT),e),this.on(Xi.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(Xi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Xi.RatchetRequest,e,t)}}var tm;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(tm||(tm={}));class VT extends ni.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var s,r;const{kind:o,data:a}=n.data;switch(o){case"error":if(ze.error(a.error.message),a.uuid){const d=this.decryptDataRequests.get(a.uuid);if(d!=null&&d.reject){d.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit($i.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const d=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!d)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,d)}break;case"ratchetKey":this.keyProvider.emit(Xi.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(a.uuid);l!=null&&l.resolve&&l.resolve(a);break}},this.onWorkerError=n=>{ze.error("e2ee worker encountered an error:",{error:n.error}),this.emit($i.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!UT())throw new Zl("tried to setup end-to-end encryption on an unsupported browser");if(ze.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:Lx.getLevel()}};this.worker&&(ze.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ze.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ze.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(oe.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(te.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==zt.NONE,s.identity)),e.on(te.ConnectionStateChanged,n=>{n===rt.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==zt.NONE,s.identity)})})}).on(te.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(te.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(te.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ce.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(ce.LocalTrackPublished,n=>{if(!qi(n.track)||!Yr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:$r(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Xi.SetKey,n=>this.postKey(n)).on(Xi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}encryptData(e){return P(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Rn;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(n),s.promise})}handleEncryptedData(e,t,n,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:s}},a=new Rn;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?$r(n.mimeType):void 0)}}setupE2EESender(e,t){if(!ar(e)||!t){t||ze.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(md()&&!Gp()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Qr in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:Qr in e}};this.worker.postMessage(a,[o,r])}e[Qr]=!0}})}handleSender(e,t,n){var s;if(!(Qr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(md()&&!Gp()){ze.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{ze.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[Qr]=!0}}}const zT=500,GT=15e3;class or{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new or),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),s=cd(n);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Yt(Math.min(zT*Math.pow(2,r),GT)))}getBackOffPromise(e){const t=new URL(e),n=t&&cd(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&cd(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}or._instance=null;const gd="default";class jt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new jt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=jt.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){ze.debug("awaiting getUserMedia promise");try{t?yield jt.userMediaPromiseMap.get(t):yield Promise.all(jt.userMediaPromiseMap.values())}catch{ze.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(bs()&&n.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==gd)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===gd);if(!r){ze.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==gd&&a.groupId===(n??r.groupId));if(!o){ze.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?jt.userMediaPromiseMap.has(e):jt.userMediaPromiseMap.size>0}}jt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],jt.userMediaPromiseMap=new Map;var ea;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(ea||(ea={}));class HT{constructor(){this.pendingTasks=new Map,this.taskMutex=new rn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ea.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ea.RUNNING,yield e()}finally{t.status=ea.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class WT{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,s;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new hn((a,c)=>{const l=()=>{c(De.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(d){r.onmessage=u=>{let{data:h}=u;return d.enqueue(h)},r.onerror=u=>d.error(u)},cancel:o}),writable:new WritableStream({write(d){r.send(d)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new hn((a,c)=>{const l=()=>P(this,void 0,void 0,function*(){const d=new hn(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield hn.race([Yt(250),d]);u?a(u):c(De.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=d=>{let{code:u,reason:h}=d;a({closeCode:u,reason:h}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const qT=["syncState","trickle","offer","answer","simulate","leave"];function jT(i){const e=qT.indexOf(i.case)>=0;return ze.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var mt;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(mt||(mt={}));const XT=250;class vd{get currentState(){return this.state}get isDisconnected(){return this.state===mt.DISCONNECTING||this.state===mt.DISCONNECTED}get isEstablishingConnection(){return this.state===mt.CONNECTING||this.state===mt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=mt.DISCONNECTED,this.log=ze,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ti((n=t.loggerName)!==null&&n!==void 0?n:Gn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new HT,this.queuedRequests=[],this.closingLock=new rn,this.connectionLock=new rn,this.state=mt.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=mt.CONNECTING,l.options=a,yield l.connect(r,o,a,c,d)})()})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=mt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=d;const h=xT(),f=d?$T(o,h,a):KT(o,h,a),g=kT(r,f,d).toString(),v=DT(g).toString();return new Promise((m,p)=>P(l,void 0,void 0,function*(){var T,C;try{let _=!1;const S=x=>P(this,void 0,void 0,function*(){if(_)return;_=!0;const R=x instanceof Event?x.currentTarget:x,O=LT(R,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(O)).catch(U=>{this.log.error(U),this.close()}):this.close(),E(),p(De.cancelled(O))});c==null||c.addEventListener("abort",S);const E=()=>{clearTimeout(w),c==null||c.removeEventListener("abort",S)},w=setTimeout(()=>{S(De.timeout("room connection has timed out (signal)"))},a.websocketTimeout),k=(x,R)=>{this.handleSignalConnected(x,w,R)},y=new URL(g);y.searchParams.has("access_token")&&y.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(y),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WT(g);try{this.ws.closed.then(G=>{var W;this.isEstablishingConnection&&p(De.internal("Websocket got closed during a (re)connection attempt: ".concat(G.reason))),G.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:G.reason,code:G.closeCode,wasClean:G.closeCode===1e3,state:this.state})),this.state===mt.CONNECTED&&this.handleOnClose((W=G.reason)!==null&&W!==void 0?W:"Unexpected WS error"))}).catch(G=>{this.isEstablishingConnection&&p(De.internal("Websocket error during a (re)connection attempt: ".concat(G)))});const x=yield this.ws.opened.catch(G=>P(this,void 0,void 0,function*(){if(this.state!==mt.CONNECTED){this.state=mt.DISCONNECTED,clearTimeout(w);const W=yield this.handleConnectionError(G,v);p(W);return}this.handleWSError(G),p(G)}));if(clearTimeout(w),!x)return;const R=x.readable.getReader();this.streamWriter=x.writable.getWriter();const O=yield R.read();if(R.releaseLock(),!O.value)throw De.internal("no message received as first message");const U=Zp(O.value),q=this.validateFirstMessage(U,(T=a.reconnect)!==null&&T!==void 0?T:!1);if(!q.isValid){p(q.error);return}((C=U.message)===null||C===void 0?void 0:C.case)==="join"&&(this.pingTimeoutDuration=U.message.value.pingTimeout,this.pingIntervalDuration=U.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})));const $=q.shouldProcessFirstMessage?U:void 0;k(x,$),m(q.response)}catch(x){p(x)}finally{E()}}finally{u()}}))})()})}startReadingLoop(e,t){return P(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Yt(this.signalLatency));const{done:n,value:s}=yield e.read();if(n)break;const r=Zp(s);this.handleSignalResponse(r)}})}close(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([mt.DISCONNECTING||mt.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=mt.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Yt(XT)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=mt.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:cr(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:cr(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new no({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new io({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Ul({requestId:a,metadata:n,name:s,attributes:o})}),a})()})}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 Uf({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Vf({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Et.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Hf({timestamp:Et.parse(Date.now()),rtt:Et.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Ol({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ro({reason:Vn.CLIENT_INITIATED,action:Qs.DISCONNECT})})}sendRequest(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!jT(t)&&n.state===mt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Yt(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const o=new rx({message:t});try{n.useJSON?yield n.streamWriter.write(o.toJsonString()):yield n.streamWriter.write(o.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=nm(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=nm(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return P(this,void 0,void 0,function*(){if(this.state===mt.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Kt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Kt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Kt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Kt.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=mt.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,s,r,o,a;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===mt.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:De.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:De.internal("Unexpected first message")}:{isValid:!1,error:De.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return P(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:return De.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield n.text();return De.notAllowed(s,n.status);default:break}return e instanceof De?e:De.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof De?n:De.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function nm(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function cr(i,e){return new Hi({sdp:i.sdp,type:i.type,id:e})}function $T(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",si()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}function KT(i,e,t){const n=new URLSearchParams;n.set("access_token",i);const s=new wx({clientInfo:e,connectionSettings:new Wf({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new Ax({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}class im{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class YT{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const s=n+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Wn={},_d={},bd={exports:{}},sm;function yd(){if(sm)return bd.exports;sm=1;var i=bd.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),bd.exports}var rm;function JT(){return rm||(rm=1,(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},n=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;t(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=yd(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(_d)),_d}var Sd,am;function ZT(){if(am)return Sd;am=1;var i=yd(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Sd=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||s,l=a.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(n(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(n(u,h,f))})})}),o.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
4505
4505
  `)+`\r
4506
- `},Sd}var om;function QT(){if(om)return Wn;om=1;var i=JT(),e=ZT(),t=yd();return Wn.grammar=t,Wn.write=e,Wn.parse=i.parse,Wn.parseParams=i.parseParams,Wn.parseFmtpConfig=i.parseFmtpConfig,Wn.parsePayloads=i.parsePayloads,Wn.parseRemoteCandidates=i.parseRemoteCandidates,Wn.parseImageAttributes=i.parseImageAttributes,Wn.parseSimulcastStreamList=i.parseSimulcastStreamList,Wn}var Ki=QT();function xd(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!o){var C=i.apply(g,f);a&&a(C),d.forEach(function(_){return(0,_.resolve)(C)}),d=[]}},u()),p){var T=i.apply(g,f);return a&&a(T),v(T)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const eE=.7,tE=20,dr={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class cm extends ni.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=ze,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=xd(s=>P(this,void 0,void 0,function*(){this.emit(dr.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),tE),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=Ti((n=t.loggerName)!==null&&n!==void 0?n:Gn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new rn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=nE(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=Ki.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(o=>{const a=Td(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Ki.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(dr.NegotiationComplete),e.sdp&&Ki.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(dr.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=Ki.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{dm(a),a.type==="audio"?lm(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Hn(c.codec)&&!bs()&&this.ensureVideoDDExtensionForSVC(a,o),!Hn(c.codec)))return!0;const d=Math.round(c.maxbr*eE);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Ki.write(o)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Ki.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{dm(s),s.type==="audio"&&lm(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ki.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new It("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 It("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new nr(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(o=>o.uri===zp))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:zp})}}}function lm(i,e,t){const n=Td(i.mid);let s=0;i.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&i.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function nE(i){var e;const t=[],n=[],s=Ki.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=Td(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===r&&l.type==="nack")&&n.push(c),o.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:n}}function dm(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function Td(i){return typeof i=="number"?i.toFixed(0):i}const Ed="vp8",iE={audioPreset:Ql.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:td.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ed,backupCodec:!0,preConnectBuffer:!1},um={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},hm={deviceId:{ideal:"default"},resolution:Xr.h720.resolution},sE={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ox,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Cd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Mt;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(Mt||(Mt={}));class rE{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var s;this.peerConnectionTimeout=Cd.peerConnectionTimeout,this.log=ze,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=Mt.CONNECTED:c.some(l=>l==="failed")?this.state=Mt.FAILED:c.some(l=>l==="connecting")?this.state=Mt.CONNECTING:c.every(l=>l==="closed")?this.state=Mt.CLOSED:c.some(l=>l==="closed")?this.state=Mt.CLOSING:c.every(l=>l==="new")&&(this.state=Mt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Mt[a]," to ").concat(Mt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=Ti((s=n.loggerName)!==null&&s!==void 0?s:Gn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new cm(e,n),this._mode=t,t!=="publisher-only"&&(this.subscriber=new cm(e,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=Mt.NEW,this.connectionLock=new rn,this.remoteOfferLock=new rn}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){var n;t===zn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){var n,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(this,void 0,void 0,function*(){var n;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return P(this,void 0,void 0,function*(){return new hn((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n(new nr("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n(new nr("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(dr.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(dr.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?n(o):n(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return n==null?void 0:n.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===zn.PUBLISHER?this.publisher.getConnectedAddress():e===zn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Kt.clearTimeout(u),l(De.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Kt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(De.internal("could not establish pc connection"))},o);for(;this.state!==Mt.CONNECTED;)if(yield Yt(50),s!=null&&s.signal.aborted){l(De.cancelled("room connection has been cancelled"));return}Kt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))})()})}}const fm=5e3,aE=3e4;class Qe{static fetchRegionSettings(e,t,n){return P(this,void 0,void 0,function*(){const s=yield Qe.fetchLock.lock();try{const r=yield fetch("".concat(oE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(r.ok){const o=PT(r.headers),a=o?o*1e3:fm;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?De.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):De.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof De?r:n!=null&&n.aborted?De.cancelled("Region fetching was aborted"):De.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,n){return P(this,void 0,void 0,function*(){const s=Qe.settingsTimeouts.get(e.hostname);clearTimeout(s),Qe.settingsTimeouts.set(e.hostname,setTimeout(()=>P(this,void 0,void 0,function*(){try{const r=yield Qe.fetchRegionSettings(e,t);Qe.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof De&&r.reason===mt.NotAllowed){ze.debug("token is not valid, cancelling auto region refresh");return}ze.debug("auto refetching of region settings failed",{error:r}),Qe.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){Qe.cache.set(e.hostname,n),Qe.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=Qe.settingsTimeouts.get(e);t&&(clearTimeout(t),Qe.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Qe.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=Qe.connectionTrackers.get(e);n&&n.connectionCount===0&&(ze.debug("stopping region refetch after disconnect delay",{hostname:e}),Qe.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},aE))}static cancelCleanup(e){const t=Qe.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Qe.connectionTrackers.get(e);t||(t={connectionCount:0},Qe.connectionTrackers.set(e,t)),t.connectionCount++,Qe.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Qe.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Qe.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return ar(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){return Qe.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Qe.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Qe.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(n.length>0){const s=n[0];return this.attemptedRegions.push(s),ze.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Qe.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Qe.cache=new Map,Qe.settingsTimeouts=new Map,Qe.connectionTrackers=new Map,Qe.fetchLock=new rn;function oE(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class wt extends Error{constructor(e,t,n){super(t),this.code=e,this.message=mm(t,wt.MAX_MESSAGE_BYTES),this.data=n?mm(n,wt.MAX_DATA_BYTES):void 0}static fromProto(e){return new wt(e.code,e.message,e.data)}toProto(){return new Tf({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new wt(wt.ErrorCode[e],wt.ErrorMessage[e],t)}}wt.MAX_MESSAGE_BYTES=256,wt.MAX_DATA_BYTES=15360,wt.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},wt.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 pm=15360;function Md(i){return new TextEncoder().encode(i).length}function mm(i,e){if(Md(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}const wd=2e3;function bo(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const Ad=typeof MediaRecorder<"u";class cE{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const lE=Ad?MediaRecorder:cE;class dE extends lE{constructor(e,t){if(!Ad)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function uE(){return Ad}const hE=1e3,fE=1e4;class gm extends J{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.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=xd(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(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(re.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new rn,this.pauseUpstreamLock=new rn,this.trackChangeLock=new rn,this.trackChangeLock.lock().then(o=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==J.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{rr(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(sr(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{sr(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:hE;return(function*(){var n;if(e.kind===J.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=fn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Yt(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Yt(50)}throw new Ci("unable to get track dimensions after timeout")})()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Wi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Wi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===J.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===J.Kind.Audio?"audioinput":"videoinput";return t?jt.getInstance().normalizeDeviceId(r,n,s):n})()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ci("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=Ux(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===J.Kind.Video?o.video=n||s?{deviceId:n,facingMode:s}:!0:o.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{rr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===J.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(re.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?re.Muted:re.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hp()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(re.UpstreamPaused,this);const n=fn();if((n==null?void 0:n.name)==="Safari"&&ri(n.version,"12.0")<0)throw new Zl("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(re.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(sr(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(rr(n._mediaStreamTrack,l),sr(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(re.TrackProcessorUpdate,n.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}})()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(re.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!uE()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new dE(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},fE)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class yo extends gm{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,J.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=bo(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===J.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 P(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 n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Wi(this._constraints.deviceId);return this.source===J.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=id({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){pn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},wd)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!si()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(re.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return P(this,void 0,void 0,function*(){const e=yield Up(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(re.AudioSilenceDetected)),e})}}function pE(i,e,t){switch(i.kind){case"audio":return new yo(i,e,!1,void 0,t);case"video":return new So(i,e,!1,t);default:throw new Ci("unsupported track type: ".concat(i.kind))}}const mE=Object.values(Xr),gE=Object.values(ed),vE=Object.values(td),_E=[Xr.h180,Xr.h360],bE=[ed.h180,ed.h360],yE=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ht(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),Rd=["q","h","f"];function Pd(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=xE(i,e,t,l),ze.debug("using video encoding",o));const d=o.maxFramerate,u=new ht(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Hn(l)){const g=new bm(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=fn();if(Yr()||si()||(m==null?void 0:m.name)==="Chrome"&&ri(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,T=_T(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:Rd[2-C],maxBitrate:o.maxBitrate/Math.pow(p,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:T?Math.pow(2,C):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),ze.debug("using svc encoding",{encodings:v}),v}if(!a)return[o];let h=[];i?h=(s=_m(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:vm(i,u):h=(r=_m(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:vm(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return kd(e,t,[g,f,u],d);if(v>=480)return kd(e,t,[g,u],d)}return kd(e,t,[u])}function SE(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ze.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===J.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Pd(i.source===J.Source.ScreenShare,c,l,t)}function xE(i,e,t,n){const s=TE(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function TE(i,e,t){if(i)return vE;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?mE:gE}function vm(i,e){if(i)return yE(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?_E:bE}function kd(i,e,t,n){const s=[];if(t.forEach((r,o)=>{if(o>=Rd.length)return;const a=Math.min(i,e),l={rid:Rd[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=_s()||o===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),si()&&qp()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,ze.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ze.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function _m(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class bm{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function EE(i){return i.source===J.Source.ScreenShare||i.constraints.height&&Wi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const CE=5e3;class So extends gm{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,J.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(re.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=bo(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new rn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!pn())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},wd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Ei(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0)r=l.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Ei(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===J.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===J.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 P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let n=yn.LOW;n<=yn.HIGH;n+=1)t.push(new Fl({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Hn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o;let a;if(e){const u=id({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=Ei(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!1;const u=r;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=Ei(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){a={error:v}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},CE))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a,c;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(Hn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=Ei(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Hn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield ym(u.sender,u.encodings,d.qualities,this.senderLock,Hn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield ym(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,s)=>{var r;return Object.assign(Object.assign({},n),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Hn(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hp()&&this.isInBackground&&this.source===J.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ym(i,e,t,n,s,r,o){return P(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:i,qualities:t,senderEncodings:e}));try{const c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=Sm(v),p=t.find(T=>T.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),o),_s()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield i.setParameters(c))}finally{a()}})}function Sm(i){switch(i){case"f":return yn.HIGH;case"h":return yn.MEDIUM;case"q":return yn.LOW;default:return yn.HIGH}}function xm(i,e,t,n){if(!t)return[new Gi({quality:yn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new bm(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)o.push(new Gi({quality:Math.min(yn.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=Sm((o=s.rid)!==null&&o!==void 0?o:"");return new Gi({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Tm="_lossy",Em="_reliable",ME=2*1e3,Id="leave-reconnect",wE=3e4,AE=8*1024,RE=256*1024;var Pn;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Pn||(Pn={}));class PE extends ni.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Cd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Pn.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=ze,this.reliableDataSequence=1,this.reliableMessageBuffer=new im,this.reliableReceivedState=new YT(wE),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Em)r.reliableDCSub=o;else if(o.label===Tm)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r,o,a,c;const l=yield this.dataProcessLock.lock();try{let d;if(n.data instanceof ArrayBuffer)d=n.data;else if(n.data instanceof Blob)d=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const u=an.fromBinary(new Uint8Array(d));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(oe.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=yf.fromBinary(h.payload),g=new an({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&Cm(g,g.value.value),this.emit(oe.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Cm(u,u.value.value),this.emit(oe.DataPacketReceived,u,Gt.NONE)}finally{l()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?je.LOSSY:je.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(oe.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===Id&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Kt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Pn.Connected&&n();const r=()=>{this.off(oe.Disconnected,o),n()},o=()=>{this.off(oe.Restarted,r),s()};this.once(oe.Restarted,r),this.once(oe.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{if(n===je.RELIABLE){const r=this.dataChannelForKind(n);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(oe.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>P(this,void 0,void 0,function*(){!this.url||!(yield fetch(Zr(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===gt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===gt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ms.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>P(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Zr(this.url),{method:"HEAD"}),Yt(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ti((t=e.loggerName)!==null&&t!==void 0?t:Gn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new vd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new rn,this.dataProcessLock=new rn,this.dcBufferStatus=new Map([[je.LOSSY,!0],[je.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(oe.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(oe.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(oe.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(oe.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(oe.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(oe.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(oe.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(oe.SignalRequestResponse,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l.url=r,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const u=yield l.client.join(r,o,a,c,d);return l._isClosed=!1,l.latestJoinResponse=u,l.subscriberPrimary=u.subscriberPrimary,l.pcManager||(yield l.configure(u,!d)),(!l.subscriberPrimary||u.fastPublish)&&l.negotiate().catch(h=>{ze.error(h,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=u.clientConfiguration,l.emit(oe.SignalConnected,u),u}catch(u){if(u instanceof De){if(u.reason===mt.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(r,o,a,c,d)}else if(u.reason===mt.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),l.join(r,o,a,c,!0)}throw u}})()})}close(){return P(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(oe.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new im,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ci("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(De.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return P(this,void 0,void 0,function*(){var n,s;if(this.pcManager&&this.pcManager.currentState!==Mt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new rE(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(oe.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===Mt.CONNECTED){const u=this.pcState===Pn.New;this.pcState=Pn.Connected,u&&this.emit(oe.Connected,e)}else o===Mt.FAILED&&(this.pcState===Pn.Connected||this.pcState===Pn.Reconnecting)&&(this.pcState=Pn.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ms.RR_SUBSCRIBER_FAILED:ms.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===gt.RECONNECTING,d=[Mt.FAILED,Mt.CLOSING,Mt.CLOSED].includes(o);l&&d&&!this._isClosed&&this.emit(oe.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(oe.MediaTrackAdded,o.track,o.streams[0],o.receiver)},kE((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),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,t,n)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(oe.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(oe.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(oe.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(oe.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(oe.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ms.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:fm,regionSettings:e.regions})),e.action){case er.DISCONNECT:this.emit(oe.Disconnected,e==null?void 0:e.reason),this.close();break;case er.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Id);break;case er.RESUME:this.handleDisconnect(Id)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Gr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Tm,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Em,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(je.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,AE),RE)}},1e3))}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(rd())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ad())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new It("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(rd())return this.createSimulcastTransceiverSender(e,t,n,s);if(ad())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new It("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),qi(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){ze.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Gr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:Mt.NEW)===Mt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof It?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof ir||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",ms.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(oe.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 P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new It("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(oe.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ir;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof De&&o.reason===mt.NotAllowed?new It("could not reconnect, token might be expired"):new ir}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(oe.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==gt.CONNECTED)throw new ir("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(oe.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new It("could not reconnect, url or token not saved");if(!this.pcManager)throw new It("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(oe.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof De&&s.reason===mt.NotAllowed?new It("could not reconnect, token might be expired"):s instanceof De&&s.reason===mt.LeaveRequest?s:new ir(r)}if(this.emit(oe.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}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!==gt.CONNECTED)throw new ir("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(oe.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=Pn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Yt(ME),!this.pcManager)throw new It("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Pn.Connected}catch(e){throw this.pcState=Pn.Disconnected,De.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcResponse",value:new kl({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,je.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcAck",value:new Pl({requestId:t})}});yield this.sendDataPacket(n,je.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=BT(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new bf({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===je.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===je.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=n.byteLength}if(this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(je.RELIABLE);const t=this.dataChannelForKind(je.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(je.RELIABLE)})}waitForBufferStatusLow(e){return new hn((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n(new It("engine closed"));for(this.once(oe.Closing,s);!this.dcBufferStatus.get(e);)yield Yt(10);this.off(oe.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!n.pcManager)throw new It("PC manager is closed");const o=s?n.pcManager.subscriber:n.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw De.internal("".concat(a," connection not set"));let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate().catch(u=>{ze.error(u,n.logContext)});const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Yt(50)}throw De.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Mt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new hn((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new nr("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new nr("cannot negotiate on closed engine")),this.on(oe.Closing,s),this.pcManager.publisher.once(dr.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();TT(c)&&o.set(a.payload,c)}),this.emit(oe.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof nr&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ms.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(oe.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===je.LOSSY)return this.lossyDCSub;if(e===je.RELIABLE)return this.reliableDCSub}else{if(e===je.LOSSY)return this.lossyDC;if(e===je.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(n=this.pcManager.subscriber)===null||n===void 0?void 0:n.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Bl({answer:this.pcManager.mode==="publisher-only"?c?lr({sdp:c.sdp,type:c.type}):void 0:d?lr({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?lr({sdp:a.sdp,type:a.type}):void 0:l?lr({sdp:l.sdp,type:l.type}):void 0,subscription:new ro({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:aT(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,v)=>new zf({publisherSid:v,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Gf({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(je.LOSSY),zn.PUBLISHER),t(this.dataChannelForKind(je.RELIABLE),zn.PUBLISHER),t(this.dataChannelForKind(je.LOSSY,!0),zn.SUBSCRIBER),t(this.dataChannelForKind(je.RELIABLE,!0),zn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Kt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){pn()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){pn()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===n});if(s)return s[1]}}}function kE(i){return i!==void 0&&i>13}function Cm(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Mm{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new An("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),on.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new An("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),on.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class IE extends Mm{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Rn,n=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),n=o}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=Ei(c),u;u=yield d.next(),n=u.done,!n;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class DE extends Mm{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=_o(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Rn,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new An("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),on.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return P(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=Ei(c),u;u=yield d.next(),n=u.done,!n;l=!0)o=u.value,l=!1,a+=o}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return a})()})}}class LE{constructor(){this.log=ze,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new An('A text stream handler for topic "'.concat(e,'" has already been set.'),on.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new An('A byte stream handler for topic "'.concat(e,'" has already been set.'),on.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new An("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),on.AbnormalEnd);for(const[l,d]of a)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e,t){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return P(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const a=new Rn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:_o(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new An("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),on.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new IE(c,l,_o(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const a=new Rn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new An("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),on.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new DE(c,l,_o(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),on.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),on.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),on.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),on.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class wm{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class NE extends wm{}class OE extends wm{}const Am=15e3;class UE{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?Gt.GCM:Gt.NONE},a=new eo({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:ys(o.timestamp),totalLength:ys(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new If({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Il.UPDATE:Il.CREATE})}}),c=e==null?void 0:e.destinationIdentities,l=new an({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,je.RELIABLE);let d=0;const u=this.engine,h=new WritableStream({write(v){return P(this,void 0,void 0,function*(){for(const m of RT(v,Am)){const p=new to({content:m,streamId:r,chunkIndex:ys(d)}),T=new an({destinationIdentities:c,value:{case:"streamChunk",value:p}});yield u.sendDataPacket(T,je.RELIABLE),d+=1}})},close(){return P(this,void 0,void 0,function*(){const v=new no({streamId:r}),m=new an({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(m,je.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>P(this,void 0,void 0,function*(){yield g.close()});u.once(oe.Closing,f);const g=new NE(h,o,()=>this.engine.off(oe.Closing,f));return g})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,d={id:c,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Gt.GCM:Gt.NONE},u=new eo({totalLength:ys((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:ys(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Df({name:d.name})}}),h=new an({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,je.RELIABLE);let f=0;const g=new rn,v=this.engine,m=this.log,p=new WritableStream({write(C){return P(this,void 0,void 0,function*(){const _=yield g.lock();let S=0;try{for(;S<C.byteLength;){const E=C.slice(S,S+Am),w=new an({destinationIdentities:l,value:{case:"streamChunk",value:new to({content:E,streamId:c,chunkIndex:ys(f)})}});yield v.sendDataPacket(w,je.RELIABLE),f+=1,S+=E.byteLength}}finally{_()}})},close(){return P(this,void 0,void 0,function*(){const C=new no({streamId:c}),_=new an({destinationIdentities:l,value:{case:"streamTrailer",value:C}});yield v.sendDataPacket(_,je.RELIABLE)})},abort(C){m.error("Sink error:",C)}});return new OE(p,d)})}}class Rm extends J{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(re.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),wd)),oT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(re.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class FE extends Rm{constructor(e,t,n,s,r,o){super(e,t,J.Kind.Audio,n,o),this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=bo(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;si()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(si())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(od(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&od(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(re.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(re.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Dd=100;class BE extends Rm{constructor(e,t,n,s,r){super(e,t,J.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=bo(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=xd(()=>{this.updateDimensions()},Dd),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===J.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?rr(this._mediaStreamTrack,t):sr(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new VE(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const s=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<Dd){Kt.setTimeout(()=>{this.updateVisibility()},Dd);return}this.lastVisible=a,this.emit(re.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(re.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?jp():t||(jp()>2?2:1)}}class VE{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.isPiP=ta(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ta(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=ta(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Ld(e),this.isPiP=pn()&&ta(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Ld(this.element),this.isPiP=ta(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,$p().observe(this.element),Xp().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,s,r;(e=$p())===null||e===void 0||e.unobserve(this.element),(t=Xp())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ta(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ld(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ld(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,o=i.offsetHeight,{hidden:a}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class wi extends ni.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=Gt.NONE,this.log=ze,this.handleMuted=()=>{this.emit(re.Muted)},this.handleUnmuted=()=>{this.emit(re.Unmuted)},this.log=Ti((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Gn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=J.Source.Unknown}setTrack(e){this.track&&(this.track.off(re.Muted,this.handleMuted),this.track.off(re.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(re.Muted,this.handleMuted),e.on(re.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),$e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Gt.NONE}get audioTrack(){if(ai(this.track))return this.track}get videoTrack(){if(qi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=J.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===J.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(wi||(wi={}));class Nd extends wi{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(re.Ended)},this.handleCpuConstrained=()=>{this.track&&qi(this.track)&&this.emit(re.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(re.Ended,this.handleTrackEnded),this.track.off(re.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(re.Ended,this.handleTrackEnded),e.on(re.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ai(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(qt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(qt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(qt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(qt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(qt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(qt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function xo(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Bp(i);let o=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Op(r,um,hm),l=id(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&(jt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>jt.userMediaPromiseMap.delete("audioinput"))),r.video&&(jt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>jt.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Wi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const T=pE(h,v,e);return T.kind===J.Kind.Video?T.source=J.Source.Camera:T.kind===J.Kind.Audio&&(T.source=J.Source.Microphone),T.mediaStream=u,ai(T)&&n?yield T.setProcessor(n):qi(T)&&s&&(yield T.setProcessor(s)),T})))}catch(u){if(!t)throw u;return xo(Object.assign(Object.assign({},i),{audio:o,video:a}),e)}})}function zE(i){return P(this,void 0,void 0,function*(){return(yield xo({audio:!1,video:!0}))[0]})}function GE(i){return P(this,void 0,void 0,function*(){return(yield xo({audio:!0,video:!1}))[0]})}var Yi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(Yi||(Yi={}));function HE(i){switch(i){case zr.EXCELLENT:return Yi.Excellent;case zr.GOOD:return Yi.Good;case zr.POOR:return Yi.Poor;case zr.LOST:return Yi.Lost;default:return Yi.Unknown}}class Pm extends ni.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Hr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Zs.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Hr.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Yi.Unknown,this.log=ze,this.log=Ti((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Gn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}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}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Rn,this.once(ce.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(J.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(J.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(J.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Zs.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Zs.ACTIVE&&this.emit(ce.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(ce.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(ce.ParticipantNameChanged,e)}_setAttributes(e){const t=cT(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ce.AttributesChanged,t)}setPermissions(e){var t,n,s,r,o,a;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(ce.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ce.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=HE(e),t!==this._connectionQuality&&this.emit(ce.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ai(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(re.Muted,()=>{this.emit(ce.TrackMuted,e)}),e.on(re.Unmuted,()=>{this.emit(ce.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case J.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case J.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function WE(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Bf({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class qE extends Pm{constructor(e,t,n,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Gt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Rn)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Rn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==Vl.OK&&u.reject(new Lp(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=wt.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},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(a=>WE(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),$e(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),$e(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),$e(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),$e(c))),this.emit(ce.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var v=!0,m=Ei(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const T=u;iT(T)&&(this.log.debug("publish ".concat(T," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),$e(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,T,f.options))}}catch(T){l={error:T}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>P(this,void 0,void 0,function*(){if(a.source===J.Source.ScreenShare||a.source===J.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),$e(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Mi(a)||ji(a))try{if(pn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===J.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),$e(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),$e(a))),Mi(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),$e(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Gt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(oe.RemoteMute,(n,s)=>{const r=this.trackPublications.get(n);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(oe.Connected,this.handleReconnected).on(oe.SignalConnected,this.handleSignalConnected).on(oe.SignalRestarted,this.handleReconnected).on(oe.SignalResumed,this.handleReconnected).on(oe.Restarting,this.handleReconnecting).on(oe.Resuming,this.handleReconnecting).on(oe.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(oe.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(oe.Closing,this.handleClosing).on(oe.SignalRequestResponse,this.handleSignalRequestResponse).on(oe.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new hn((a,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),a();return}yield Yt(50)}c(new Lp("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(J.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(J.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(J.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?Gt.GCM:Gt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,o;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 c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case J.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case J.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case J.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ci(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(ce.MediaDevicesError,l,sd(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===J.Source.Microphone&&ai(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),$e(u))),l.push(this.publishTrack(u,s));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&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===J.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(J.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(J.Source.Camera)||this.pendingPublishing.has(J.Source.Microphone))){this.pendingPublishing.add(J.Source.Camera),this.pendingPublishing.add(J.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(J.Source.Camera),this.pendingPublishing.delete(J.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Op(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield xo(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(ai(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=J.Source.Microphone,this.emit(ce.AudioStreamAcquired)),qi(a)&&(this.cameraError=void 0,a.source=J.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Zl("getDisplayMedia not supported");e.resolution===void 0&&!vT()&&(e.resolution=td.h1080fps30.resolution);const t=rT(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new Ci("no video track found");const r=new So(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=J.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(ce.AudioStreamAcquired);const a=new yo(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=J.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Mi(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),or(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case J.Source.Microphone:p="audioinput";break;case J.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new yo(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new So(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new Ci("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),$e(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:g;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),$e(n))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(d=f.red)!==null&&d!==void 0||(f.red=!1)),!bT()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((p,T)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==gt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:$e(n)}));let C=!1;const _=setTimeout(()=>{C=!0,n.stop(),T(new Dp("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(_),C)return;const S=yield this.publish(n,f,v);p(S)}else try{const C=yield this.publish(n,f,v);p(C)}catch(C){T(C)}}catch(C){T(C)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Rn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),$e(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>lT(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),$e(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Dp("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>or(e)&&y.source===e.source)&&e.source!==J.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),$e(e))),t.stopMicTrackOnMute&&ai(e)&&(e.stopOnMute=!0),e.source===J.Source.ScreenShare&&_s()&&(t.simulcast=!1),t.videoCodec==="av1"&&!pT()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!mT()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ed),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===$r(y.mime))||(t.videoCodec=$r(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(re.Muted,this.onTrackMuted),e.on(re.Unmuted,this.onTrackUnmuted),e.on(re.Ended,this.handleTrackEnded),e.on(re.UpstreamPaused,this.onTrackUpstreamPaused),e.on(re.UpstreamResumed,this.onTrackUpstreamResumed),e.on(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),T=e.getSourceTrackSettings();T.autoGainControl&&m.push(qt.TF_AUTO_GAIN_CONTROL),T.echoCancellation&&m.push(qt.TF_ECHO_CANCELLATION),T.noiseSuppression&&m.push(qt.TF_NOISE_SUPPRESSION),T.channelCount&&T.channelCount>1&&m.push(qt.TF_STEREO),p&&m.push(qt.TF_NO_DTX),Mi(e)&&e.hasPreConnectBuffer&&m.push(qt.TF_PRECONNECT_BUFFER);const C=new Wr({cid:e.mediaStreamTrack.id,name:t.name,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let _;if(e.kind===J.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Xr.h720.resolution;y={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{dims:y}))}C.width=y.width,C.height=y.height,ji(e)&&(Hn(v)&&(e.source===J.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),$e(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new Ll({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ed}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===Gt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new Ll({codec:t.backupCodec.codec,cid:""})))),_=Pd(e.source===J.Source.ScreenShare,C.width,C.height,t),C.layers=xm(C.width,C.height,_,Hn(t.videoCodec))}else e.kind===J.Kind.Audio&&(_=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new It("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var y,x,R;if(!this.engine.pcManager)throw new It("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,_),this.emit(ce.LocalSenderCreated,e.sender,e),ji(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=EE(e)),e.setDegradationPreference(t.degradationPreference)),_)if(_s()&&e.kind===J.Kind.Audio){let O;for(const U of this.engine.pcManager.publisher.getTransceivers())if(U.sender===e.sender){O=U;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((x=_[0])===null||x===void 0)&&x.maxBitrate?_[0].maxBitrate/1e3:0})}else e.codec&&Hn(e.codec)&&(!((R=_[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:_[0].maxBitrate/1e3});yield this.engine.negotiate()});let E;const w=new Promise((y,x)=>P(this,void 0,void 0,function*(){var R;try{E=yield this.engine.addTrack(C),y(E)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(U=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{error:U}))})),x(O)}}));if(this.enabledPublishVideoCodecs.length>0)E=(yield Promise.all([w,S()]))[0];else{E=yield w;let y;if(E.codecs.forEach(x=>{y===void 0&&(y=x.mimeType)}),y&&e.kind===J.Kind.Video){const x=$r(y);x!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{codec:x})),t.videoCodec=x,_=Pd(e.source===J.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new Nd(e.kind,E,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(re.CpuConstrained,y=>this.onTrackCpuConstrained(y,k)),k.options=t,e.sid=E.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:_,trackInfo:E})),ji(e)?e.startMonitor(this.engine.client):Mi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(ce.LocalTrackPublished,k),Mi(e)&&E.audioFeatures.includes(qt.TF_PRECONNECT_BUFFER)){const y=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(ce.LocalTrackSubscribed,R=>{if(R.trackSid===E.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),$e(e))),e.stopPreConnectBuffer()}}),y&&new Promise((O,U)=>P(this,void 0,void 0,function*(){var q,$,G,W,ee,ge;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),$e(e)));const Fe=setTimeout(()=>{U(new Error("agent not active within 10 seconds"))},1e4),Tt=yield this.waitUntilActiveAgentPresent();clearTimeout(Fe),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),$e(e)));const ft=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Tt.identity],attributes:{trackId:k.trackSid,sampleRate:String((ee=T.sampleRate)!==null&&ee!==void 0?ee:"48000"),channels:String((ge=T.channelCount)!==null&&ge!==void 0?ge:"1")}});try{for(var le=!0,_e=Ei(y),Be;Be=yield _e.next(),q=Be.done,!q;le=!0){W=Be.value,le=!1;const K=W;yield ft.write(K)}}catch(K){$={error:K}}finally{try{!le&&!q&&(G=_e.return)&&(yield G.call(_e))}finally{if($)throw $.error}}yield ft.close(),O()}catch(Fe){U(Fe)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),$e(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==Gt.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new Ci("track is not published");if(!ji(e))throw new Ci("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=SE(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),$e(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const l=new Wr({cid:c.mediaStreamTrack.id,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=xm(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new It("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(or(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),$e(e))),yield l)}const r=this.getPublicationForTrack(e),o=r?$e(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(re.Muted,this.onTrackMuted),e.off(re.Unmuted,this.onTrackUnmuted),e.off(re.Ended,this.handleTrackEnded),e.off(re.UpstreamPaused,this.onTrackUpstreamPaused),e.off(re.UpstreamResumed,this.onTrackUpstreamResumed),e.off(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Mt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ji(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case J.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case J.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(ce.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new hn((r,o)=>P(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==J.Source.ScreenShare&&l.source!==J.Source.ScreenShareAudio&&(Mi(l)||ji(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?je.RELIABLE:je.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new Al({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:a});const l=new an({kind:r,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new an({kind:je.RELIABLE,value:{case:"sipDtmf",value:new xf({code:e,digit:t})}});yield this.engine.sendDataPacket(n,je.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new an({value:{case:"chatMessage",value:new Qa(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,je.RELIABLE),this.emit(ce.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new an({value:{case:"chatMessage",value:new Qa(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp),editTimestamp:Et.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,je.RELIABLE),this.emit(ce.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new hn((c,l)=>P(this,void 0,void 0,function*(){var d,u,h,f;if(Md(s)>pm){l(wt.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&ri((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(wt.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,n,s,g);const m=setTimeout(()=>{this.pendingAcks.delete(v),l(wt.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},o);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(v),l(wt.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(T,C)=>{clearTimeout(p),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),C?l(C):c(T??"")},participantIdentity:t})}))}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&&arguments[1]!==void 0?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,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const o=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcRequest",value:new Rl({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,je.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,wt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),$e(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,n,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Rn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(Mi(s)||ji(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Yt(20)}})}}class jE extends wi{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(re.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new ro({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ef({participantSid:"",trackSids:[this.trackSid]})]});this.emit(re.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?wi.SubscriptionStatus.Unsubscribed:super.isSubscribed?wi.SubscriptionStatus.Subscribed:wi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?wi.PermissionStatus.Allowed:wi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(fd(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&fd(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:yn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(re.VisibilityChanged,this.handleVisibilityChange),s.off(re.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(re.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(re.VisibilityChanged,this.handleVisibilityChange),e.on(re.Ended,this.handleEnded),this.emit(re.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(re.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?re.Muted:re.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(re.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(re.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return fd(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Nf({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===J.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Vp(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=dT(this.trackInfo,this.requestedMaxQuality);n&&Vp(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:yn.HIGH})),e.quality=yn.HIGH)}this.emit(re.UpdateSettings,e)}}class To extends Pm{static fromParticipantInfo(e,t,n){return new To(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Hr.STANDARD;super(t,n||"",s,r,o,a,c),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(re.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(re.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(re.SubscriptionPermissionChanged,t=>{this.emit(ce.TrackSubscriptionPermissionChanged,e,t)}),e.on(re.SubscriptionStatusChanged,t=>{this.emit(ce.TrackSubscriptionStatusChanged,e,t)}),e.on(re.Subscribed,t=>{this.emit(ce.TrackSubscribed,t,e)}),e.on(re.Unsubscribed,t=>{this.emit(ce.TrackUnsubscribed,t,e)}),e.on(re.SubscriptionFailed,t=>{this.emit(ce.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:J.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:J.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ce.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),$e(a))),this.emit(ce.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new BE(e,t,s,r):l=new FE(e,t,s,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(n),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&hd(l)&&ai(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=J.kindFromProto(s.type);if(!c)return;a=new jE(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==J.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:$e(l),newTrack:$e(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),$e(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(ce.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case J.Kind.Audio:this.audioTrackPublications.delete(e);break;case J.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(ce.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;ai(n.track)&&hd(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var rt;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(rt||(rt={}));const XE=4*1e3;class ur extends ni.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,s,r,o;if(super(),t=this,this.state=rt.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ze,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,l)=>P(this,void 0,void 0,function*(){var d;if(!gT())throw si()?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 u=yield this.disconnectLock.lock();if(this.state===rt.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(rt.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==Jp(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ar(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Qe(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,v,m)=>P(this,void 0,void 0,function*(){var p,T;this.abortController&&this.abortController.abort();const C=new AbortController;this.abortController=C,u==null||u();try{if(yield cr.getInstance().getBackOffPromise(a),C.signal.aborted)throw De.cancelled("Connection attempt aborted");yield this.attemptConnection(m??a,c,l,C),this.abortController=void 0,g()}catch(_){if(this.regionUrlProvider&&_ instanceof De&&_.reason!==mt.Cancelled&&_.reason!==mt.NotAllowed){let S=null;try{this.log.debug("Fetching next region"),S=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(E){if(E instanceof De&&(E.status===401||E.reason===mt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(E);return}}[mt.InternalError,mt.ServerUnreachable,mt.Timeout].includes(_.reason)&&(this.log.debug("Adding failed connection attempt to back off"),cr.getInstance().addFailedConnectionAttempt(a)),S&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield h(g,v,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Yp(_)),v(_))}else{let S=Vn.UNKNOWN_REASON;_ instanceof De&&(S=Yp(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),v(_)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Rn((g,v)=>{h(g,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,l,d,u,h)=>P(this,void 0,void 0,function*(){var f,g,v;const m=yield l.join(a,c,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},h.signal,!u.singlePeerConnection);let p=m.serverInfo;if(p||(p={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(T=>{let[C,_]=T;return"".concat(C,": ").concat(_)}).join(", ")),{room:(f=m.room)===null||f===void 0?void 0:f.name,roomSid:(g=m.room)===null||g===void 0?void 0:g.sid,identity:(v=m.participant)===null||v===void 0?void 0:v.identity}),!p.version)throw new Zx("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,l,d)=>P(this,void 0,void 0,function*(){var u,h;this.state===rt.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Cd),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(te.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=d.signal.aborted?De.cancelled("Signal connection aborted"):De.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof De&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),De.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}pn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),pn()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(rt.Connected),this.emit(te.Connected),cr.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];return P(t,[...c],void 0,function(){var d=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const v=yield d.disconnectLock.lock();try{if(d.state===rt.Disconnected){d.log.debug("already disconnected",d.logContext);return}if(d.log.info("disconnect from room",Object.assign({},d.logContext)),d.state===rt.Connecting||d.state===rt.Reconnecting||d.isResuming){const m="Abort connection attempt due to user initiated disconnect";d.log.warn(m,d.logContext),(h=d.abortController)===null||h===void 0||h.abort(m),(g=(f=d.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,De.cancelled("Client initiated disconnect")),d.connectFuture=void 0}d.engine&&(d.engine.client.isDisconnected||(yield d.engine.client.sendLeave()),yield d.engine.close()),d.handleDisconnect(u,Vn.CLIENT_INITIATED),d.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],c=fn();if(c&&c.os==="iOS"){const l="livekit-dummy-audio-el";let d=document.getElementById(l);if(!d){d=document.createElement("audio"),d.id=l,d.autoplay=!0,d.hidden=!0;const u=ud();u.enabled=!0;const h=new MediaStream([u]);d.srcObject=h,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(te.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(l=>{var d;(d=l.track)===null||d===void 0||d.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(rt.Reconnecting)&&this.emit(te.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(rt.Connected),this.emit(te.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var l;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(l=this.sidToIdentity.get(c.sid))!==null&&l!==void 0?l:"");let d=this.remoteParticipants.get(c.identity);c.state===Zs.DISCONNECTED?this.handleParticipantDisconnected(c.identity,d):d=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],l={};a.forEach(d=>{if(l[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(d.sid);u&&(u.audioLevel=d.level,u.setIsSpeaking(!0),c.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{l[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(te.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(d=>{const u=this.remoteParticipants.get(d.identity);u&&u.sid!==d.sid||c.set(d.sid,d)}),a.forEach(d=>{let u=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=d.level,u.setIsSpeaking(d.active),d.active?c.set(d.sid,u):c.delete(d.sid))});const l=Array.from(c.values());l.sort((d,u)=>u.audioLevel-d.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(te.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);if(!d||!d.track)return;const u=J.streamStateFromProto(c.state);d.track.setStreamState(u),u!==d.track.streamState&&(l.emit(ce.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(te.TrackStreamStateChanged,d,d.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const l=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(l,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(l,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(l,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(l,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,l);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const d=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,d.id,d.method,d.payload,d.responseTimeoutMs,d.version)}},this.handleUserPacket=(a,c,l,d)=>{this.emit(te.DataReceived,c.payload,a,l,c.topic,d),a==null||a.emit(ce.DataReceived,c.payload,l,d)},this.handleSipDtmf=(a,c)=>{this.emit(te.SipDTMFReceived,c,a),a==null||a.emit(ce.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const l=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),d=l==null?void 0:l.trackPublications.get(c.trackId),u=CT(c,this.transcriptionReceivedTimes);d==null||d.emit(re.TranscriptionReceived,u),l==null||l.emit(ce.TranscriptionReceived,u,d),this.emit(te.TranscriptionReceived,u,l,d)},this.handleChatMessage=(a,c)=>{const l=MT(c);this.emit(te.ChatMessage,l,a)},this.handleMetrics=(a,c)=>{this.emit(te.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(te.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(te.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(te.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(te.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=fn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(te.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(te.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(te.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const l=this.getRemoteParticipantBySid(c.participantSid);l&&l.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(te.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(te.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(te.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(te.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(te.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h,f;(c=a.track)===null||c===void 0||c.on(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(re.Restarted,this.onLocalTrackRestarted),(h=(u=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(te.LocalTrackPublished,a,this.localParticipant),Mi(a.track)&&(yield a.track.checkForSilence())&&this.emit(te.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=sd(a.source);v&&g&&g!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,g),this.emit(te.ActiveDeviceChanged,v,g))}),this.onLocalTrackUnpublished=a=>{var c,l;(c=a.track)===null||c===void 0||c.off(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(re.Restarted,this.onLocalTrackRestarted),this.emit(te.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),l=sd(a.source);l&&c&&c!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,c),this.emit(te.ActiveDeviceChanged,l,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(te.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(te.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(te.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(te.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},sE),e),this.log=Ti((n=this.options.loggerName)!==null&&n!==void 0?n:Gn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},um),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},hm),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},iE),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new LE,this.outgoingDataStreamManager=new UE(this.engine,this.log),this.disconnectLock=new rn,this.localParticipant=new qE("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Wi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Wi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Wi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),pn()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),ur.cleanupRegistry&&ur.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}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)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new VT(n,t),this.e2eeManager.on($i.ParticipantEncryptionStatusChanged,(s,r)=>{AT(r)&&(this.isE2EEEnabled=s),this.emit(te.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on($i.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(te.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===rt.Disconnected?hn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?hn.resolve(this.roomInfo.sid):new hn((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(oe.RoomUpdate,n),e(s.sid))};this.engine.on(oe.RoomUpdate,n),this.once(te.Disconnected,()=>{this.engine.off(oe.RoomUpdate,n),t(new It("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new PE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(oe.ParticipantUpdate,this.handleParticipantUpdates).on(oe.RoomUpdate,this.handleRoomUpdate).on(oe.SpeakersChanged,this.handleSpeakersChanged).on(oe.StreamStateChanged,this.handleStreamStateUpdate).on(oe.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(oe.SubscriptionError,this.handleSubscriptionError).on(oe.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(oe.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(oe.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(oe.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(oe.DataPacketReceived,this.handleDataPacket).on(oe.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(rt.SignalReconnecting)&&this.emit(te.SignalReconnecting)}).on(oe.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(rt.Connected)&&this.emit(te.Reconnected)}).on(oe.SignalResumed,()=>{this.bufferedEvents=[],(this.state===rt.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(oe.Restarting,this.handleRestarting).on(oe.SignalRestarted,this.handleSignalRestarted).on(oe.Offline,()=>{this.setAndEmitConnectionState(rt.Reconnecting)&&this.emit(te.Reconnecting)}).on(oe.DCBufferStatusChanged,(e,t)=>{this.emit(te.DCBufferStatusChanged,e,t)}).on(oe.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(ce.LocalTrackSubscribed,t),this.emitWhenConnected(te.LocalTrackSubscribed,t,this.localParticipant)}).on(oe.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(te.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return jt.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===rt.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ar(new URL(e))&&t){this.regionUrlProvider=new Qe(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===rt.Disconnected&&(this.regionUrl=n,yield fetch(Zr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Zr(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>P(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new ti({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new ti({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new ti({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new ti({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=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ti({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ti({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new ti({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new ao({reason:Vn.CLIENT_INITIATED,action:er.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new ti({scenario:{case:"subscriberBandwidth",value:ys(t)}});break;case"leave-full-reconnect":s=new ti({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,v=!1;const m=o?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.audioTrackPublications.values()).filter(_=>_.source===J.Source.Microphone);try{g=(yield Promise.all(T.map(_=>{var S;return(S=_.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(_=>_===!0)}catch(_){throw r.options.audioCaptureDefaults.deviceId=p,_}const C=T.some(_=>{var S,E;return(E=(S=_.track)===null||S===void 0?void 0:S.isMuted)!==null&&E!==void 0?E:!1});g&&C&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.videoTrackPublications.values()).filter(_=>_.source===J.Source.Camera);try{g=(yield Promise.all(T.map(_=>{var S;return(S=_.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(_=>_===!0)}catch(_){throw r.options.videoCaptureDefaults.deviceId=p,_}const C=T.some(_=>{var S,E;return(E=(S=_.track)===null||S===void 0?void 0:S.isMuted)!==null&&E!==void 0?E:!1});g&&C&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!od()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield jt.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(T=>T.setAudioOutput({deviceId:s})))}catch(T){throw r.options.audioOutput.deviceId=p,T}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(te.ActiveDeviceChanged,n,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ce.AttributesChanged,this.onLocalAttributesChanged).on(ce.TrackMuted,this.onLocalTrackMuted).on(ce.TrackUnmuted,this.onLocalTrackUnmuted).on(ce.LocalTrackPublished,this.onLocalTrackPublished).on(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ce.MediaDevicesError,this.onMediaDevicesError).on(ce.AudioStreamAcquired,this.startAudio).on(ce.ChatMessage,this.onLocalChatMessageSent).on(ce.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===rt.Connecting||this.state===rt.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(te.Reconnected,u),this.off(te.Connected,u),this.off(te.Disconnected,h)};this.once(te.Reconnected,u),this.once(te.Connected,u),this.once(te.Disconnected,h);return}if(this.state===rt.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=fT(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,a,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(te.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==rt.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ce.AttributesChanged,this.onLocalAttributesChanged).off(ce.TrackMuted,this.onLocalTrackMuted).off(ce.TrackUnmuted,this.onLocalTrackUnmuted).off(ce.LocalTrackPublished,this.onLocalTrackPublished).off(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ce.MediaDevicesError,this.onMediaDevicesError).off(ce.AudioStreamAcquired,this.startAudio).off(ce.ChatMessage,this.onLocalChatMessageSent).off(ce.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),pn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||s===void 0||s.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(rt.Disconnected),this.emit(te.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(te.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,o){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,wt.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,t,null,wt.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Md(d)>pm?(c=wt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof wt?c=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=wt.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=jt.getInstance().previousDevices,r=yield jt.getInstance().getDevices(void 0,!1),o=fn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(te.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=sT(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Yr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Yr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Fp())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Yt(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(te.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=To.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new To(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(te.ParticipantConnected,n),n.on(ce.TrackPublished,s=>{this.emitWhenConnected(te.TrackPublished,s,n)}).on(ce.TrackSubscribed,(s,r)=>{s.kind===J.Kind.Audio?(s.on(re.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(re.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===J.Kind.Video&&(s.on(re.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(re.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(te.TrackSubscribed,s,r,n)}).on(ce.TrackUnpublished,s=>{this.emit(te.TrackUnpublished,s,n)}).on(ce.TrackUnsubscribed,(s,r)=>{this.emit(te.TrackUnsubscribed,s,r,n)}).on(ce.TrackMuted,s=>{this.emitWhenConnected(te.TrackMuted,s,n)}).on(ce.TrackUnmuted,s=>{this.emitWhenConnected(te.TrackUnmuted,s,n)}).on(ce.ParticipantMetadataChanged,s=>{this.emitWhenConnected(te.ParticipantMetadataChanged,s,n)}).on(ce.ParticipantNameChanged,s=>{this.emitWhenConnected(te.ParticipantNameChanged,s,n)}).on(ce.AttributesChanged,s=>{this.emitWhenConnected(te.ParticipantAttributesChanged,s,n)}).on(ce.ConnectionQualityChanged,s=>{this.emitWhenConnected(te.ConnectionQualityChanged,s,n)}).on(ce.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(te.ParticipantPermissionsChanged,s,n)}).on(ce.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(te.TrackSubscriptionStatusChanged,s,r,n)}).on(ce.TrackSubscriptionFailed,(s,r)=>{this.emit(te.TrackSubscriptionFailed,s,n,r)}).on(ce.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(te.TrackSubscriptionPermissionChanged,s,r,n)}).on(ce.Active,()=>{this.emitWhenConnected(te.ParticipantActive,n),n.kind===Hr.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&wT(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=Kt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vn.STATE_MISMATCH))):e=0},XE)}clearConnectionReconcile(){this.connectionReconcileInterval&&Kt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(te.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===rt.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===rt.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ja({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Et.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new gs({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(te.SignalConnected),this.emit(te.Connected),this.setAndEmitConnectionState(rt.Connected),o.video){const c=new Nd(J.Kind.Video,new Qs({source:Nt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO,name:"video-dummy"}),new So(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kp(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(ce.LocalTrackPublished,c)}if(o.audio){const c=new Nd(J.Kind.Audio,new Qs({source:Nt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO}),new yo(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ud(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(ce.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let l=new gs({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Zs.ACTIVE,tracks:[],joinedAt:Et.parse(Date.now())});const d=this.getOrCreateParticipant(l.identity,l);if(a.video){const u=Kp(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Qs({source:Nt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}if(a.audio){const u=ud(),h=new Qs({source:Nt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}d.updateInfo(l)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==te.ActiveSpeakersChanged&&e!==te.TranscriptionReceived){const r=km(n).filter(o=>o!==void 0);(e===te.TrackSubscribed||e===te.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}ur.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function km(i){return i.map(e=>{if(e)return Array.isArray(e)?km(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var qn;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(qn||(qn={}));class Ji extends ni.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ur(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==qn.IDLE)throw Error("check is running already");this.setStatus(qn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==qn.SKIPPED&&this.setStatus(this.isSuccess()?qn.SUCCESS:qn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===rt.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==rt.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(te.Reconnecting,()=>{t=!0}),this.room.once(te.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Yt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class $E extends Ji{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new Qe(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return P(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Od=1e4;class KE extends Ji{get description(){return"Connection via UDP vs TCP"}perform(){return P(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Od/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Od/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Od)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),d})}}class YE extends Ji{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield GE();if(yield Up(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class JE extends Ji{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield zE();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return P(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),t.getTracks().forEach(s=>s.stop()),n.remove()})}}class ZE extends Ji{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(l=>{setTimeout(l,5e3),r=l}),a=()=>{n=!0};t.on(te.SignalReconnecting,a).on(te.Reconnecting,a).on(te.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,n){if(!s||t.state!==rt.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class QE extends Ji{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;ar(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Qe(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new vd,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let l of r.iceServers)for(let d of l.urls)d.startsWith("turn:")?(a=!0,c=!0):d.startsWith("turns:")&&(a=!0,c=!0,o=!0),d.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class eC extends Ji{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(te.SignalConnected,()=>{var n;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(tC(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),ze.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function tC(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class nC extends Ji{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new vd,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(ar(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new Qe(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Mf.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class yM extends ni.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:qn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==qn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(nC)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(eC)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(QE)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ZE)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(YE)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(JE)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(KE);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck($E)})}}function Ke(i,e,t){return(e=sC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function iC(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function sC(i){var e=iC(i,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class cn extends Error{constructor(e,t){var n;super(e,t),Ke(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}Ke(cn,"code","ERR_JOSE_GENERIC");class rC extends cn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ke(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ke(this,"claim",void 0),Ke(this,"reason",void 0),Ke(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ke(rC,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class aC extends cn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ke(this,"code","ERR_JWT_EXPIRED"),Ke(this,"claim",void 0),Ke(this,"reason",void 0),Ke(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ke(aC,"code","ERR_JWT_EXPIRED");class oC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Ke(oC,"code","ERR_JOSE_ALG_NOT_ALLOWED");class cC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Ke(cC,"code","ERR_JOSE_NOT_SUPPORTED");class lC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Ke(lC,"code","ERR_JWE_DECRYPTION_FAILED");class dC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWE_INVALID")}}Ke(dC,"code","ERR_JWE_INVALID");class uC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWS_INVALID")}}Ke(uC,"code","ERR_JWS_INVALID");class hC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWT_INVALID")}}Ke(hC,"code","ERR_JWT_INVALID");class fC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWK_INVALID")}}Ke(fC,"code","ERR_JWK_INVALID");class pC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWKS_INVALID")}}Ke(pC,"code","ERR_JWKS_INVALID");class mC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Ke(mC,"code","ERR_JWKS_NO_MATCHING_KEY");class gC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,Symbol.asyncIterator,void 0),Ke(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Ke(gC,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class vC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWKS_TIMEOUT")}}Ke(vC,"code","ERR_JWKS_TIMEOUT");class _C extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Ke(_C,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class bC extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const t=new ur;this.room=t,this.setupRoomEventListeners(t);const n=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!n.ok){const c=await n.text();throw new Error(`Failed to get room token: ${n.status} ${c}`)}const{token:s,url:r,room_name:o,user_identity:a}=await n.json();this.roomName=o,this.userIdentity=a,await t.connect(r,s),this.updateStatus("connected"),this.isReady=!0,await this.enableMicrophone(t),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:a}}))}catch(t){this.error=`Connection failed: ${t instanceof Error?t.message:String(t)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(te.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(te.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(te.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(te.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(te.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}))}}),e.on(te.TrackUnsubscribed,(t,n,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(te.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(te.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async enableMicrophone(e){try{await e.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}catch(t){this.error=`Failed to enable microphone: ${t instanceof Error?t.message:String(t)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");try{await this.room.disconnect(),this.room=null,this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.dispatchEvent(new CustomEvent("call-ended"))}catch(e){this.error=`Error ending call: ${e instanceof Error?e.message:String(e)}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}class yC{constructor(e={}){this.callManager=null,this.config=null,this.callbacks={},this.state="idle",this.callStartTime=null,this.callEndReason="user",this.hasStarted=!1,this.hasFinished=!1,this.eventHandlers=[],this.callbacks=e}configure(e){this.config=e}getState(){return this.state}isConnected(){return this.state==="active"}async connect(){var e,t;if(!this.config)throw new Error("LiveKitManager not configured. Call configure() first.");if(this.state!=="idle"){console.warn("Call already in progress");return}this.setState("connecting"),this.callEndReason="user",this.hasStarted=!1,this.hasFinished=!1,this.callManager=new bC,this.callManager.serviceUrl=this.config.voiceServiceUrl,this.attachEventHandlers(this.callManager);try{await this.callManager.makeCall({agentId:this.config.agentId})}catch(n){throw this.setState("error"),(t=(e=this.callbacks).onError)==null||t.call(e,n instanceof Error?n:new Error(String(n))),n}}async disconnect(e="user"){var t;if(this.state!=="idle"){this.callEndReason=e,this.setState("ending");try{await((t=this.callManager)==null?void 0:t.hangUp())}finally{this.finishCall()}}}destroy(){this.disconnect("user")}attachEventHandlers(e){const r=[["status-changed",o=>{const a=o.detail;this.handleStatus(a)}],["audio-track-added",o=>{var d,u;const a=o.detail,c=a==null?void 0:a.element,l=(c==null?void 0:c.srcObject)||null;l&&((u=(d=this.callbacks).onAudioTrack)==null||u.call(d,l))}],["error",o=>{const a=o.detail;this.handleError(a==null?void 0:a.error)}]];this.eventHandlers.push(...r),r.forEach(([o,a])=>e.addEventListener(o,a))}detachEventHandlers(){this.callManager&&(this.eventHandlers.forEach(([e,t])=>{var n;return(n=this.callManager)==null?void 0:n.removeEventListener(e,t)}),this.eventHandlers.length=0)}handleStatus(e){var t,n,s;switch(e){case"connecting":case"ringing":this.setState("connecting");break;case"connected":case"agent-connected":this.setState("active"),this.hasStarted||(this.callStartTime=Date.now(),this.hasStarted=!0,(s=(n=this.callbacks).onCallStart)==null||s.call(n,{agentId:((t=this.config)==null?void 0:t.agentId)??"",timestamp:this.callStartTime}));break;case"disconnecting":this.setState("ending");break;case"disconnected":this.finishCall();break;case"error":this.handleError("Unknown LiveKit error");break}}handleError(e){var t,n;this.callEndReason="error",this.setState("error"),(n=(t=this.callbacks).onError)==null||n.call(t,new Error(e||"LiveKit error")),this.detachEventHandlers(),this.callManager=null,setTimeout(()=>{this.state==="error"&&this.finishCall()},500)}finishCall(){var t,n,s;if(this.hasFinished)return;this.hasFinished=!0;const e=this.callStartTime?Date.now()-this.callStartTime:0;this.state!=="idle"&&((s=(n=this.callbacks).onCallEnd)==null||s.call(n,{agentId:((t=this.config)==null?void 0:t.agentId)??"",duration:e,reason:this.callEndReason,timestamp:Date.now()})),this.callStartTime=null,this.hasStarted=!1,this.setState("idle"),this.detachEventHandlers(),this.callManager=null}setState(e){var n,s;const t=this.state;this.state=e,(s=(n=this.callbacks).onStateChange)==null||s.call(n,e,t)}}class Im{constructor(e={}){this.audioContext=null,this.config={enabled:!0,volume:.3,...e}}async ensureContext(){if(!this.config.enabled)return null;if(!this.audioContext)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)}catch{return console.warn("Web Audio API not supported"),null}return this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.audioContext}createTone(e,t,n,s,r="sine"){const o=e.createOscillator(),a=e.createGain();o.type=r,o.frequency.setValueAtTime(t,n);const c=.05,l=.1,d=.7,u=.3;return a.gain.setValueAtTime(0,n),a.gain.linearRampToValueAtTime(this.config.volume,n+c),a.gain.linearRampToValueAtTime(this.config.volume*d,n+c+l),a.gain.setValueAtTime(this.config.volume*d,n+s-u),a.gain.linearRampToValueAtTime(0,n+s),o.connect(a),{oscillator:o,gain:a}}async playCallStartSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const s=[{freq:261.63,start:0,duration:.5},{freq:329.63,start:.15,duration:.5},{freq:392,start:.3,duration:.6},{freq:523.25,start:.5,duration:.8}],r=[];s.forEach(o=>{const{oscillator:a,gain:c}=this.createTone(e,o.freq,t+o.start,o.duration,"sine");c.connect(n),a.start(t+o.start),a.stop(t+o.start+o.duration),r.push(a);const{oscillator:l,gain:d}=this.createTone(e,o.freq*2,t+o.start,o.duration,"triangle");d.gain.setValueAtTime(d.gain.value*.3,t),d.connect(n),l.start(t+o.start),l.stop(t+o.start+o.duration),r.push(l)}),setTimeout(()=>{r.forEach(o=>{try{o.disconnect()}catch{}})},2e3)}async playCallEndSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const s=[{freq:523.25,start:0,duration:.4},{freq:392,start:.12,duration:.4},{freq:329.63,start:.24,duration:.5},{freq:261.63,start:.4,duration:.7}],r=[];s.forEach(o=>{const{oscillator:a,gain:c}=this.createTone(e,o.freq,t+o.start,o.duration,"sine");c.connect(n),a.start(t+o.start),a.stop(t+o.start+o.duration),r.push(a);const{oscillator:l,gain:d}=this.createTone(e,o.freq*2,t+o.start,o.duration,"triangle");d.gain.setValueAtTime(d.gain.value*.25,t),d.connect(n),l.start(t+o.start),l.stop(t+o.start+o.duration),r.push(l)}),setTimeout(()=>{r.forEach(o=>{try{o.disconnect()}catch{}})},1500)}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled}destroy(){this.audioContext&&(this.audioContext.close(),this.audioContext=null)}}class Dm{constructor(e,t={}){this.orbContainer=null,this.button=null,this.buttonIcon=null,this.buttonText=null,this.orbRenderer=null,this.liveKitManager=null,this.state="idle",this.animationId=null,this.audioSimPhase=0,this.isAgentMode=!1,this.defaultConfig={agentId:"",voiceServiceUrl:"",size:280,colors:{},buttonText:"Start call",activeButtonText:"End call",connectingText:"Connecting...",position:"center",mode:"inline",orbConfig:{},enableSounds:!0,soundVolume:.3,onCallStart:()=>{},onCallEnd:()=>{},onStateChange:()=>{},onError:()=>{}},this.handlePillMouseEnter=()=>{this.container.style.transform="scale(1.02)",this.container.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.05)"},this.handlePillMouseLeave=()=>{this.container.style.transform="scale(1)",this.container.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.05)"},this.handleButtonHover=()=>{!this.button||!this.buttonText||(this.button.style.transform="translate(-50%, -50%) scale(1.05)",this.button.style.boxShadow="0 6px 30px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.state!=="active"&&(this.buttonText.style.maxWidth="120px",this.buttonText.style.opacity="1",this.buttonText.style.paddingLeft="8px",this.buttonText.style.paddingRight="12px"))},this.handleButtonLeave=()=>{!this.button||!this.buttonText||(this.button.style.transform="translate(-50%, -50%) scale(1)",this.button.style.boxShadow="0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.state!=="connecting"&&(this.buttonText.style.maxWidth="0",this.buttonText.style.opacity="0",this.buttonText.style.paddingLeft="0",this.buttonText.style.paddingRight="0"))},this.handleMouseEnter=()=>{this.orbContainer&&(this.orbContainer.style.transform="scale(1.02)"),this.button&&this.buttonText&&this.state!=="active"&&(this.button.style.transform="translate(-50%, -50%) scale(1.05)",this.button.style.boxShadow="0 6px 30px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.buttonText.style.maxWidth="120px",this.buttonText.style.opacity="1",this.buttonText.style.paddingLeft="8px",this.buttonText.style.paddingRight="12px")},this.handleMouseLeave=()=>{this.orbContainer&&(this.orbContainer.style.transform="scale(1)"),this.button&&this.buttonText&&this.state!=="connecting"&&(this.button.style.transform="translate(-50%, -50%) scale(1)",this.button.style.boxShadow="0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.buttonText.style.maxWidth="0",this.buttonText.style.opacity="0",this.buttonText.style.paddingLeft="0",this.buttonText.style.paddingRight="0")},this.handleClick=()=>{this.state==="idle"?this.startCall():this.state==="active"&&this.endCall()};const n=typeof e=="string"?document.querySelector(e):e;if(!n)throw new Error("Container not found");this.container=n,this.config={...this.defaultConfig,...t},this.audioAnalyzer=new Uh,this.soundManager=new Im({enabled:this.config.enableSounds,volume:this.config.soundVolume}),this.isAgentMode=!!(this.config.agentId&&this.config.voiceServiceUrl),this.isAgentMode&&this.initializeLiveKit(),this.createWidget()}initializeLiveKit(){this.liveKitManager=new yC({onStateChange:(e,t)=>{this.setState(e),this.config.onStateChange(e,t)},onCallStart:e=>{this.config.onCallStart(e),this.dispatchEvent("call-start",e)},onCallEnd:e=>{this.config.onCallEnd(e),this.dispatchEvent("call-end",e),this.startIdleAnimation()},onAudioTrack:e=>{this.audioAnalyzer.connectStream(e),this.startRealAudioLoop()},onError:e=>{this.config.onError(e),this.dispatchEvent("error",{error:e})}}),this.liveKitManager.configure({agentId:this.config.agentId,voiceServiceUrl:this.config.voiceServiceUrl})}dispatchEvent(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0});this.container.dispatchEvent(n)}createWidget(){var e;this.container.innerHTML="",this.config.mode==="pill"?this.createPillWidget():this.createStandardWidget(),(e=this.orbRenderer)==null||e.start(),this.startIdleAnimation()}getFloatOffsets(){switch(this.config.position){case"top-left":return{top:"24px",left:"24px"};case"top-right":return{top:"24px",right:"24px"};case"bottom-left":return{bottom:"24px",left:"24px"};case"center":return{top:"50%",left:"50%",transform:"translate(-50%, -50%)"};case"bottom-right":default:return{bottom:"24px",right:"24px"}}}createStandardWidget(){const e=this.config.mode==="float",t=e?this.getFloatOffsets():{};this.container.style.cssText=`
4506
+ `},Sd}var om;function QT(){if(om)return Wn;om=1;var i=JT(),e=ZT(),t=yd();return Wn.grammar=t,Wn.write=e,Wn.parse=i.parse,Wn.parseParams=i.parseParams,Wn.parseFmtpConfig=i.parseFmtpConfig,Wn.parsePayloads=i.parsePayloads,Wn.parseRemoteCandidates=i.parseRemoteCandidates,Wn.parseImageAttributes=i.parseImageAttributes,Wn.parseSimulcastStreamList=i.parseSimulcastStreamList,Wn}var Ki=QT();function xd(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!o){var C=i.apply(g,f);a&&a(C),d.forEach(function(_){return(0,_.resolve)(C)}),d=[]}},u()),p){var T=i.apply(g,f);return a&&a(T),v(T)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const eE=.7,tE=20,lr={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class cm extends ni.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=ze,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=xd(s=>P(this,void 0,void 0,function*(){this.emit(lr.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),tE),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=Ti((n=t.loggerName)!==null&&n!==void 0?n:Gn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new rn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=nE(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=Ki.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(o=>{const a=Td(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Ki.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(lr.NegotiationComplete),e.sdp&&Ki.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(lr.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=Ki.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{dm(a),a.type==="audio"?lm(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Hn(c.codec)&&!bs()&&this.ensureVideoDDExtensionForSVC(a,o),!Hn(c.codec)))return!0;const d=Math.round(c.maxbr*eE);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Ki.write(o)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Ki.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{dm(s),s.type==="audio"&&lm(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ki.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new It("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 It("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new tr(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(o=>o.uri===zp))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:zp})}}}function lm(i,e,t){const n=Td(i.mid);let s=0;i.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&i.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function nE(i){var e;const t=[],n=[],s=Ki.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=Td(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===r&&l.type==="nack")&&n.push(c),o.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:n}}function dm(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function Td(i){return typeof i=="number"?i.toFixed(0):i}const Ed="vp8",iE={audioPreset:Ql.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:td.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ed,backupCodec:!0,preConnectBuffer:!1},um={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},hm={deviceId:{ideal:"default"},resolution:Xr.h720.resolution},sE={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ox,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Cd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Mt;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(Mt||(Mt={}));class rE{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var s;this.peerConnectionTimeout=Cd.peerConnectionTimeout,this.log=ze,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=Mt.CONNECTED:c.some(l=>l==="failed")?this.state=Mt.FAILED:c.some(l=>l==="connecting")?this.state=Mt.CONNECTING:c.every(l=>l==="closed")?this.state=Mt.CLOSED:c.some(l=>l==="closed")?this.state=Mt.CLOSING:c.every(l=>l==="new")&&(this.state=Mt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Mt[a]," to ").concat(Mt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=Ti((s=n.loggerName)!==null&&s!==void 0?s:Gn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new cm(e,n),this._mode=t,t!=="publisher-only"&&(this.subscriber=new cm(e,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=Mt.NEW,this.connectionLock=new rn,this.remoteOfferLock=new rn}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){var n;t===zn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){var n,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(this,void 0,void 0,function*(){var n;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return P(this,void 0,void 0,function*(){return new hn((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n(new tr("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n(new tr("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(lr.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(lr.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?n(o):n(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return n==null?void 0:n.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===zn.PUBLISHER?this.publisher.getConnectedAddress():e===zn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Kt.clearTimeout(u),l(De.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Kt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(De.internal("could not establish pc connection"))},o);for(;this.state!==Mt.CONNECTED;)if(yield Yt(50),s!=null&&s.signal.aborted){l(De.cancelled("room connection has been cancelled"));return}Kt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))})()})}}const fm=5e3,aE=3e4;class Qe{static fetchRegionSettings(e,t,n){return P(this,void 0,void 0,function*(){const s=yield Qe.fetchLock.lock();try{const r=yield fetch("".concat(oE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(r.ok){const o=PT(r.headers),a=o?o*1e3:fm;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?De.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):De.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof De?r:n!=null&&n.aborted?De.cancelled("Region fetching was aborted"):De.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,n){return P(this,void 0,void 0,function*(){const s=Qe.settingsTimeouts.get(e.hostname);clearTimeout(s),Qe.settingsTimeouts.set(e.hostname,setTimeout(()=>P(this,void 0,void 0,function*(){try{const r=yield Qe.fetchRegionSettings(e,t);Qe.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof De&&r.reason===pt.NotAllowed){ze.debug("token is not valid, cancelling auto region refresh");return}ze.debug("auto refetching of region settings failed",{error:r}),Qe.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){Qe.cache.set(e.hostname,n),Qe.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=Qe.settingsTimeouts.get(e);t&&(clearTimeout(t),Qe.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Qe.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=Qe.connectionTrackers.get(e);n&&n.connectionCount===0&&(ze.debug("stopping region refetch after disconnect delay",{hostname:e}),Qe.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},aE))}static cancelCleanup(e){const t=Qe.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Qe.connectionTrackers.get(e);t||(t={connectionCount:0},Qe.connectionTrackers.set(e,t)),t.connectionCount++,Qe.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Qe.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&Qe.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return rr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){return Qe.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Qe.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Qe.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(n.length>0){const s=n[0];return this.attemptedRegions.push(s),ze.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Qe.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Qe.cache=new Map,Qe.settingsTimeouts=new Map,Qe.connectionTrackers=new Map,Qe.fetchLock=new rn;function oE(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class wt extends Error{constructor(e,t,n){super(t),this.code=e,this.message=mm(t,wt.MAX_MESSAGE_BYTES),this.data=n?mm(n,wt.MAX_DATA_BYTES):void 0}static fromProto(e){return new wt(e.code,e.message,e.data)}toProto(){return new Tf({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new wt(wt.ErrorCode[e],wt.ErrorMessage[e],t)}}wt.MAX_MESSAGE_BYTES=256,wt.MAX_DATA_BYTES=15360,wt.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},wt.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 pm=15360;function Md(i){return new TextEncoder().encode(i).length}function mm(i,e){if(Md(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}const wd=2e3;function _o(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const Ad=typeof MediaRecorder<"u";class cE{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const lE=Ad?MediaRecorder:cE;class dE extends lE{constructor(e,t){if(!Ad)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function uE(){return Ad}const hE=1e3,fE=1e4;class gm extends J{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.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=xd(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(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(re.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new rn,this.pauseUpstreamLock=new rn,this.trackChangeLock=new rn,this.trackChangeLock.lock().then(o=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==J.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{sr(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ir(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{ir(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:hE;return(function*(){var n;if(e.kind===J.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=fn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Yt(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Yt(50)}throw new Ci("unable to get track dimensions after timeout")})()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Wi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Wi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===J.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===J.Kind.Audio?"audioinput":"videoinput";return t?jt.getInstance().normalizeDeviceId(r,n,s):n})()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ci("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=Ux(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===J.Kind.Video?o.video=n||s?{deviceId:n,facingMode:s}:!0:o.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{sr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===J.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(re.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?re.Muted:re.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hp()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(re.UpstreamPaused,this);const n=fn();if((n==null?void 0:n.name)==="Safari"&&ri(n.version,"12.0")<0)throw new Zl("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(re.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(ir(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(sr(n._mediaStreamTrack,l),ir(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(re.TrackProcessorUpdate,n.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}})()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(re.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!uE()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new dE(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},fE)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class bo extends gm{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,J.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=_o(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===J.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 P(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 n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Wi(this._constraints.deviceId);return this.source===J.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=id({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){pn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},wd)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!si()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(re.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return P(this,void 0,void 0,function*(){const e=yield Up(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(re.AudioSilenceDetected)),e})}}function pE(i,e,t){switch(i.kind){case"audio":return new bo(i,e,!1,void 0,t);case"video":return new yo(i,e,!1,t);default:throw new Ci("unsupported track type: ".concat(i.kind))}}const mE=Object.values(Xr),gE=Object.values(ed),vE=Object.values(td),_E=[Xr.h180,Xr.h360],bE=[ed.h180,ed.h360],yE=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ut(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),Rd=["q","h","f"];function Pd(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=xE(i,e,t,l),ze.debug("using video encoding",o));const d=o.maxFramerate,u=new ut(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Hn(l)){const g=new bm(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=fn();if(Yr()||si()||(m==null?void 0:m.name)==="Chrome"&&ri(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,T=_T(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:Rd[2-C],maxBitrate:o.maxBitrate/Math.pow(p,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:T?Math.pow(2,C):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),ze.debug("using svc encoding",{encodings:v}),v}if(!a)return[o];let h=[];i?h=(s=_m(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:vm(i,u):h=(r=_m(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:vm(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return kd(e,t,[g,f,u],d);if(v>=480)return kd(e,t,[g,u],d)}return kd(e,t,[u])}function SE(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ze.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===J.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Pd(i.source===J.Source.ScreenShare,c,l,t)}function xE(i,e,t,n){const s=TE(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function TE(i,e,t){if(i)return vE;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?mE:gE}function vm(i,e){if(i)return yE(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?_E:bE}function kd(i,e,t,n){const s=[];if(t.forEach((r,o)=>{if(o>=Rd.length)return;const a=Math.min(i,e),l={rid:Rd[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=_s()||o===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),si()&&qp()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,ze.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ze.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function _m(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class bm{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function EE(i){return i.source===J.Source.ScreenShare||i.constraints.height&&Wi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const CE=5e3;class yo extends gm{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,J.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(re.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=_o(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new rn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!pn())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},wd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=Ei(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0)r=l.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=Ei(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===J.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===J.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 P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let n=yn.LOW;n<=yn.HIGH;n+=1)t.push(new Fl({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Hn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o;let a;if(e){const u=id({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=Ei(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!1;const u=r;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=Ei(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){a={error:v}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},CE))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a,c;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(Hn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=Ei(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Hn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield ym(u.sender,u.encodings,d.qualities,this.senderLock,Hn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield ym(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,s)=>{var r;return Object.assign(Object.assign({},n),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Hn(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Hp()&&this.isInBackground&&this.source===J.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ym(i,e,t,n,s,r,o){return P(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:i,qualities:t,senderEncodings:e}));try{const c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=Sm(v),p=t.find(T=>T.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),o),_s()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield i.setParameters(c))}finally{a()}})}function Sm(i){switch(i){case"f":return yn.HIGH;case"h":return yn.MEDIUM;case"q":return yn.LOW;default:return yn.HIGH}}function xm(i,e,t,n){if(!t)return[new Gi({quality:yn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new bm(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)o.push(new Gi({quality:Math.min(yn.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=Sm((o=s.rid)!==null&&o!==void 0?o:"");return new Gi({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Tm="_lossy",Em="_reliable",ME=2*1e3,Id="leave-reconnect",wE=3e4,AE=8*1024,RE=256*1024;var Pn;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Pn||(Pn={}));class PE extends ni.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Cd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Pn.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=ze,this.reliableDataSequence=1,this.reliableMessageBuffer=new im,this.reliableReceivedState=new YT(wE),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Em)r.reliableDCSub=o;else if(o.label===Tm)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r,o,a,c;const l=yield this.dataProcessLock.lock();try{let d;if(n.data instanceof ArrayBuffer)d=n.data;else if(n.data instanceof Blob)d=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const u=an.fromBinary(new Uint8Array(d));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(oe.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=yf.fromBinary(h.payload),g=new an({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&Cm(g,g.value.value),this.emit(oe.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Cm(u,u.value.value),this.emit(oe.DataPacketReceived,u,zt.NONE)}finally{l()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?je.LOSSY:je.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(oe.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===Id&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Kt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Pn.Connected&&n();const r=()=>{this.off(oe.Disconnected,o),n()},o=()=>{this.off(oe.Restarted,r),s()};this.once(oe.Restarted,r),this.once(oe.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{if(n===je.RELIABLE){const r=this.dataChannelForKind(n);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(oe.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>P(this,void 0,void 0,function*(){!this.url||!(yield fetch(Zr(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===mt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===mt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ms.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>P(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Zr(this.url),{method:"HEAD"}),Yt(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ti((t=e.loggerName)!==null&&t!==void 0?t:Gn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new vd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new rn,this.dataProcessLock=new rn,this.dcBufferStatus=new Map([[je.LOSSY,!0],[je.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(oe.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(oe.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(oe.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(oe.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(oe.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(oe.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(oe.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(oe.SignalRequestResponse,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l.url=r,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const u=yield l.client.join(r,o,a,c,d);return l._isClosed=!1,l.latestJoinResponse=u,l.subscriberPrimary=u.subscriberPrimary,l.pcManager||(yield l.configure(u,!d)),(!l.subscriberPrimary||u.fastPublish)&&l.negotiate().catch(h=>{ze.error(h,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=u.clientConfiguration,l.emit(oe.SignalConnected,u),u}catch(u){if(u instanceof De){if(u.reason===pt.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(r,o,a,c,d)}else if(u.reason===pt.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),l.join(r,o,a,c,!0)}throw u}})()})}close(){return P(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(oe.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new im,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ci("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(De.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return P(this,void 0,void 0,function*(){var n,s;if(this.pcManager&&this.pcManager.currentState!==Mt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new rE(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(oe.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===Mt.CONNECTED){const u=this.pcState===Pn.New;this.pcState=Pn.Connected,u&&this.emit(oe.Connected,e)}else o===Mt.FAILED&&(this.pcState===Pn.Connected||this.pcState===Pn.Reconnecting)&&(this.pcState=Pn.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ms.RR_SUBSCRIBER_FAILED:ms.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===mt.RECONNECTING,d=[Mt.FAILED,Mt.CLOSING,Mt.CLOSED].includes(o);l&&d&&!this._isClosed&&this.emit(oe.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(oe.MediaTrackAdded,o.track,o.streams[0],o.receiver)},kE((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),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,t,n)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(oe.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(oe.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(oe.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(oe.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(oe.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ms.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:fm,regionSettings:e.regions})),e.action){case Qs.DISCONNECT:this.emit(oe.Disconnected,e==null?void 0:e.reason),this.close();break;case Qs.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Id);break;case Qs.RESUME:this.handleDisconnect(Id)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Gr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Tm,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Em,{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,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(je.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,AE),RE)}},1e3))}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(rd())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ad())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new It("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(rd())return this.createSimulcastTransceiverSender(e,t,n,s);if(ad())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new It("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),qi(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){ze.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Gr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:Mt.NEW)===Mt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof It?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof nr||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",ms.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(oe.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 P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new It("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(oe.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new nr;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof De&&o.reason===pt.NotAllowed?new It("could not reconnect, token might be expired"):new nr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(oe.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==mt.CONNECTED)throw new nr("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(oe.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new It("could not reconnect, url or token not saved");if(!this.pcManager)throw new It("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(oe.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof De&&s.reason===pt.NotAllowed?new It("could not reconnect, token might be expired"):s instanceof De&&s.reason===pt.LeaveRequest?s:new nr(r)}if(this.emit(oe.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}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!==mt.CONNECTED)throw new nr("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(oe.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new It("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=Pn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Yt(ME),!this.pcManager)throw new It("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Pn.Connected}catch(e){throw this.pcState=Pn.Disconnected,De.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcResponse",value:new kl({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,je.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcAck",value:new Pl({requestId:t})}});yield this.sendDataPacket(n,je.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=BT(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new bf({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===je.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===je.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=n.byteLength}if(this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(je.RELIABLE);const t=this.dataChannelForKind(je.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(je.RELIABLE)})}waitForBufferStatusLow(e){return new hn((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n(new It("engine closed"));for(this.once(oe.Closing,s);!this.dcBufferStatus.get(e);)yield Yt(10);this.off(oe.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!n.pcManager)throw new It("PC manager is closed");const o=s?n.pcManager.subscriber:n.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw De.internal("".concat(a," connection not set"));let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate().catch(u=>{ze.error(u,n.logContext)});const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Yt(50)}throw De.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Mt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new hn((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new tr("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new tr("cannot negotiate on closed engine")),this.on(oe.Closing,s),this.pcManager.publisher.once(lr.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();TT(c)&&o.set(a.payload,c)}),this.emit(oe.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof tr&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ms.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(oe.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===je.LOSSY)return this.lossyDCSub;if(e===je.RELIABLE)return this.reliableDCSub}else{if(e===je.LOSSY)return this.lossyDC;if(e===je.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(n=this.pcManager.subscriber)===null||n===void 0?void 0:n.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Bl({answer:this.pcManager.mode==="publisher-only"?c?cr({sdp:c.sdp,type:c.type}):void 0:d?cr({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?cr({sdp:a.sdp,type:a.type}):void 0:l?cr({sdp:l.sdp,type:l.type}):void 0,subscription:new so({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:aT(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,v)=>new zf({publisherSid:v,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Gf({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(je.LOSSY),zn.PUBLISHER),t(this.dataChannelForKind(je.RELIABLE),zn.PUBLISHER),t(this.dataChannelForKind(je.LOSSY,!0),zn.SUBSCRIBER),t(this.dataChannelForKind(je.RELIABLE,!0),zn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Kt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){pn()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){pn()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===n});if(s)return s[1]}}}function kE(i){return i!==void 0&&i>13}function Cm(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Mm{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new An("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),on.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new An("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),on.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class IE extends Mm{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Rn,n=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),n=o}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=Ei(c),u;u=yield d.next(),n=u.done,!n;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class DE extends Mm{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=vo(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Rn,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new An("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),on.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return P(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=Ei(c),u;u=yield d.next(),n=u.done,!n;l=!0)o=u.value,l=!1,a+=o}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return a})()})}}class LE{constructor(){this.log=ze,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new An('A text stream handler for topic "'.concat(e,'" has already been set.'),on.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new An('A byte stream handler for topic "'.concat(e,'" has already been set.'),on.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new An("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),on.AbnormalEnd);for(const[l,d]of a)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e,t){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return P(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const a=new Rn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:vo(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new An("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),on.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new IE(c,l,vo(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const a=new Rn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new An("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),on.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new DE(c,l,vo(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),on.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),on.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),on.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new An("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),on.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class wm{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class NE extends wm{}class OE extends wm{}const Am=15e3;class UE{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?zt.GCM:zt.NONE},a=new Qa({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:ys(o.timestamp),totalLength:ys(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new If({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Il.UPDATE:Il.CREATE})}}),c=e==null?void 0:e.destinationIdentities,l=new an({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,je.RELIABLE);let d=0;const u=this.engine,h=new WritableStream({write(v){return P(this,void 0,void 0,function*(){for(const m of RT(v,Am)){const p=new eo({content:m,streamId:r,chunkIndex:ys(d)}),T=new an({destinationIdentities:c,value:{case:"streamChunk",value:p}});yield u.sendDataPacket(T,je.RELIABLE),d+=1}})},close(){return P(this,void 0,void 0,function*(){const v=new to({streamId:r}),m=new an({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(m,je.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>P(this,void 0,void 0,function*(){yield g.close()});u.once(oe.Closing,f);const g=new NE(h,o,()=>this.engine.off(oe.Closing,f));return g})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,d={id:c,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?zt.GCM:zt.NONE},u=new Qa({totalLength:ys((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:ys(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Df({name:d.name})}}),h=new an({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,je.RELIABLE);let f=0;const g=new rn,v=this.engine,m=this.log,p=new WritableStream({write(C){return P(this,void 0,void 0,function*(){const _=yield g.lock();let S=0;try{for(;S<C.byteLength;){const E=C.slice(S,S+Am),w=new an({destinationIdentities:l,value:{case:"streamChunk",value:new eo({content:E,streamId:c,chunkIndex:ys(f)})}});yield v.sendDataPacket(w,je.RELIABLE),f+=1,S+=E.byteLength}}finally{_()}})},close(){return P(this,void 0,void 0,function*(){const C=new to({streamId:c}),_=new an({destinationIdentities:l,value:{case:"streamTrailer",value:C}});yield v.sendDataPacket(_,je.RELIABLE)})},abort(C){m.error("Sink error:",C)}});return new OE(p,d)})}}class Rm extends J{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(re.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),wd)),oT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(re.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class FE extends Rm{constructor(e,t,n,s,r,o){super(e,t,J.Kind.Audio,n,o),this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=_o(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;si()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(si())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(od(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&od(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(re.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(re.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Dd=100;class BE extends Rm{constructor(e,t,n,s,r){super(e,t,J.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=_o(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=xd(()=>{this.updateDimensions()},Dd),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===J.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?sr(this._mediaStreamTrack,t):ir(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new VE(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const s=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<Dd){Kt.setTimeout(()=>{this.updateVisibility()},Dd);return}this.lastVisible=a,this.emit(re.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(re.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?jp():t||(jp()>2?2:1)}}class VE{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.isPiP=ta(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ta(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=ta(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Ld(e),this.isPiP=pn()&&ta(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Ld(this.element),this.isPiP=ta(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,$p().observe(this.element),Xp().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,s,r;(e=$p())===null||e===void 0||e.unobserve(this.element),(t=Xp())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ta(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ld(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ld(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,o=i.offsetHeight,{hidden:a}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class wi extends ni.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=zt.NONE,this.log=ze,this.handleMuted=()=>{this.emit(re.Muted)},this.handleUnmuted=()=>{this.emit(re.Unmuted)},this.log=Ti((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Gn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=J.Source.Unknown}setTrack(e){this.track&&(this.track.off(re.Muted,this.handleMuted),this.track.off(re.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(re.Muted,this.handleMuted),e.on(re.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),$e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==zt.NONE}get audioTrack(){if(ai(this.track))return this.track}get videoTrack(){if(qi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=J.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===J.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(wi||(wi={}));class Nd extends wi{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(re.Ended)},this.handleCpuConstrained=()=>{this.track&&qi(this.track)&&this.emit(re.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(re.Ended,this.handleTrackEnded),this.track.off(re.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(re.Ended,this.handleTrackEnded),e.on(re.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ai(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(qt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(qt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(qt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(qt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(qt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(qt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function So(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Bp(i);let o=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Op(r,um,hm),l=id(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&(jt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>jt.userMediaPromiseMap.delete("audioinput"))),r.video&&(jt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>jt.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Wi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const T=pE(h,v,e);return T.kind===J.Kind.Video?T.source=J.Source.Camera:T.kind===J.Kind.Audio&&(T.source=J.Source.Microphone),T.mediaStream=u,ai(T)&&n?yield T.setProcessor(n):qi(T)&&s&&(yield T.setProcessor(s)),T})))}catch(u){if(!t)throw u;return So(Object.assign(Object.assign({},i),{audio:o,video:a}),e)}})}function zE(i){return P(this,void 0,void 0,function*(){return(yield So({audio:!1,video:!0}))[0]})}function GE(i){return P(this,void 0,void 0,function*(){return(yield So({audio:!0,video:!1}))[0]})}var Yi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(Yi||(Yi={}));function HE(i){switch(i){case zr.EXCELLENT:return Yi.Excellent;case zr.GOOD:return Yi.Good;case zr.POOR:return Yi.Poor;case zr.LOST:return Yi.Lost;default:return Yi.Unknown}}class Pm extends ni.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Hr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Js.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Hr.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Yi.Unknown,this.log=ze,this.log=Ti((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Gn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}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}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Rn,this.once(ce.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(J.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(J.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(J.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Js.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Js.ACTIVE&&this.emit(ce.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(ce.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(ce.ParticipantNameChanged,e)}_setAttributes(e){const t=cT(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ce.AttributesChanged,t)}setPermissions(e){var t,n,s,r,o,a;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(ce.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ce.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=HE(e),t!==this._connectionQuality&&this.emit(ce.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ai(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(re.Muted,()=>{this.emit(ce.TrackMuted,e)}),e.on(re.Unmuted,()=>{this.emit(ce.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case J.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case J.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function WE(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Bf({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class qE extends Pm{constructor(e,t,n,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=zt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Rn)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Rn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==Vl.OK&&u.reject(new Lp(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=wt.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},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(a=>WE(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),$e(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),$e(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),$e(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),$e(c))),this.emit(ce.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var v=!0,m=Ei(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const T=u;iT(T)&&(this.log.debug("publish ".concat(T," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),$e(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,T,f.options))}}catch(T){l={error:T}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>P(this,void 0,void 0,function*(){if(a.source===J.Source.ScreenShare||a.source===J.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),$e(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Mi(a)||ji(a))try{if(pn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===J.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),$e(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),$e(a))),Mi(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),$e(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==zt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(oe.RemoteMute,(n,s)=>{const r=this.trackPublications.get(n);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(oe.Connected,this.handleReconnected).on(oe.SignalConnected,this.handleSignalConnected).on(oe.SignalRestarted,this.handleReconnected).on(oe.SignalResumed,this.handleReconnected).on(oe.Restarting,this.handleReconnecting).on(oe.Resuming,this.handleReconnecting).on(oe.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(oe.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(oe.Closing,this.handleClosing).on(oe.SignalRequestResponse,this.handleSignalRequestResponse).on(oe.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new hn((a,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),a();return}yield Yt(50)}c(new Lp("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(J.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(J.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(J.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?zt.GCM:zt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,o;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 c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case J.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case J.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case J.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ci(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(ce.MediaDevicesError,l,sd(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===J.Source.Microphone&&ai(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),$e(u))),l.push(this.publishTrack(u,s));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&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===J.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(J.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(J.Source.Camera)||this.pendingPublishing.has(J.Source.Microphone))){this.pendingPublishing.add(J.Source.Camera),this.pendingPublishing.add(J.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(J.Source.Camera),this.pendingPublishing.delete(J.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Op(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield So(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(ai(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=J.Source.Microphone,this.emit(ce.AudioStreamAcquired)),qi(a)&&(this.cameraError=void 0,a.source=J.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Zl("getDisplayMedia not supported");e.resolution===void 0&&!vT()&&(e.resolution=td.h1080fps30.resolution);const t=rT(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new Ci("no video track found");const r=new yo(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=J.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(ce.AudioStreamAcquired);const a=new bo(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=J.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;Mi(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),ar(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case J.Source.Microphone:p="audioinput";break;case J.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new bo(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new yo(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new Ci("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),$e(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:g;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),$e(n))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(d=f.red)!==null&&d!==void 0||(f.red=!1)),!bT()&&r.roomOptions.e2ee&&(r.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({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((p,T)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==mt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:$e(n)}));let C=!1;const _=setTimeout(()=>{C=!0,n.stop(),T(new Dp("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(_),C)return;const S=yield this.publish(n,f,v);p(S)}else try{const C=yield this.publish(n,f,v);p(C)}catch(C){T(C)}}catch(C){T(C)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Rn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),$e(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>lT(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),$e(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Dp("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>ar(e)&&y.source===e.source)&&e.source!==J.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),$e(e))),t.stopMicTrackOnMute&&ai(e)&&(e.stopOnMute=!0),e.source===J.Source.ScreenShare&&_s()&&(t.simulcast=!1),t.videoCodec==="av1"&&!pT()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!mT()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ed),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===$r(y.mime))||(t.videoCodec=$r(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(re.Muted,this.onTrackMuted),e.on(re.Unmuted,this.onTrackUnmuted),e.on(re.Ended,this.handleTrackEnded),e.on(re.UpstreamPaused,this.onTrackUpstreamPaused),e.on(re.UpstreamResumed,this.onTrackUpstreamResumed),e.on(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),T=e.getSourceTrackSettings();T.autoGainControl&&m.push(qt.TF_AUTO_GAIN_CONTROL),T.echoCancellation&&m.push(qt.TF_ECHO_CANCELLATION),T.noiseSuppression&&m.push(qt.TF_NOISE_SUPPRESSION),T.channelCount&&T.channelCount>1&&m.push(qt.TF_STEREO),p&&m.push(qt.TF_NO_DTX),Mi(e)&&e.hasPreConnectBuffer&&m.push(qt.TF_PRECONNECT_BUFFER);const C=new Wr({cid:e.mediaStreamTrack.id,name:t.name,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let _;if(e.kind===J.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Xr.h720.resolution;y={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{dims:y}))}C.width=y.width,C.height=y.height,ji(e)&&(Hn(v)&&(e.source===J.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),$e(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new Ll({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ed}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===zt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new Ll({codec:t.backupCodec.codec,cid:""})))),_=Pd(e.source===J.Source.ScreenShare,C.width,C.height,t),C.layers=xm(C.width,C.height,_,Hn(t.videoCodec))}else e.kind===J.Kind.Audio&&(_=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new It("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var y,x,R;if(!this.engine.pcManager)throw new It("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,_),this.emit(ce.LocalSenderCreated,e.sender,e),ji(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=EE(e)),e.setDegradationPreference(t.degradationPreference)),_)if(_s()&&e.kind===J.Kind.Audio){let O;for(const U of this.engine.pcManager.publisher.getTransceivers())if(U.sender===e.sender){O=U;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((x=_[0])===null||x===void 0)&&x.maxBitrate?_[0].maxBitrate/1e3:0})}else e.codec&&Hn(e.codec)&&(!((R=_[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:_[0].maxBitrate/1e3});yield this.engine.negotiate()});let E;const w=new Promise((y,x)=>P(this,void 0,void 0,function*(){var R;try{E=yield this.engine.addTrack(C),y(E)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(U=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{error:U}))})),x(O)}}));if(this.enabledPublishVideoCodecs.length>0)E=(yield Promise.all([w,S()]))[0];else{E=yield w;let y;if(E.codecs.forEach(x=>{y===void 0&&(y=x.mimeType)}),y&&e.kind===J.Kind.Video){const x=$r(y);x!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{codec:x})),t.videoCodec=x,_=Pd(e.source===J.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new Nd(e.kind,E,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(re.CpuConstrained,y=>this.onTrackCpuConstrained(y,k)),k.options=t,e.sid=E.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:_,trackInfo:E})),ji(e)?e.startMonitor(this.engine.client):Mi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(ce.LocalTrackPublished,k),Mi(e)&&E.audioFeatures.includes(qt.TF_PRECONNECT_BUFFER)){const y=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(ce.LocalTrackSubscribed,R=>{if(R.trackSid===E.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),$e(e))),e.stopPreConnectBuffer()}}),y&&new Promise((O,U)=>P(this,void 0,void 0,function*(){var q,$,G,W,ee,ge;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),$e(e)));const Fe=setTimeout(()=>{U(new Error("agent not active within 10 seconds"))},1e4),Tt=yield this.waitUntilActiveAgentPresent();clearTimeout(Fe),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),$e(e)));const ht=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Tt.identity],attributes:{trackId:k.trackSid,sampleRate:String((ee=T.sampleRate)!==null&&ee!==void 0?ee:"48000"),channels:String((ge=T.channelCount)!==null&&ge!==void 0?ge:"1")}});try{for(var le=!0,_e=Ei(y),Be;Be=yield _e.next(),q=Be.done,!q;le=!0){W=Be.value,le=!1;const K=W;yield ht.write(K)}}catch(K){$={error:K}}finally{try{!le&&!q&&(G=_e.return)&&(yield G.call(_e))}finally{if($)throw $.error}}yield ht.close(),O()}catch(Fe){U(Fe)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),$e(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==zt.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new Ci("track is not published");if(!ji(e))throw new Ci("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=SE(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),$e(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const l=new Wr({cid:c.mediaStreamTrack.id,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=xm(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new It("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(ar(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),$e(e))),yield l)}const r=this.getPublicationForTrack(e),o=r?$e(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(re.Muted,this.onTrackMuted),e.off(re.Unmuted,this.onTrackUnmuted),e.off(re.Ended,this.handleTrackEnded),e.off(re.UpstreamPaused,this.onTrackUpstreamPaused),e.off(re.UpstreamResumed,this.onTrackUpstreamResumed),e.off(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Mt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ji(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case J.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case J.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(ce.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new hn((r,o)=>P(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==J.Source.ScreenShare&&l.source!==J.Source.ScreenShareAudio&&(Mi(l)||ji(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?je.RELIABLE:je.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new Al({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:a});const l=new an({kind:r,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new an({kind:je.RELIABLE,value:{case:"sipDtmf",value:new xf({code:e,digit:t})}});yield this.engine.sendDataPacket(n,je.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new an({value:{case:"chatMessage",value:new Za(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,je.RELIABLE),this.emit(ce.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new an({value:{case:"chatMessage",value:new Za(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp),editTimestamp:Et.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,je.RELIABLE),this.emit(ce.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new hn((c,l)=>P(this,void 0,void 0,function*(){var d,u,h,f;if(Md(s)>pm){l(wt.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&ri((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(wt.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,n,s,g);const m=setTimeout(()=>{this.pendingAcks.delete(v),l(wt.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},o);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(v),l(wt.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(T,C)=>{clearTimeout(p),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),C?l(C):c(T??"")},participantIdentity:t})}))}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&&arguments[1]!==void 0?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,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const o=new an({destinationIdentities:[e],kind:je.RELIABLE,value:{case:"rpcRequest",value:new Rl({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,je.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,wt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),$e(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,n,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Rn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(Mi(s)||ji(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Yt(20)}})}}class jE extends wi{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(re.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new so({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ef({participantSid:"",trackSids:[this.trackSid]})]});this.emit(re.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?wi.SubscriptionStatus.Unsubscribed:super.isSubscribed?wi.SubscriptionStatus.Subscribed:wi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?wi.PermissionStatus.Allowed:wi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(fd(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&fd(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:yn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(re.VisibilityChanged,this.handleVisibilityChange),s.off(re.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(re.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(re.VisibilityChanged,this.handleVisibilityChange),e.on(re.Ended,this.handleEnded),this.emit(re.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(re.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?re.Muted:re.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(re.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(re.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return fd(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Nf({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===J.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Vp(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=dT(this.trackInfo,this.requestedMaxQuality);n&&Vp(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:yn.HIGH})),e.quality=yn.HIGH)}this.emit(re.UpdateSettings,e)}}class xo extends Pm{static fromParticipantInfo(e,t,n){return new xo(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Hr.STANDARD;super(t,n||"",s,r,o,a,c),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(re.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),$e(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(re.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(re.SubscriptionPermissionChanged,t=>{this.emit(ce.TrackSubscriptionPermissionChanged,e,t)}),e.on(re.SubscriptionStatusChanged,t=>{this.emit(ce.TrackSubscriptionStatusChanged,e,t)}),e.on(re.Subscribed,t=>{this.emit(ce.TrackSubscribed,t,e)}),e.on(re.Unsubscribed,t=>{this.emit(ce.TrackUnsubscribed,t,e)}),e.on(re.SubscriptionFailed,t=>{this.emit(ce.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:J.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:J.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ce.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),$e(a))),this.emit(ce.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new BE(e,t,s,r):l=new FE(e,t,s,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(n),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&hd(l)&&ai(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=J.kindFromProto(s.type);if(!c)return;a=new jE(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==J.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:$e(l),newTrack:$e(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),$e(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(ce.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case J.Kind.Audio:this.audioTrackPublications.delete(e);break;case J.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(ce.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;ai(n.track)&&hd(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var rt;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(rt||(rt={}));const XE=4*1e3;class dr extends ni.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,s,r,o;if(super(),t=this,this.state=rt.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ze,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,l)=>P(this,void 0,void 0,function*(){var d;if(!gT())throw si()?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 u=yield this.disconnectLock.lock();if(this.state===rt.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(rt.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==Jp(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),rr(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Qe(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,v,m)=>P(this,void 0,void 0,function*(){var p,T;this.abortController&&this.abortController.abort();const C=new AbortController;this.abortController=C,u==null||u();try{if(yield or.getInstance().getBackOffPromise(a),C.signal.aborted)throw De.cancelled("Connection attempt aborted");yield this.attemptConnection(m??a,c,l,C),this.abortController=void 0,g()}catch(_){if(this.regionUrlProvider&&_ instanceof De&&_.reason!==pt.Cancelled&&_.reason!==pt.NotAllowed){let S=null;try{this.log.debug("Fetching next region"),S=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(E){if(E instanceof De&&(E.status===401||E.reason===pt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(E);return}}[pt.InternalError,pt.ServerUnreachable,pt.Timeout].includes(_.reason)&&(this.log.debug("Adding failed connection attempt to back off"),or.getInstance().addFailedConnectionAttempt(a)),S&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield h(g,v,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Yp(_)),v(_))}else{let S=Vn.UNKNOWN_REASON;_ instanceof De&&(S=Yp(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),v(_)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Rn((g,v)=>{h(g,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,l,d,u,h)=>P(this,void 0,void 0,function*(){var f,g,v;const m=yield l.join(a,c,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},h.signal,!u.singlePeerConnection);let p=m.serverInfo;if(p||(p={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(T=>{let[C,_]=T;return"".concat(C,": ").concat(_)}).join(", ")),{room:(f=m.room)===null||f===void 0?void 0:f.name,roomSid:(g=m.room)===null||g===void 0?void 0:g.sid,identity:(v=m.participant)===null||v===void 0?void 0:v.identity}),!p.version)throw new Zx("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,l,d)=>P(this,void 0,void 0,function*(){var u,h;this.state===rt.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Cd),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(te.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=d.signal.aborted?De.cancelled("Signal connection aborted"):De.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof De&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),De.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}pn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),pn()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(rt.Connected),this.emit(te.Connected),or.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];return P(t,[...c],void 0,function(){var d=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const v=yield d.disconnectLock.lock();try{if(d.state===rt.Disconnected){d.log.debug("already disconnected",d.logContext);return}if(d.log.info("disconnect from room",Object.assign({},d.logContext)),d.state===rt.Connecting||d.state===rt.Reconnecting||d.isResuming){const m="Abort connection attempt due to user initiated disconnect";d.log.warn(m,d.logContext),(h=d.abortController)===null||h===void 0||h.abort(m),(g=(f=d.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,De.cancelled("Client initiated disconnect")),d.connectFuture=void 0}d.engine&&(d.engine.client.isDisconnected||(yield d.engine.client.sendLeave()),yield d.engine.close()),d.handleDisconnect(u,Vn.CLIENT_INITIATED),d.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],c=fn();if(c&&c.os==="iOS"){const l="livekit-dummy-audio-el";let d=document.getElementById(l);if(!d){d=document.createElement("audio"),d.id=l,d.autoplay=!0,d.hidden=!0;const u=ud();u.enabled=!0;const h=new MediaStream([u]);d.srcObject=h,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(te.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(l=>{var d;(d=l.track)===null||d===void 0||d.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(rt.Reconnecting)&&this.emit(te.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(rt.Connected),this.emit(te.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var l;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(l=this.sidToIdentity.get(c.sid))!==null&&l!==void 0?l:"");let d=this.remoteParticipants.get(c.identity);c.state===Js.DISCONNECTED?this.handleParticipantDisconnected(c.identity,d):d=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],l={};a.forEach(d=>{if(l[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(d.sid);u&&(u.audioLevel=d.level,u.setIsSpeaking(!0),c.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{l[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(te.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(d=>{const u=this.remoteParticipants.get(d.identity);u&&u.sid!==d.sid||c.set(d.sid,d)}),a.forEach(d=>{let u=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=d.level,u.setIsSpeaking(d.active),d.active?c.set(d.sid,u):c.delete(d.sid))});const l=Array.from(c.values());l.sort((d,u)=>u.audioLevel-d.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(te.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);if(!d||!d.track)return;const u=J.streamStateFromProto(c.state);d.track.setStreamState(u),u!==d.track.streamState&&(l.emit(ce.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(te.TrackStreamStateChanged,d,d.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const l=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(l,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(l,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(l,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(l,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,l);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const d=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,d.id,d.method,d.payload,d.responseTimeoutMs,d.version)}},this.handleUserPacket=(a,c,l,d)=>{this.emit(te.DataReceived,c.payload,a,l,c.topic,d),a==null||a.emit(ce.DataReceived,c.payload,l,d)},this.handleSipDtmf=(a,c)=>{this.emit(te.SipDTMFReceived,c,a),a==null||a.emit(ce.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const l=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),d=l==null?void 0:l.trackPublications.get(c.trackId),u=CT(c,this.transcriptionReceivedTimes);d==null||d.emit(re.TranscriptionReceived,u),l==null||l.emit(ce.TranscriptionReceived,u,d),this.emit(te.TranscriptionReceived,u,l,d)},this.handleChatMessage=(a,c)=>{const l=MT(c);this.emit(te.ChatMessage,l,a)},this.handleMetrics=(a,c)=>{this.emit(te.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(te.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(te.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(te.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(te.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=fn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(te.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(te.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(te.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const l=this.getRemoteParticipantBySid(c.participantSid);l&&l.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(te.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(te.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(te.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(te.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(te.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h,f;(c=a.track)===null||c===void 0||c.on(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(re.Restarted,this.onLocalTrackRestarted),(h=(u=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(te.LocalTrackPublished,a,this.localParticipant),Mi(a.track)&&(yield a.track.checkForSilence())&&this.emit(te.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=sd(a.source);v&&g&&g!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,g),this.emit(te.ActiveDeviceChanged,v,g))}),this.onLocalTrackUnpublished=a=>{var c,l;(c=a.track)===null||c===void 0||c.off(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(re.Restarted,this.onLocalTrackRestarted),this.emit(te.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),l=sd(a.source);l&&c&&c!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,c),this.emit(te.ActiveDeviceChanged,l,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(te.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(te.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(te.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(te.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},sE),e),this.log=Ti((n=this.options.loggerName)!==null&&n!==void 0?n:Gn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},um),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},hm),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},iE),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new LE,this.outgoingDataStreamManager=new UE(this.engine,this.log),this.disconnectLock=new rn,this.localParticipant=new qE("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Wi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Wi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Wi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),pn()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),dr.cleanupRegistry&&dr.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}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)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new VT(n,t),this.e2eeManager.on($i.ParticipantEncryptionStatusChanged,(s,r)=>{AT(r)&&(this.isE2EEEnabled=s),this.emit(te.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on($i.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(te.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===rt.Disconnected?hn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?hn.resolve(this.roomInfo.sid):new hn((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(oe.RoomUpdate,n),e(s.sid))};this.engine.on(oe.RoomUpdate,n),this.once(te.Disconnected,()=>{this.engine.off(oe.RoomUpdate,n),t(new It("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new PE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(oe.ParticipantUpdate,this.handleParticipantUpdates).on(oe.RoomUpdate,this.handleRoomUpdate).on(oe.SpeakersChanged,this.handleSpeakersChanged).on(oe.StreamStateChanged,this.handleStreamStateUpdate).on(oe.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(oe.SubscriptionError,this.handleSubscriptionError).on(oe.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(oe.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(oe.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(oe.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(oe.DataPacketReceived,this.handleDataPacket).on(oe.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(rt.SignalReconnecting)&&this.emit(te.SignalReconnecting)}).on(oe.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(rt.Connected)&&this.emit(te.Reconnected)}).on(oe.SignalResumed,()=>{this.bufferedEvents=[],(this.state===rt.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(oe.Restarting,this.handleRestarting).on(oe.SignalRestarted,this.handleSignalRestarted).on(oe.Offline,()=>{this.setAndEmitConnectionState(rt.Reconnecting)&&this.emit(te.Reconnecting)}).on(oe.DCBufferStatusChanged,(e,t)=>{this.emit(te.DCBufferStatusChanged,e,t)}).on(oe.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(ce.LocalTrackSubscribed,t),this.emitWhenConnected(te.LocalTrackSubscribed,t,this.localParticipant)}).on(oe.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(te.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return jt.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===rt.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(rr(new URL(e))&&t){this.regionUrlProvider=new Qe(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===rt.Disconnected&&(this.regionUrl=n,yield fetch(Zr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Zr(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>P(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new ti({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new ti({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new ti({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new ti({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=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ti({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ti({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new ti({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new ro({reason:Vn.CLIENT_INITIATED,action:Qs.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new ti({scenario:{case:"subscriberBandwidth",value:ys(t)}});break;case"leave-full-reconnect":s=new ti({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,v=!1;const m=o?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.audioTrackPublications.values()).filter(_=>_.source===J.Source.Microphone);try{g=(yield Promise.all(T.map(_=>{var S;return(S=_.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(_=>_===!0)}catch(_){throw r.options.audioCaptureDefaults.deviceId=p,_}const C=T.some(_=>{var S,E;return(E=(S=_.track)===null||S===void 0?void 0:S.isMuted)!==null&&E!==void 0?E:!1});g&&C&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.videoTrackPublications.values()).filter(_=>_.source===J.Source.Camera);try{g=(yield Promise.all(T.map(_=>{var S;return(S=_.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(_=>_===!0)}catch(_){throw r.options.videoCaptureDefaults.deviceId=p,_}const C=T.some(_=>{var S,E;return(E=(S=_.track)===null||S===void 0?void 0:S.isMuted)!==null&&E!==void 0?E:!1});g&&C&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!od()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield jt.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(T=>T.setAudioOutput({deviceId:s})))}catch(T){throw r.options.audioOutput.deviceId=p,T}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(te.ActiveDeviceChanged,n,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ce.AttributesChanged,this.onLocalAttributesChanged).on(ce.TrackMuted,this.onLocalTrackMuted).on(ce.TrackUnmuted,this.onLocalTrackUnmuted).on(ce.LocalTrackPublished,this.onLocalTrackPublished).on(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ce.MediaDevicesError,this.onMediaDevicesError).on(ce.AudioStreamAcquired,this.startAudio).on(ce.ChatMessage,this.onLocalChatMessageSent).on(ce.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===rt.Connecting||this.state===rt.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(te.Reconnected,u),this.off(te.Connected,u),this.off(te.Disconnected,h)};this.once(te.Reconnected,u),this.once(te.Connected,u),this.once(te.Disconnected,h);return}if(this.state===rt.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=fT(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,a,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(te.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==rt.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ce.AttributesChanged,this.onLocalAttributesChanged).off(ce.TrackMuted,this.onLocalTrackMuted).off(ce.TrackUnmuted,this.onLocalTrackUnmuted).off(ce.LocalTrackPublished,this.onLocalTrackPublished).off(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ce.MediaDevicesError,this.onMediaDevicesError).off(ce.AudioStreamAcquired,this.startAudio).off(ce.ChatMessage,this.onLocalChatMessageSent).off(ce.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),pn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||s===void 0||s.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(rt.Disconnected),this.emit(te.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(te.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,o){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,wt.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,t,null,wt.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Md(d)>pm?(c=wt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof wt?c=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=wt.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=jt.getInstance().previousDevices,r=yield jt.getInstance().getDevices(void 0,!1),o=fn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(te.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=sT(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Yr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Yr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Fp())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Yt(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(te.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=xo.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new xo(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(te.ParticipantConnected,n),n.on(ce.TrackPublished,s=>{this.emitWhenConnected(te.TrackPublished,s,n)}).on(ce.TrackSubscribed,(s,r)=>{s.kind===J.Kind.Audio?(s.on(re.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(re.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===J.Kind.Video&&(s.on(re.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(re.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(te.TrackSubscribed,s,r,n)}).on(ce.TrackUnpublished,s=>{this.emit(te.TrackUnpublished,s,n)}).on(ce.TrackUnsubscribed,(s,r)=>{this.emit(te.TrackUnsubscribed,s,r,n)}).on(ce.TrackMuted,s=>{this.emitWhenConnected(te.TrackMuted,s,n)}).on(ce.TrackUnmuted,s=>{this.emitWhenConnected(te.TrackUnmuted,s,n)}).on(ce.ParticipantMetadataChanged,s=>{this.emitWhenConnected(te.ParticipantMetadataChanged,s,n)}).on(ce.ParticipantNameChanged,s=>{this.emitWhenConnected(te.ParticipantNameChanged,s,n)}).on(ce.AttributesChanged,s=>{this.emitWhenConnected(te.ParticipantAttributesChanged,s,n)}).on(ce.ConnectionQualityChanged,s=>{this.emitWhenConnected(te.ConnectionQualityChanged,s,n)}).on(ce.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(te.ParticipantPermissionsChanged,s,n)}).on(ce.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(te.TrackSubscriptionStatusChanged,s,r,n)}).on(ce.TrackSubscriptionFailed,(s,r)=>{this.emit(te.TrackSubscriptionFailed,s,n,r)}).on(ce.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(te.TrackSubscriptionPermissionChanged,s,r,n)}).on(ce.Active,()=>{this.emitWhenConnected(te.ParticipantActive,n),n.kind===Hr.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&wT(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=Kt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vn.STATE_MISMATCH))):e=0},XE)}clearConnectionReconcile(){this.connectionReconcileInterval&&Kt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(te.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===rt.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===rt.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ya({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Et.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new gs({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(te.SignalConnected),this.emit(te.Connected),this.setAndEmitConnectionState(rt.Connected),o.video){const c=new Nd(J.Kind.Video,new Zs({source:Nt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO,name:"video-dummy"}),new yo(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kp(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(ce.LocalTrackPublished,c)}if(o.audio){const c=new Nd(J.Kind.Audio,new Zs({source:Nt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO}),new bo(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ud(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(ce.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let l=new gs({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Js.ACTIVE,tracks:[],joinedAt:Et.parse(Date.now())});const d=this.getOrCreateParticipant(l.identity,l);if(a.video){const u=Kp(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Zs({source:Nt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}if(a.audio){const u=ud(),h=new Zs({source:Nt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Bn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}d.updateInfo(l)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==te.ActiveSpeakersChanged&&e!==te.TranscriptionReceived){const r=km(n).filter(o=>o!==void 0);(e===te.TrackSubscribed||e===te.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}dr.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function km(i){return i.map(e=>{if(e)return Array.isArray(e)?km(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var qn;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(qn||(qn={}));class Ji extends ni.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new dr(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==qn.IDLE)throw Error("check is running already");this.setStatus(qn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==qn.SKIPPED&&this.setStatus(this.isSuccess()?qn.SUCCESS:qn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===rt.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==rt.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(te.Reconnecting,()=>{t=!0}),this.room.once(te.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Yt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class $E extends Ji{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new Qe(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return P(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Od=1e4;class KE extends Ji{get description(){return"Connection via UDP vs TCP"}perform(){return P(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Od/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Od/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Od)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),d})}}class YE extends Ji{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield GE();if(yield Up(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class JE extends Ji{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield zE();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return P(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),t.getTracks().forEach(s=>s.stop()),n.remove()})}}class ZE extends Ji{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(l=>{setTimeout(l,5e3),r=l}),a=()=>{n=!0};t.on(te.SignalReconnecting,a).on(te.Reconnecting,a).on(te.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,n){if(!s||t.state!==rt.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class QE extends Ji{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;rr(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Qe(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new vd,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let l of r.iceServers)for(let d of l.urls)d.startsWith("turn:")?(a=!0,c=!0):d.startsWith("turns:")&&(a=!0,c=!0,o=!0),d.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class eC extends Ji{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(te.SignalConnected,()=>{var n;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(tC(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),ze.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function tC(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class nC extends Ji{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new vd,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(rr(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new Qe(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Mf.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class bM extends ni.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:qn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==qn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(nC)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(eC)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(QE)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ZE)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(YE)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(JE)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(KE);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck($E)})}}function Ke(i,e,t){return(e=sC(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function iC(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function sC(i){var e=iC(i,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class cn extends Error{constructor(e,t){var n;super(e,t),Ke(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}Ke(cn,"code","ERR_JOSE_GENERIC");class rC extends cn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ke(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ke(this,"claim",void 0),Ke(this,"reason",void 0),Ke(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ke(rC,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class aC extends cn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ke(this,"code","ERR_JWT_EXPIRED"),Ke(this,"claim",void 0),Ke(this,"reason",void 0),Ke(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ke(aC,"code","ERR_JWT_EXPIRED");class oC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Ke(oC,"code","ERR_JOSE_ALG_NOT_ALLOWED");class cC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Ke(cC,"code","ERR_JOSE_NOT_SUPPORTED");class lC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Ke(lC,"code","ERR_JWE_DECRYPTION_FAILED");class dC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWE_INVALID")}}Ke(dC,"code","ERR_JWE_INVALID");class uC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWS_INVALID")}}Ke(uC,"code","ERR_JWS_INVALID");class hC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWT_INVALID")}}Ke(hC,"code","ERR_JWT_INVALID");class fC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWK_INVALID")}}Ke(fC,"code","ERR_JWK_INVALID");class pC extends cn{constructor(){super(...arguments),Ke(this,"code","ERR_JWKS_INVALID")}}Ke(pC,"code","ERR_JWKS_INVALID");class mC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Ke(mC,"code","ERR_JWKS_NO_MATCHING_KEY");class gC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,Symbol.asyncIterator,void 0),Ke(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Ke(gC,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class vC extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWKS_TIMEOUT")}}Ke(vC,"code","ERR_JWKS_TIMEOUT");class _C extends cn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ke(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Ke(_C,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class bC extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const t=new dr;this.room=t,this.setupRoomEventListeners(t);const n=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!n.ok){const c=await n.text();throw new Error(`Failed to get room token: ${n.status} ${c}`)}const{token:s,url:r,room_name:o,user_identity:a}=await n.json();this.roomName=o,this.userIdentity=a,await t.connect(r,s),this.updateStatus("connected"),this.isReady=!0,await this.enableMicrophone(t),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:a}}))}catch(t){this.error=`Connection failed: ${t instanceof Error?t.message:String(t)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(te.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(te.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(te.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(te.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(te.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}))}}),e.on(te.TrackUnsubscribed,(t,n,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(te.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(te.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async enableMicrophone(e){try{await e.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}catch(t){this.error=`Failed to enable microphone: ${t instanceof Error?t.message:String(t)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");try{await this.room.disconnect(),this.room=null,this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.dispatchEvent(new CustomEvent("call-ended"))}catch(e){this.error=`Error ending call: ${e instanceof Error?e.message:String(e)}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}class yC{constructor(e={}){this.callManager=null,this.config=null,this.callbacks={},this.state="idle",this.callStartTime=null,this.callEndReason="user",this.hasStarted=!1,this.hasFinished=!1,this.eventHandlers=[],this.callbacks=e}configure(e){this.config=e}getState(){return this.state}isConnected(){return this.state==="active"}async connect(){var e,t;if(!this.config)throw new Error("LiveKitManager not configured. Call configure() first.");if(this.state!=="idle"){console.warn("Call already in progress");return}this.setState("connecting"),this.callEndReason="user",this.hasStarted=!1,this.hasFinished=!1,this.callManager=new bC,this.callManager.serviceUrl=this.config.voiceServiceUrl,this.attachEventHandlers(this.callManager);try{await this.callManager.makeCall({agentId:this.config.agentId})}catch(n){throw this.setState("error"),(t=(e=this.callbacks).onError)==null||t.call(e,n instanceof Error?n:new Error(String(n))),n}}async disconnect(e="user"){var t;if(this.state!=="idle"){this.callEndReason=e,this.setState("ending");try{await((t=this.callManager)==null?void 0:t.hangUp())}finally{this.finishCall()}}}destroy(){this.disconnect("user")}attachEventHandlers(e){const r=[["status-changed",o=>{const a=o.detail;this.handleStatus(a)}],["audio-track-added",o=>{var d,u;const a=o.detail,c=a==null?void 0:a.element,l=(c==null?void 0:c.srcObject)||null;l&&((u=(d=this.callbacks).onAudioTrack)==null||u.call(d,l))}],["error",o=>{const a=o.detail;this.handleError(a==null?void 0:a.error)}]];this.eventHandlers.push(...r),r.forEach(([o,a])=>e.addEventListener(o,a))}detachEventHandlers(){this.callManager&&(this.eventHandlers.forEach(([e,t])=>{var n;return(n=this.callManager)==null?void 0:n.removeEventListener(e,t)}),this.eventHandlers.length=0)}handleStatus(e){var t,n,s;switch(e){case"connecting":case"ringing":this.setState("connecting");break;case"connected":case"agent-connected":this.setState("active"),this.hasStarted||(this.callStartTime=Date.now(),this.hasStarted=!0,(s=(n=this.callbacks).onCallStart)==null||s.call(n,{agentId:((t=this.config)==null?void 0:t.agentId)??"",timestamp:this.callStartTime}));break;case"disconnecting":this.setState("ending");break;case"disconnected":this.finishCall();break;case"error":this.handleError("Unknown LiveKit error");break}}handleError(e){var t,n;this.callEndReason="error",this.setState("error"),(n=(t=this.callbacks).onError)==null||n.call(t,new Error(e||"LiveKit error")),this.detachEventHandlers(),this.callManager=null,setTimeout(()=>{this.state==="error"&&this.finishCall()},500)}finishCall(){var t,n,s;if(this.hasFinished)return;this.hasFinished=!0;const e=this.callStartTime?Date.now()-this.callStartTime:0;this.state!=="idle"&&((s=(n=this.callbacks).onCallEnd)==null||s.call(n,{agentId:((t=this.config)==null?void 0:t.agentId)??"",duration:e,reason:this.callEndReason,timestamp:Date.now()})),this.callStartTime=null,this.hasStarted=!1,this.setState("idle"),this.detachEventHandlers(),this.callManager=null}setState(e){var n,s;const t=this.state;this.state=e,(s=(n=this.callbacks).onStateChange)==null||s.call(n,e,t)}}class Im{constructor(e={}){this.audioContext=null,this.config={enabled:!0,volume:.3,...e}}async ensureContext(){if(!this.config.enabled)return null;if(!this.audioContext)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)}catch{return console.warn("Web Audio API not supported"),null}return this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.audioContext}createTone(e,t,n,s,r="sine"){const o=e.createOscillator(),a=e.createGain();o.type=r,o.frequency.setValueAtTime(t,n);const c=.05,l=.1,d=.7,u=.3;return a.gain.setValueAtTime(0,n),a.gain.linearRampToValueAtTime(this.config.volume,n+c),a.gain.linearRampToValueAtTime(this.config.volume*d,n+c+l),a.gain.setValueAtTime(this.config.volume*d,n+s-u),a.gain.linearRampToValueAtTime(0,n+s),o.connect(a),{oscillator:o,gain:a}}async playCallStartSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const s=[{freq:261.63,start:0,duration:.5},{freq:329.63,start:.15,duration:.5},{freq:392,start:.3,duration:.6},{freq:523.25,start:.5,duration:.8}],r=[];s.forEach(o=>{const{oscillator:a,gain:c}=this.createTone(e,o.freq,t+o.start,o.duration,"sine");c.connect(n),a.start(t+o.start),a.stop(t+o.start+o.duration),r.push(a);const{oscillator:l,gain:d}=this.createTone(e,o.freq*2,t+o.start,o.duration,"triangle");d.gain.setValueAtTime(d.gain.value*.3,t),d.connect(n),l.start(t+o.start),l.stop(t+o.start+o.duration),r.push(l)}),setTimeout(()=>{r.forEach(o=>{try{o.disconnect()}catch{}})},2e3)}async playCallEndSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const s=[{freq:523.25,start:0,duration:.4},{freq:392,start:.12,duration:.4},{freq:329.63,start:.24,duration:.5},{freq:261.63,start:.4,duration:.7}],r=[];s.forEach(o=>{const{oscillator:a,gain:c}=this.createTone(e,o.freq,t+o.start,o.duration,"sine");c.connect(n),a.start(t+o.start),a.stop(t+o.start+o.duration),r.push(a);const{oscillator:l,gain:d}=this.createTone(e,o.freq*2,t+o.start,o.duration,"triangle");d.gain.setValueAtTime(d.gain.value*.25,t),d.connect(n),l.start(t+o.start),l.stop(t+o.start+o.duration),r.push(l)}),setTimeout(()=>{r.forEach(o=>{try{o.disconnect()}catch{}})},1500)}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled}destroy(){this.audioContext&&(this.audioContext.close(),this.audioContext=null)}}class Dm{constructor(e,t={}){this.orbContainer=null,this.button=null,this.buttonIcon=null,this.buttonText=null,this.orbRenderer=null,this.liveKitManager=null,this.state="idle",this.animationId=null,this.audioSimPhase=0,this.isAgentMode=!1,this.defaultConfig={agentId:"",voiceServiceUrl:"",size:280,colors:{},buttonText:"Start call",activeButtonText:"End call",connectingText:"Connecting...",position:"center",mode:"inline",orbConfig:{},enableSounds:!0,soundVolume:.3,onCallStart:()=>{},onCallEnd:()=>{},onStateChange:()=>{},onError:()=>{}},this.handlePillMouseEnter=()=>{this.container.style.transform="scale(1.02)",this.container.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.05)"},this.handlePillMouseLeave=()=>{this.container.style.transform="scale(1)",this.container.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.05)"},this.handleButtonHover=()=>{!this.button||!this.buttonText||(this.button.style.transform="translate(-50%, -50%) scale(1.05)",this.button.style.boxShadow="0 6px 30px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.state!=="active"&&(this.buttonText.style.maxWidth="120px",this.buttonText.style.opacity="1",this.buttonText.style.paddingLeft="8px",this.buttonText.style.paddingRight="12px"))},this.handleButtonLeave=()=>{!this.button||!this.buttonText||(this.button.style.transform="translate(-50%, -50%) scale(1)",this.button.style.boxShadow="0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.state!=="connecting"&&(this.buttonText.style.maxWidth="0",this.buttonText.style.opacity="0",this.buttonText.style.paddingLeft="0",this.buttonText.style.paddingRight="0"))},this.handleMouseEnter=()=>{this.orbContainer&&(this.orbContainer.style.transform="scale(1.02)"),this.button&&this.buttonText&&this.state!=="active"&&(this.button.style.transform="translate(-50%, -50%) scale(1.05)",this.button.style.boxShadow="0 6px 30px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.buttonText.style.maxWidth="120px",this.buttonText.style.opacity="1",this.buttonText.style.paddingLeft="8px",this.buttonText.style.paddingRight="12px")},this.handleMouseLeave=()=>{this.orbContainer&&(this.orbContainer.style.transform="scale(1)"),this.button&&this.buttonText&&this.state!=="connecting"&&(this.button.style.transform="translate(-50%, -50%) scale(1)",this.button.style.boxShadow="0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05)",this.buttonText.style.maxWidth="0",this.buttonText.style.opacity="0",this.buttonText.style.paddingLeft="0",this.buttonText.style.paddingRight="0")},this.handleClick=()=>{this.state==="idle"?this.startCall():this.state==="active"&&this.endCall()};const n=typeof e=="string"?document.querySelector(e):e;if(!n)throw new Error("Container not found");this.container=n,this.config={...this.defaultConfig,...t},this.audioAnalyzer=new Uh,this.soundManager=new Im({enabled:this.config.enableSounds,volume:this.config.soundVolume}),this.isAgentMode=!!(this.config.agentId&&this.config.voiceServiceUrl),this.isAgentMode&&this.initializeLiveKit(),this.createWidget()}initializeLiveKit(){this.liveKitManager=new yC({onStateChange:(e,t)=>{this.setState(e),this.config.onStateChange(e,t)},onCallStart:e=>{this.config.onCallStart(e),this.dispatchEvent("call-start",e)},onCallEnd:e=>{this.config.onCallEnd(e),this.dispatchEvent("call-end",e),this.startIdleAnimation()},onAudioTrack:e=>{this.audioAnalyzer.connectStream(e),this.startRealAudioLoop()},onError:e=>{this.config.onError(e),this.dispatchEvent("error",{error:e})}}),this.liveKitManager.configure({agentId:this.config.agentId,voiceServiceUrl:this.config.voiceServiceUrl})}dispatchEvent(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0});this.container.dispatchEvent(n)}createWidget(){var e;this.container.innerHTML="",this.config.mode==="pill"?this.createPillWidget():this.createStandardWidget(),(e=this.orbRenderer)==null||e.start(),this.startIdleAnimation()}getFloatOffsets(){switch(this.config.position){case"top-left":return{top:"24px",left:"24px"};case"top-right":return{top:"24px",right:"24px"};case"bottom-left":return{bottom:"24px",left:"24px"};case"center":return{top:"50%",left:"50%",transform:"translate(-50%, -50%)"};case"bottom-right":default:return{bottom:"24px",right:"24px"}}}createStandardWidget(){const e=this.config.mode==="float",t=e?this.getFloatOffsets():{};this.container.style.cssText=`
4507
4507
  position: ${e?"fixed":"relative"};
4508
4508
  ${t.top?`top: ${t.top};`:""}
4509
4509
  ${t.right?`right: ${t.right};`:""}
@@ -4632,16 +4632,16 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
4632
4632
  font-size: inherit;
4633
4633
  font-weight: inherit;
4634
4634
  }
4635
- `;var xC=Object.defineProperty,TC=Object.getOwnPropertyDescriptor,Ot=(i,e,t,n)=>{for(var s=n>1?void 0:n?TC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&xC(e,t,s),s};const Ss=280,Lm={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},cyan:{primary:"#0e7490",secondary:"#0891b2",accent:"#06b6d4",glow:"#0e7490",atmosphere:"#0891b2",depth:"#083344",highlight:"#67e8f9"},emerald:{primary:"#047857",secondary:"#059669",accent:"#10b981",glow:"#047857",atmosphere:"#059669",depth:"#022c22",highlight:"#6ee7b7"},rose:{primary:"#be123c",secondary:"#e11d48",accent:"#f43f5e",glow:"#be123c",atmosphere:"#e11d48",depth:"#4c0519",highlight:"#fda4af"},amber:{primary:"#b45309",secondary:"#d97706",accent:"#f59e0b",glow:"#b45309",atmosphere:"#d97706",depth:"#451a03",highlight:"#fcd34d"}},Nm={indigo:{primary:"#6366f1",secondary:"#818cf8",accent:"#a5b4fc",glow:"#c7d2fe",atmosphere:"#e0e7ff",depth:"#4338ca",highlight:"#eef2ff"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#a5f3fc",atmosphere:"#cffafe",depth:"#0891b2",highlight:"#ecfeff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#a7f3d0",atmosphere:"#d1fae5",depth:"#059669",highlight:"#ecfdf5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fecdd3",atmosphere:"#ffe4e6",depth:"#be123c",highlight:"#fff1f2"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fde68a",atmosphere:"#fef3c7",depth:"#b45309",highlight:"#fffbeb"}},Ud=class Ud extends yr{constructor(){super(),this.agentId="",this.size=Ss,this.mode="inline",this.position="center",this.enableSounds=!0,this.soundVolume=.3,this.theme="auto",this.colorPreset="indigo",this.currentState="idle",this.widget=null,this.themeQuery=null,this.handleThemeChange=()=>{this.theme==="auto"&&this.applyThemeToWidget()};const e=this.getAttribute("mode")??"inline";if(e!=="pill"&&e!=="float"){const t=this.getAttribute("size"),n=t?Number(t):NaN,s=Number.isFinite(n)&&n>0?n:Ss;this.style.setProperty("--hanc-orb-size",`${s}px`)}}connectedCallback(){super.connectedCallback(),this.setupThemeListener()}disconnectedCallback(){this.destroyWidget(),this.teardownThemeListener(),super.disconnectedCallback()}firstUpdated(){this.applyHostStyles(),this.initializeWidget()}updated(e){super.updated(e),e.has("theme")&&(this.teardownThemeListener(),this.setupThemeListener());const t=["agentId","voiceServiceUrl","mode","size","position","buttonText","activeButtonText","connectingText","buttonStartText","buttonEndText","buttonConnectingText","orbConfig"],n=["colors","theme","colorPreset"],s=["enableSounds","soundVolume"],r=[...e.keys()].some(o=>t.includes(o));if((e.has("mode")||e.has("size"))&&this.applyHostStyles(),!this.widget||r){this.initializeWidget();return}[...e.keys()].some(o=>n.includes(o))&&this.applyThemeToWidget(),[...e.keys()].some(o=>s.includes(o))&&(this.widget.setSoundsEnabled(this.enableSounds),this.widget.setSoundVolume(this.soundVolume))}render(){return sg`<div id="orb-container" aria-live="polite"></div>`}async startCall(){var e;await((e=this.widget)==null?void 0:e.startCall())}async endCall(){var e;await((e=this.widget)==null?void 0:e.endCall())}initializeWidget(){if(this.destroyWidget(),!this.orbContainer)return;const e=this.buildConfig();this.widget=new Dm(this.orbContainer,e),this.applyThemeToWidget(),this.widget.setSoundsEnabled(this.enableSounds),this.widget.setSoundVolume(this.soundVolume),this.currentState=this.widget.getState(),this.setAttribute("data-state",this.currentState)}destroyWidget(){this.widget&&(this.widget.destroy(),this.widget=null)}buildConfig(){const e=this.resolveColors(),t=this.parseOrbConfig();return{agentId:this.agentId,voiceServiceUrl:this.voiceServiceUrl||"https://voice.hanc.ai",size:this.size,mode:this.mode,position:this.position,colors:e,buttonText:this.getButtonText(),activeButtonText:this.getActiveButtonText(),connectingText:this.getConnectingText(),orbConfig:t,enableSounds:this.enableSounds,soundVolume:this.soundVolume,onStateChange:(n,s)=>{this.currentState=n,this.setAttribute("data-state",n),this.dispatchEvent(new CustomEvent("state-change",{detail:{state:n,previousState:s},bubbles:!0,composed:!0}))},onCallStart:n=>{this.dispatchEvent(new CustomEvent("call-start",{detail:n,bubbles:!0,composed:!0}))},onCallEnd:n=>{this.dispatchEvent(new CustomEvent("call-end",{detail:n,bubbles:!0,composed:!0}))},onError:n=>{this.dispatchEvent(new CustomEvent("error",{detail:{error:n},bubbles:!0,composed:!0}))}}}resolveColors(){return{...this.getResolvedTheme()==="dark"?Lm[this.colorPreset]||Lm.indigo:Nm[this.colorPreset]||Nm.indigo,...this.parseColors()}}parseColors(){if(!this.colors)return{};try{return JSON.parse(this.colors)}catch(e){return console.warn("Failed to parse colors JSON",e),{}}}parseOrbConfig(){if(!this.orbConfig)return{};try{return JSON.parse(this.orbConfig)}catch(e){return console.warn("Failed to parse orb-config JSON",e),{}}}applyHostStyles(){if(this.mode==="pill"){this.style.removeProperty("--hanc-orb-size");return}if(this.mode==="float"){this.style.removeProperty("--hanc-orb-size");return}const e=Number.isFinite(this.size)&&this.size>0?this.size:Ss;this.style.setProperty("--hanc-orb-size",`${e}px`)}getButtonText(){return this.buttonText||this.buttonStartText||"Start call"}getActiveButtonText(){return this.activeButtonText||this.buttonEndText||"End call"}getConnectingText(){return this.connectingText||this.buttonConnectingText||"Connecting..."}applyThemeToWidget(){var n,s,r;const e=this.getResolvedTheme(),t=this.resolveColors();(n=this.widget)==null||n.setColors(t),e==="dark"?(s=this.widget)==null||s.setGlowSettings(.8,.4):(r=this.widget)==null||r.setGlowSettings(.4,.2)}setupThemeListener(){this.theme!=="auto"||typeof window>"u"||(this.themeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.themeQuery.addEventListener("change",this.handleThemeChange))}teardownThemeListener(){this.themeQuery&&(this.themeQuery.removeEventListener("change",this.handleThemeChange),this.themeQuery=null)}getResolvedTheme(){var e;return this.theme==="auto"?(e=this.themeQuery)!=null&&e.matches?"dark":"light":this.theme}};Ud.styles=[SC,Hd`
4635
+ `;var xC=Object.defineProperty,Gt=(i,e,t,n)=>{for(var s=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=o(e,t,s)||s);return s&&xC(e,t,s),s};const ur=280,Lm={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},cyan:{primary:"#0e7490",secondary:"#0891b2",accent:"#06b6d4",glow:"#0e7490",atmosphere:"#0891b2",depth:"#083344",highlight:"#67e8f9"},emerald:{primary:"#047857",secondary:"#059669",accent:"#10b981",glow:"#047857",atmosphere:"#059669",depth:"#022c22",highlight:"#6ee7b7"},rose:{primary:"#be123c",secondary:"#e11d48",accent:"#f43f5e",glow:"#be123c",atmosphere:"#e11d48",depth:"#4c0519",highlight:"#fda4af"},amber:{primary:"#b45309",secondary:"#d97706",accent:"#f59e0b",glow:"#b45309",atmosphere:"#d97706",depth:"#451a03",highlight:"#fcd34d"}},Nm={indigo:{primary:"#6366f1",secondary:"#818cf8",accent:"#a5b4fc",glow:"#c7d2fe",atmosphere:"#e0e7ff",depth:"#4338ca",highlight:"#eef2ff"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#a5f3fc",atmosphere:"#cffafe",depth:"#0891b2",highlight:"#ecfeff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#a7f3d0",atmosphere:"#d1fae5",depth:"#059669",highlight:"#ecfdf5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fecdd3",atmosphere:"#ffe4e6",depth:"#be123c",highlight:"#fff1f2"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fde68a",atmosphere:"#fef3c7",depth:"#b45309",highlight:"#fffbeb"}},Ud=class Ud extends yr{constructor(){super(...arguments),this.agentId="",this.size=ur,this.mode="inline",this.position="center",this.enableSounds=!0,this.soundVolume=.3,this.theme="auto",this.colorPreset="indigo",this.currentState="idle",this.widget=null,this.themeQuery=null,this.handleThemeChange=()=>{this.theme==="auto"&&this.applyThemeToWidget()}}connectedCallback(){super.connectedCallback(),this.syncHostSizing(),this.setupThemeListener()}disconnectedCallback(){this.destroyWidget(),this.teardownThemeListener(),super.disconnectedCallback()}firstUpdated(){this.syncHostSizing(),this.initializeWidget()}updated(e){super.updated(e),e.has("theme")&&(this.teardownThemeListener(),this.setupThemeListener()),(e.has("mode")||e.has("size"))&&this.syncHostSizing();const t=["agentId","voiceServiceUrl","mode","size","position","buttonText","activeButtonText","connectingText","buttonStartText","buttonEndText","buttonConnectingText","orbConfig"],n=["colors","theme","colorPreset"],s=["enableSounds","soundVolume"],r=[...e.keys()].some(o=>t.includes(o));if(!this.widget||r){this.initializeWidget();return}[...e.keys()].some(o=>n.includes(o))&&this.applyThemeToWidget(),[...e.keys()].some(o=>s.includes(o))&&(this.widget.setSoundsEnabled(this.enableSounds),this.widget.setSoundVolume(this.soundVolume))}render(){return sg`<div id="orb-container" aria-live="polite"></div>`}async startCall(){var e;await((e=this.widget)==null?void 0:e.startCall())}async endCall(){var e;await((e=this.widget)==null?void 0:e.endCall())}initializeWidget(){if(this.destroyWidget(),!this.orbContainer)return;const e=this.buildConfig();this.widget=new Dm(this.orbContainer,e),this.applyThemeToWidget(),this.widget.setSoundsEnabled(this.enableSounds),this.widget.setSoundVolume(this.soundVolume),this.currentState=this.widget.getState(),this.setAttribute("data-state",this.currentState)}destroyWidget(){this.widget&&(this.widget.destroy(),this.widget=null)}buildConfig(){const e=this.resolveColors(),t=this.parseOrbConfig();return{agentId:this.agentId,voiceServiceUrl:this.voiceServiceUrl||"https://voice.hanc.ai",size:this.size,mode:this.mode,position:this.position,colors:e,buttonText:this.getButtonText(),activeButtonText:this.getActiveButtonText(),connectingText:this.getConnectingText(),orbConfig:t,enableSounds:this.enableSounds,soundVolume:this.soundVolume,onStateChange:(n,s)=>{this.currentState=n,this.setAttribute("data-state",n),this.dispatchEvent(new CustomEvent("state-change",{detail:{state:n,previousState:s},bubbles:!0,composed:!0}))},onCallStart:n=>{this.dispatchEvent(new CustomEvent("call-start",{detail:n,bubbles:!0,composed:!0}))},onCallEnd:n=>{this.dispatchEvent(new CustomEvent("call-end",{detail:n,bubbles:!0,composed:!0}))},onError:n=>{this.dispatchEvent(new CustomEvent("error",{detail:{error:n},bubbles:!0,composed:!0}))}}}resolveColors(){return{...this.getResolvedTheme()==="dark"?Lm[this.colorPreset]||Lm.indigo:Nm[this.colorPreset]||Nm.indigo,...this.parseColors()}}parseColors(){if(!this.colors)return{};try{return JSON.parse(this.colors)}catch(e){return console.warn("Failed to parse colors JSON",e),{}}}parseOrbConfig(){if(!this.orbConfig)return{};try{return JSON.parse(this.orbConfig)}catch(e){return console.warn("Failed to parse orb-config JSON",e),{}}}syncHostSizing(){if(this.mode==="pill"||this.mode==="float"){this.style.removeProperty("--hanc-orb-size");return}const e=Number.isFinite(this.size)&&this.size>0?this.size:ur;this.style.setProperty("--hanc-orb-size",`${e}px`)}getButtonText(){return this.buttonText||this.buttonStartText||"Start call"}getActiveButtonText(){return this.activeButtonText||this.buttonEndText||"End call"}getConnectingText(){return this.connectingText||this.buttonConnectingText||"Connecting..."}applyThemeToWidget(){var n,s,r;const e=this.getResolvedTheme(),t=this.resolveColors();(n=this.widget)==null||n.setColors(t),e==="dark"?(s=this.widget)==null||s.setGlowSettings(.8,.4):(r=this.widget)==null||r.setGlowSettings(.4,.2)}setupThemeListener(){this.theme!=="auto"||typeof window>"u"||(this.themeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.themeQuery.addEventListener("change",this.handleThemeChange))}teardownThemeListener(){this.themeQuery&&(this.themeQuery.removeEventListener("change",this.handleThemeChange),this.themeQuery=null)}getResolvedTheme(){var e;return this.theme==="auto"?(e=this.themeQuery)!=null&&e.matches?"dark":"light":this.theme}};Ud.styles=[SC,Hd`
4636
4636
  :host {
4637
4637
  display: inline-block;
4638
4638
  position: relative;
4639
4639
 
4640
- /* Layout-safe defaults: reserve space BEFORE any JS runs */
4641
- width: var(--hanc-orb-size, ${Ss}px);
4642
- height: var(--hanc-orb-size, ${Ss}px);
4643
- min-width: var(--hanc-orb-size, ${Ss}px);
4644
- min-height: var(--hanc-orb-size, ${Ss}px);
4640
+ /* ВАЖНО: резервируем место сразу, до JS */
4641
+ width: var(--hanc-orb-size, ${ur}px);
4642
+ height: var(--hanc-orb-size, ${ur}px);
4643
+ min-width: var(--hanc-orb-size, ${ur}px);
4644
+ min-height: var(--hanc-orb-size, ${ur}px);
4645
4645
  }
4646
4646
 
4647
4647
  :host([hidden]) {
@@ -4653,9 +4653,9 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
4653
4653
  inset: auto;
4654
4654
  width: 0;
4655
4655
  height: 0;
4656
- pointer-events: none;
4657
4656
  min-width: 0;
4658
4657
  min-height: 0;
4658
+ pointer-events: none;
4659
4659
  }
4660
4660
 
4661
4661
  :host([mode='float']) #orb-container {
@@ -4667,7 +4667,6 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
4667
4667
  height: 100%;
4668
4668
  }
4669
4669
 
4670
- /* Pill mode is content-sized; host should NOT reserve the orb square */
4671
4670
  :host([mode='pill']) {
4672
4671
  width: auto;
4673
4672
  height: auto;
@@ -4679,4 +4678,4 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
4679
4678
  width: auto;
4680
4679
  height: auto;
4681
4680
  }
4682
- `];let bt=Ud;Ot([Bt({type:String,attribute:"agent-id"})],bt.prototype,"agentId",2),Ot([Bt({type:String,attribute:"voice-service-url"})],bt.prototype,"voiceServiceUrl",2),Ot([Bt({type:Number})],bt.prototype,"size",2),Ot([Bt({type:String,reflect:!0})],bt.prototype,"mode",2),Ot([Bt({type:String})],bt.prototype,"position",2),Ot([Bt({type:String,attribute:"button-text"})],bt.prototype,"buttonText",2),Ot([Bt({type:String,attribute:"active-button-text"})],bt.prototype,"activeButtonText",2),Ot([Bt({type:String,attribute:"connecting-text"})],bt.prototype,"connectingText",2),Ot([Bt({type:String,attribute:"button-start-text"})],bt.prototype,"buttonStartText",2),Ot([Bt({type:String,attribute:"button-end-text"})],bt.prototype,"buttonEndText",2),Ot([Bt({type:String,attribute:"button-connecting-text"})],bt.prototype,"buttonConnectingText",2),Ot([Bt({type:Boolean,attribute:"enable-sounds"})],bt.prototype,"enableSounds",2),Ot([Bt({type:Number,attribute:"sound-volume"})],bt.prototype,"soundVolume",2),Ot([Bt({type:String})],bt.prototype,"colors",2),Ot([Bt({type:String,attribute:"orb-config"})],bt.prototype,"orbConfig",2),Ot([Bt({type:String,reflect:!0})],bt.prototype,"theme",2),Ot([Bt({type:String,attribute:"color-preset"})],bt.prototype,"colorPreset",2),Ot([gg("#orb-container")],bt.prototype,"orbContainer",2),Ot([pg()],bt.prototype,"currentState",2),ot.HancAiOrb=class extends bt{},ot.HancAiOrb=Ot([aa("hanc-ai-orb")],ot.HancAiOrb);var EC=Object.getOwnPropertyDescriptor,CC=(i,e,t,n)=>{for(var s=n>1?void 0:n?EC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=o(s)||s);return s};ot.InlineCall=class extends bt{constructor(){super(),this.mode="inline"}},ot.InlineCall=CC([aa("hanc-ai-inline-call")],ot.InlineCall);var MC=Object.defineProperty,wC=Object.getOwnPropertyDescriptor,Om=(i,e,t,n)=>{for(var s=n>1?void 0:n?wC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&MC(e,t,s),s};ot.FloatingCall=class extends bt{constructor(){super(),this.labelText="Need a help?",this.mode="float",this.position="bottom-right"}},Om([Bt({type:String,attribute:"label-text"})],ot.FloatingCall.prototype,"labelText",2),ot.FloatingCall=Om([aa("hanc-ai-floating-call")],ot.FloatingCall);var AC=Object.getOwnPropertyDescriptor,RC=(i,e,t,n)=>{for(var s=n>1?void 0:n?AC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=o(s)||s);return s};ot.PillCall=class extends bt{constructor(){super(),this.mode="pill"}},ot.PillCall=RC([aa("hanc-ai-pill-call")],ot.PillCall),ot.AudioAnalyzer=Uh,ot.HancAiOrbElement=bt,ot.HancAiWidget=Dm,ot.OrbRenderer=yl,ot.SoundManager=Im,ot.atmosphereFragmentShader=Jy,ot.atmosphereVertexShader=Yy,ot.glowFragmentShader=Oh,ot.glowVertexShader=Nh,ot.orbFragmentShader=Lh,ot.orbVertexShader=Dh,Object.defineProperty(ot,Symbol.toStringTag,{value:"Module"})}));
4681
+ `];let xt=Ud;Gt([Ft({type:String,attribute:"agent-id"})],xt.prototype,"agentId"),Gt([Ft({type:String,attribute:"voice-service-url"})],xt.prototype,"voiceServiceUrl"),Gt([Ft({type:Number,reflect:!0})],xt.prototype,"size"),Gt([Ft({type:String,reflect:!0})],xt.prototype,"mode"),Gt([Ft({type:String})],xt.prototype,"position"),Gt([Ft({type:String,attribute:"button-text"})],xt.prototype,"buttonText"),Gt([Ft({type:String,attribute:"active-button-text"})],xt.prototype,"activeButtonText"),Gt([Ft({type:String,attribute:"connecting-text"})],xt.prototype,"connectingText"),Gt([Ft({type:String,attribute:"button-start-text"})],xt.prototype,"buttonStartText"),Gt([Ft({type:String,attribute:"button-end-text"})],xt.prototype,"buttonEndText"),Gt([Ft({type:String,attribute:"button-connecting-text"})],xt.prototype,"buttonConnectingText"),Gt([Ft({type:Boolean,attribute:"enable-sounds"})],xt.prototype,"enableSounds"),Gt([Ft({type:Number,attribute:"sound-volume"})],xt.prototype,"soundVolume"),Gt([Ft({type:String})],xt.prototype,"colors"),Gt([Ft({type:String,attribute:"orb-config"})],xt.prototype,"orbConfig"),Gt([Ft({type:String,reflect:!0})],xt.prototype,"theme"),Gt([Ft({type:String,attribute:"color-preset"})],xt.prototype,"colorPreset"),Gt([gg("#orb-container")],xt.prototype,"orbContainer"),Gt([pg()],xt.prototype,"currentState");var TC=Object.getOwnPropertyDescriptor,EC=(i,e,t,n)=>{for(var s=n>1?void 0:n?TC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=o(s)||s);return s};_t.InlineCall=class extends xt{constructor(){super(),this.mode="inline"}},_t.InlineCall=EC([Do("hanc-ai-inline-call")],_t.InlineCall);var CC=Object.defineProperty,MC=Object.getOwnPropertyDescriptor,Om=(i,e,t,n)=>{for(var s=n>1?void 0:n?MC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&CC(e,t,s),s};_t.FloatingCall=class extends xt{constructor(){super(),this.labelText="Need a help?",this.mode="float",this.position="bottom-right"}},Om([Ft({type:String,attribute:"label-text"})],_t.FloatingCall.prototype,"labelText",2),_t.FloatingCall=Om([Do("hanc-ai-floating-call")],_t.FloatingCall);var wC=Object.getOwnPropertyDescriptor,AC=(i,e,t,n)=>{for(var s=n>1?void 0:n?wC(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=o(s)||s);return s};_t.PillCall=class extends xt{constructor(){super(),this.mode="pill"}},_t.PillCall=AC([Do("hanc-ai-pill-call")],_t.PillCall),_t.AudioAnalyzer=Uh,_t.HancAiOrbElement=xt,_t.HancAiWidget=Dm,_t.OrbRenderer=yl,_t.SoundManager=Im,_t.atmosphereFragmentShader=Jy,_t.atmosphereVertexShader=Yy,_t.glowFragmentShader=Oh,_t.glowVertexShader=Nh,_t.orbFragmentShader=Lh,_t.orbVertexShader=Dh,Object.defineProperty(_t,Symbol.toStringTag,{value:"Module"})}));