hanc-webrtc-widgets 2.6.20 → 2.7.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.
|
@@ -2,25 +2,25 @@
|
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2019 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
5
|
-
*/var dc;const Tt=globalThis,ta=Tt.ShadowRoot&&(Tt.ShadyCSS===void 0||Tt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ia=Symbol(),ps=new WeakMap;let ms=class{constructor(A,e,g){if(this._$cssResult$=!0,g!==ia)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=A,this.t=e}get styleSheet(){let A=this.o;const e=this.t;if(ta&&A===void 0){const g=e!==void 0&&e.length===1;g&&(A=ps.get(e)),A===void 0&&((this.o=A=new CSSStyleSheet).replaceSync(this.cssText),g&&ps.set(e,A))}return A}toString(){return this.cssText}};const mc=t=>new ms(typeof t=="string"?t:t+"",void 0,ia),
|
|
5
|
+
*/var dc;const Tt=globalThis,ta=Tt.ShadowRoot&&(Tt.ShadyCSS===void 0||Tt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ia=Symbol(),ps=new WeakMap;let ms=class{constructor(A,e,g){if(this._$cssResult$=!0,g!==ia)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=A,this.t=e}get styleSheet(){let A=this.o;const e=this.t;if(ta&&A===void 0){const g=e!==void 0&&e.length===1;g&&(A=ps.get(e)),A===void 0&&((this.o=A=new CSSStyleSheet).replaceSync(this.cssText),g&&ps.set(e,A))}return A}toString(){return this.cssText}};const mc=t=>new ms(typeof t=="string"?t:t+"",void 0,ia),Ti=(t,...A)=>{const e=t.length===1?t[0]:A.reduce((g,i,I)=>g+(C=>{if(C._$cssResult$===!0)return C.cssText;if(typeof C=="number")return C;throw Error("Value passed to 'css' function must be a 'css' function result: "+C+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[I+1],t[0]);return new ms(e,t,ia)},yc=(t,A)=>{if(ta)t.adoptedStyleSheets=A.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of A){const g=document.createElement("style"),i=Tt.litNonce;i!==void 0&&g.setAttribute("nonce",i),g.textContent=e.cssText,t.appendChild(g)}},ys=ta?t=>t:t=>t instanceof CSSStyleSheet?(A=>{let e="";for(const g of A.cssRules)e+=g.cssText;return mc(e)})(t):t;/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2017 Google LLC
|
|
8
8
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
9
|
-
*/const{is:bc,defineProperty:Nc,getOwnPropertyDescriptor:Sc,getOwnPropertyNames:kc,getOwnPropertySymbols:Rc,getPrototypeOf:Gc}=Object,qt=globalThis,bs=qt.trustedTypes,Mc=bs?bs.emptyScript:"",Ia=qt.reactiveElementPolyfillSupport,GI=(t,A)=>t,yC={toAttribute(t,A){switch(A){case Boolean:t=t?Mc:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,A){let e=t;switch(A){case Boolean:e=t!==null;break;case Number:e=t===null?null:Number(t);break;case Object:case Array:try{e=JSON.parse(t)}catch{e=null}}return e}},Ca=(t,A)=>!bc(t,A),Ns={attribute:!0,type:String,converter:yC,reflect:!1,hasChanged:Ca};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),qt.litPropertyMetadata??(qt.litPropertyMetadata=new WeakMap);let
|
|
9
|
+
*/const{is:bc,defineProperty:Nc,getOwnPropertyDescriptor:Sc,getOwnPropertyNames:kc,getOwnPropertySymbols:Rc,getPrototypeOf:Gc}=Object,qt=globalThis,bs=qt.trustedTypes,Mc=bs?bs.emptyScript:"",Ia=qt.reactiveElementPolyfillSupport,GI=(t,A)=>t,yC={toAttribute(t,A){switch(A){case Boolean:t=t?Mc:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,A){let e=t;switch(A){case Boolean:e=t!==null;break;case Number:e=t===null?null:Number(t);break;case Object:case Array:try{e=JSON.parse(t)}catch{e=null}}return e}},Ca=(t,A)=>!bc(t,A),Ns={attribute:!0,type:String,converter:yC,reflect:!1,hasChanged:Ca};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),qt.litPropertyMetadata??(qt.litPropertyMetadata=new WeakMap);let qi=class extends HTMLElement{static addInitializer(A){this._$Ei(),(this.l??(this.l=[])).push(A)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(A,e=Ns){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(A,e),!e.noAccessor){const g=Symbol(),i=this.getPropertyDescriptor(A,g,e);i!==void 0&&Nc(this.prototype,A,i)}}static getPropertyDescriptor(A,e,g){const{get:i,set:I}=Sc(this.prototype,A)??{get(){return this[e]},set(C){this[e]=C}};return{get(){return i==null?void 0:i.call(this)},set(C){const o=i==null?void 0:i.call(this);I.call(this,C),this.requestUpdate(A,o,g)},configurable:!0,enumerable:!0}}static getPropertyOptions(A){return this.elementProperties.get(A)??Ns}static _$Ei(){if(this.hasOwnProperty(GI("elementProperties")))return;const A=Gc(this);A.finalize(),A.l!==void 0&&(this.l=[...A.l]),this.elementProperties=new Map(A.elementProperties)}static finalize(){if(this.hasOwnProperty(GI("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(GI("properties"))){const e=this.properties,g=[...kc(e),...Rc(e)];for(const i of g)this.createProperty(i,e[i])}const A=this[Symbol.metadata];if(A!==null){const e=litPropertyMetadata.get(A);if(e!==void 0)for(const[g,i]of e)this.elementProperties.set(g,i)}this._$Eh=new Map;for(const[e,g]of this.elementProperties){const i=this._$Eu(e,g);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(A){const e=[];if(Array.isArray(A)){const g=new Set(A.flat(1/0).reverse());for(const i of g)e.unshift(ys(i))}else A!==void 0&&e.push(ys(A));return e}static _$Eu(A,e){const g=e.attribute;return g===!1?void 0:typeof g=="string"?g:typeof A=="string"?A.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var A;this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),(A=this.constructor.l)==null||A.forEach(e=>e(this))}addController(A){var e;(this._$EO??(this._$EO=new Set)).add(A),this.renderRoot!==void 0&&this.isConnected&&((e=A.hostConnected)==null||e.call(A))}removeController(A){var e;(e=this._$EO)==null||e.delete(A)}_$E_(){const A=new Map,e=this.constructor.elementProperties;for(const g of e.keys())this.hasOwnProperty(g)&&(A.set(g,this[g]),delete this[g]);A.size>0&&(this._$Ep=A)}createRenderRoot(){const A=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return yc(A,this.constructor.elementStyles),A}connectedCallback(){var A;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(A=this._$EO)==null||A.forEach(e=>{var g;return(g=e.hostConnected)==null?void 0:g.call(e)})}enableUpdating(A){}disconnectedCallback(){var A;(A=this._$EO)==null||A.forEach(e=>{var g;return(g=e.hostDisconnected)==null?void 0:g.call(e)})}attributeChangedCallback(A,e,g){this._$AK(A,g)}_$EC(A,e){var I;const g=this.constructor.elementProperties.get(A),i=this.constructor._$Eu(A,g);if(i!==void 0&&g.reflect===!0){const C=(((I=g.converter)==null?void 0:I.toAttribute)!==void 0?g.converter:yC).toAttribute(e,g.type);this._$Em=A,C==null?this.removeAttribute(i):this.setAttribute(i,C),this._$Em=null}}_$AK(A,e){var I;const g=this.constructor,i=g._$Eh.get(A);if(i!==void 0&&this._$Em!==i){const C=g.getPropertyOptions(i),o=typeof C.converter=="function"?{fromAttribute:C.converter}:((I=C.converter)==null?void 0:I.fromAttribute)!==void 0?C.converter:yC;this._$Em=i,this[i]=o.fromAttribute(e,C.type),this._$Em=null}}requestUpdate(A,e,g){if(A!==void 0){if(g??(g=this.constructor.getPropertyOptions(A)),!(g.hasChanged??Ca)(this[A],e))return;this.P(A,e,g)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(A,e,g){this._$AL.has(A)||this._$AL.set(A,e),g.reflect===!0&&this._$Em!==A&&(this._$Ej??(this._$Ej=new Set)).add(A)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const A=this.scheduleUpdate();return A!=null&&await A,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var g;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[I,C]of this._$Ep)this[I]=C;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[I,C]of i)C.wrapped!==!0||this._$AL.has(I)||this[I]===void 0||this.P(I,this[I],C)}let A=!1;const e=this._$AL;try{A=this.shouldUpdate(e),A?(this.willUpdate(e),(g=this._$EO)==null||g.forEach(i=>{var I;return(I=i.hostUpdate)==null?void 0:I.call(i)}),this.update(e)):this._$EU()}catch(i){throw A=!1,this._$EU(),i}A&&this._$AE(e)}willUpdate(A){}_$AE(A){var e;(e=this._$EO)==null||e.forEach(g=>{var i;return(i=g.hostUpdated)==null?void 0:i.call(g)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(A)),this.updated(A)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(A){return!0}update(A){this._$Ej&&(this._$Ej=this._$Ej.forEach(e=>this._$EC(e,this[e]))),this._$EU()}updated(A){}firstUpdated(A){}};qi.elementStyles=[],qi.shadowRootOptions={mode:"open"},qi[GI("elementProperties")]=new Map,qi[GI("finalized")]=new Map,Ia==null||Ia({ReactiveElement:qi}),(qt.reactiveElementVersions??(qt.reactiveElementVersions=[])).push("2.0.4");/**
|
|
10
10
|
* @license
|
|
11
11
|
* Copyright 2017 Google LLC
|
|
12
12
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
13
13
|
*/const MI=globalThis,bC=MI.trustedTypes,Ss=bC?bC.createPolicy("lit-html",{createHTML:t=>t}):void 0,ks="$lit$",Ht=`lit$${Math.random().toFixed(9).slice(2)}$`,Rs="?"+Ht,Fc=`<${Rs}>`,ri=document,FI=()=>ri.createComment(""),UI=t=>t===null||typeof t!="object"&&typeof t!="function",oa=Array.isArray,Uc=t=>oa(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",aa=`[
|
|
14
14
|
\f\r]`,LI=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Gs=/-->/g,Ms=/>/g,ci=RegExp(`>|${aa}(?:([^\\s"'>=/]+)(${aa}*=${aa}*(?:[^
|
|
15
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Fs=/'/g,Us=/"/g,Ls=/^(?:script|style|textarea|title)$/i,Lc=t=>(A,...e)=>({_$litType$:t,strings:A,values:e}),zA=Lc(1),
|
|
15
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Fs=/'/g,Us=/"/g,Ls=/^(?:script|style|textarea|title)$/i,Lc=t=>(A,...e)=>({_$litType$:t,strings:A,values:e}),zA=Lc(1),Hi=Symbol.for("lit-noChange"),ke=Symbol.for("lit-nothing"),Ks=new WeakMap,hi=ri.createTreeWalker(ri,129);function vs(t,A){if(!oa(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ss!==void 0?Ss.createHTML(A):A}const Kc=(t,A)=>{const e=t.length-1,g=[];let i,I=A===2?"<svg>":A===3?"<math>":"",C=LI;for(let o=0;o<e;o++){const a=t[o];let Q,n,s=-1,B=0;for(;B<a.length&&(C.lastIndex=B,n=C.exec(a),n!==null);)B=C.lastIndex,C===LI?n[1]==="!--"?C=Gs:n[1]!==void 0?C=Ms:n[2]!==void 0?(Ls.test(n[2])&&(i=RegExp("</"+n[2],"g")),C=ci):n[3]!==void 0&&(C=ci):C===ci?n[0]===">"?(C=i??LI,s=-1):n[1]===void 0?s=-2:(s=C.lastIndex-n[2].length,Q=n[1],C=n[3]===void 0?ci:n[3]==='"'?Us:Fs):C===Us||C===Fs?C=ci:C===Gs||C===Ms?C=LI:(C=ci,i=void 0);const E=C===ci&&t[o+1].startsWith("/>")?" ":"";I+=C===LI?a+Fc:s>=0?(g.push(Q),a.slice(0,s)+ks+a.slice(s)+Ht+E):a+Ht+(s===-2?o:E)}return[vs(t,I+(t[e]||"<?>")+(A===2?"</svg>":A===3?"</math>":"")),g]};class KI{constructor({strings:A,_$litType$:e},g){let i;this.parts=[];let I=0,C=0;const o=A.length-1,a=this.parts,[Q,n]=Kc(A,e);if(this.el=KI.createElement(Q,g),hi.currentNode=this.el.content,e===2||e===3){const s=this.el.content.firstChild;s.replaceWith(...s.childNodes)}for(;(i=hi.nextNode())!==null&&a.length<o;){if(i.nodeType===1){if(i.hasAttributes())for(const s of i.getAttributeNames())if(s.endsWith(ks)){const B=n[C++],E=i.getAttribute(s).split(Ht),d=/([.?@])?(.*)/.exec(B);a.push({type:1,index:I,name:d[2],strings:E,ctor:d[1]==="."?Jc:d[1]==="?"?Yc:d[1]==="@"?Tc:NC}),i.removeAttribute(s)}else s.startsWith(Ht)&&(a.push({type:6,index:I}),i.removeAttribute(s));if(Ls.test(i.tagName)){const s=i.textContent.split(Ht),B=s.length-1;if(B>0){i.textContent=bC?bC.emptyScript:"";for(let E=0;E<B;E++)i.append(s[E],FI()),hi.nextNode(),a.push({type:2,index:++I});i.append(s[B],FI())}}}else if(i.nodeType===8)if(i.data===Rs)a.push({type:2,index:I});else{let s=-1;for(;(s=i.data.indexOf(Ht,s+1))!==-1;)a.push({type:7,index:I}),s+=Ht.length-1}I++}}static createElement(A,e){const g=ri.createElement("template");return g.innerHTML=A,g}}function Pi(t,A,e=t,g){var C,o;if(A===Hi)return A;let i=g!==void 0?(C=e._$Co)==null?void 0:C[g]:e._$Cl;const I=UI(A)?void 0:A._$litDirective$;return(i==null?void 0:i.constructor)!==I&&((o=i==null?void 0:i._$AO)==null||o.call(i,!1),I===void 0?i=void 0:(i=new I(t),i._$AT(t,e,g)),g!==void 0?(e._$Co??(e._$Co=[]))[g]=i:e._$Cl=i),i!==void 0&&(A=Pi(t,i._$AS(t,A.values),i,g)),A}let vc=class{constructor(A,e){this._$AV=[],this._$AN=void 0,this._$AD=A,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(A){const{el:{content:e},parts:g}=this._$AD,i=((A==null?void 0:A.creationScope)??ri).importNode(e,!0);hi.currentNode=i;let I=hi.nextNode(),C=0,o=0,a=g[0];for(;a!==void 0;){if(C===a.index){let Q;a.type===2?Q=new vI(I,I.nextSibling,this,A):a.type===1?Q=new a.ctor(I,a.name,a.strings,this,A):a.type===6&&(Q=new qc(I,this,A)),this._$AV.push(Q),a=g[++o]}C!==(a==null?void 0:a.index)&&(I=hi.nextNode(),C++)}return hi.currentNode=ri,i}p(A){let e=0;for(const g of this._$AV)g!==void 0&&(g.strings!==void 0?(g._$AI(A,g,e),e+=g.strings.length-2):g._$AI(A[e])),e++}};class vI{get _$AU(){var A;return((A=this._$AM)==null?void 0:A._$AU)??this._$Cv}constructor(A,e,g,i){this.type=2,this._$AH=ke,this._$AN=void 0,this._$AA=A,this._$AB=e,this._$AM=g,this.options=i,this._$Cv=(i==null?void 0:i.isConnected)??!0}get parentNode(){let A=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&(A==null?void 0:A.nodeType)===11&&(A=e.parentNode),A}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(A,e=this){A=Pi(this,A,e),UI(A)?A===ke||A==null||A===""?(this._$AH!==ke&&this._$AR(),this._$AH=ke):A!==this._$AH&&A!==Hi&&this._(A):A._$litType$!==void 0?this.$(A):A.nodeType!==void 0?this.T(A):Uc(A)?this.k(A):this._(A)}O(A){return this._$AA.parentNode.insertBefore(A,this._$AB)}T(A){this._$AH!==A&&(this._$AR(),this._$AH=this.O(A))}_(A){this._$AH!==ke&&UI(this._$AH)?this._$AA.nextSibling.data=A:this.T(ri.createTextNode(A)),this._$AH=A}$(A){var I;const{values:e,_$litType$:g}=A,i=typeof g=="number"?this._$AC(A):(g.el===void 0&&(g.el=KI.createElement(vs(g.h,g.h[0]),this.options)),g);if(((I=this._$AH)==null?void 0:I._$AD)===i)this._$AH.p(e);else{const C=new vc(i,this),o=C.u(this.options);C.p(e),this.T(o),this._$AH=C}}_$AC(A){let e=Ks.get(A.strings);return e===void 0&&Ks.set(A.strings,e=new KI(A)),e}k(A){oa(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let g,i=0;for(const I of A)i===e.length?e.push(g=new vI(this.O(FI()),this.O(FI()),this,this.options)):g=e[i],g._$AI(I),i++;i<e.length&&(this._$AR(g&&g._$AB.nextSibling,i),e.length=i)}_$AR(A=this._$AA.nextSibling,e){var g;for((g=this._$AP)==null?void 0:g.call(this,!1,!0,e);A&&A!==this._$AB;){const i=A.nextSibling;A.remove(),A=i}}setConnected(A){var e;this._$AM===void 0&&(this._$Cv=A,(e=this._$AP)==null||e.call(this,A))}}let NC=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(A,e,g,i,I){this.type=1,this._$AH=ke,this._$AN=void 0,this.element=A,this.name=e,this._$AM=i,this.options=I,g.length>2||g[0]!==""||g[1]!==""?(this._$AH=Array(g.length-1).fill(new String),this.strings=g):this._$AH=ke}_$AI(A,e=this,g,i){const I=this.strings;let C=!1;if(I===void 0)A=Pi(this,A,e,0),C=!UI(A)||A!==this._$AH&&A!==Hi,C&&(this._$AH=A);else{const o=A;let a,Q;for(A=I[0],a=0;a<I.length-1;a++)Q=Pi(this,o[g+a],e,a),Q===Hi&&(Q=this._$AH[a]),C||(C=!UI(Q)||Q!==this._$AH[a]),Q===ke?A=ke:A!==ke&&(A+=(Q??"")+I[a+1]),this._$AH[a]=Q}C&&!i&&this.j(A)}j(A){A===ke?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,A??"")}},Jc=class extends NC{constructor(){super(...arguments),this.type=3}j(A){this.element[this.name]=A===ke?void 0:A}};class Yc extends NC{constructor(){super(...arguments),this.type=4}j(A){this.element.toggleAttribute(this.name,!!A&&A!==ke)}}class Tc extends NC{constructor(A,e,g,i,I){super(A,e,g,i,I),this.type=5}_$AI(A,e=this){if((A=Pi(this,A,e,0)??ke)===Hi)return;const g=this._$AH,i=A===ke&&g!==ke||A.capture!==g.capture||A.once!==g.once||A.passive!==g.passive,I=A!==ke&&(g===ke||i);i&&this.element.removeEventListener(this.name,this,g),I&&this.element.addEventListener(this.name,this,A),this._$AH=A}handleEvent(A){var e;typeof this._$AH=="function"?this._$AH.call(((e=this.options)==null?void 0:e.host)??this.element,A):this._$AH.handleEvent(A)}}class qc{constructor(A,e,g){this.element=A,this.type=6,this._$AN=void 0,this._$AM=e,this.options=g}get _$AU(){return this._$AM._$AU}_$AI(A){Pi(this,A)}}const Qa=MI.litHtmlPolyfillSupport;Qa==null||Qa(KI,vI),(MI.litHtmlVersions??(MI.litHtmlVersions=[])).push("3.2.1");const Hc=(t,A,e)=>{const g=(e==null?void 0:e.renderBefore)??A;let i=g._$litPart$;if(i===void 0){const I=(e==null?void 0:e.renderBefore)??null;g._$litPart$=i=new vI(A.insertBefore(FI(),I),I,void 0,e??{})}return i._$AI(t),i};/**
|
|
16
16
|
* @license
|
|
17
17
|
* Copyright 2017 Google LLC
|
|
18
18
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
19
|
-
*/let Zg=class extends
|
|
19
|
+
*/let Zg=class extends qi{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const A=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=A.firstChild),A}update(A){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(A),this._$Do=Hc(e,this.renderRoot,this.renderOptions)}connectedCallback(){var A;super.connectedCallback(),(A=this._$Do)==null||A.setConnected(!0)}disconnectedCallback(){var A;super.disconnectedCallback(),(A=this._$Do)==null||A.setConnected(!1)}render(){return Hi}};Zg._$litElement$=!0,Zg.finalized=!0,(dc=globalThis.litElementHydrateSupport)==null||dc.call(globalThis,{LitElement:Zg});const na=globalThis.litElementPolyfillSupport;na==null||na({LitElement:Zg}),(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.1.1");/**
|
|
20
20
|
* @license
|
|
21
21
|
* Copyright 2017 Google LLC
|
|
22
22
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
23
|
-
*/const
|
|
23
|
+
*/const Oi=t=>(A,e)=>{e!==void 0?e.addInitializer(()=>{customElements.define(t,A)}):customElements.define(t,A)};/**
|
|
24
24
|
* @license
|
|
25
25
|
* Copyright 2017 Google LLC
|
|
26
26
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
* @license
|
|
29
29
|
* Copyright 2017 Google LLC
|
|
30
30
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
31
|
-
*/function
|
|
31
|
+
*/function $A(t){return W({...t,state:!0,attribute:!1})}/**
|
|
32
32
|
* @license
|
|
33
33
|
* Copyright 2020 Google LLC
|
|
34
34
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -44,8 +44,8 @@
|
|
|
44
44
|
* @license
|
|
45
45
|
* Copyright 2020 Google LLC
|
|
46
46
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
47
|
-
*/const kC=()=>new eh;let eh=class{};const sa=new WeakMap,RC=Wc(class extends Ah{render(t){return ke}update(t,[A]){var g;const e=A!==this.Y;return e&&this.Y!==void 0&&this.rt(void 0),(e||this.lt!==this.ct)&&(this.Y=A,this.ht=(g=t.options)==null?void 0:g.host,this.rt(this.ct=t.element)),ke}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const A=this.ht??globalThis;let e=sa.get(A);e===void 0&&(e=new WeakMap,sa.set(A,e)),e.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),e.set(this.Y,t),t!==void 0&&this.Y.call(this.ht,t)}else this.Y.value=t}get lt(){var t,A;return typeof this.Y=="function"?(t=sa.get(this.ht??globalThis))==null?void 0:t.get(this.Y):(A=this.Y)==null?void 0:A.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function gh(t,A){return A.forEach(function(e){e&&typeof e!="string"&&!Array.isArray(e)&&Object.keys(e).forEach(function(g){if(g!=="default"&&!(g in t)){var i=Object.getOwnPropertyDescriptor(e,g);Object.defineProperty(t,g,i.get?i:{enumerable:!0,get:function(){return e[g]}})}})}),Object.freeze(t)}var th=Object.defineProperty,ih=(t,A,e)=>A in t?th(t,A,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[A]=e,Ys=(t,A,e)=>ih(t,typeof A!="symbol"?A+"":A,e);let sg=class{constructor(){Ys(this,"_locking"),Ys(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let A;const e=new Promise(i=>A=()=>{this._locks-=1,i()}),g=this._locking.then(()=>A);return this._locking=this._locking.then(()=>e),g}};function Re(t,A){if(!t)throw new Error(A)}const Ih=34028234663852886e22,Ch=-34028234663852886e22,oh=4294967295,ah=2147483647,Qh=-2147483648;function GC(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>ah||t<Qh)throw new Error("invalid int 32: "+t)}function Ba(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>oh||t<0)throw new Error("invalid uint 32: "+t)}function Ts(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>Ih||t<Ch))throw new Error("invalid float 32: "+t)}const qs=Symbol("@bufbuild/protobuf/enum-type");function nh(t){const A=t[qs];return Re(A,"missing enum type on enum object"),A}function Hs(t,A,e,g){t[qs]=Ps(A,e.map(i=>({no:i.no,name:i.name,localName:t[i.no]})))}function Ps(t,A,e){const g=Object.create(null),i=Object.create(null),I=[];for(const C of A){const o=Os(C);I.push(o),g[C.name]=o,i[C.no]=o}return{typeName:t,values:I,findName(C){return g[C]},findNumber(C){return i[C]}}}function sh(t,A,e){const g={};for(const i of A){const I=Os(i);g[I.localName]=I.no,g[I.no]=I.localName}return Hs(g,t,A),g}function Os(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class Ea{equals(A){return this.getType().runtime.util.equals(this.getType(),this,A)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(A,e){const g=this.getType(),i=g.runtime.bin,I=i.makeReadOptions(e);return i.readMessage(this,I.readerFactory(A),A.byteLength,I),this}fromJson(A,e){const g=this.getType(),i=g.runtime.json,I=i.makeReadOptions(e);return i.readMessage(g,A,I,this),this}fromJsonString(A,e){let g;try{g=JSON.parse(A)}catch(i){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(i instanceof Error?i.message:String(i)))}return this.fromJson(g,e)}toBinary(A){const e=this.getType(),g=e.runtime.bin,i=g.makeWriteOptions(A),I=i.writerFactory();return g.writeMessage(this,I,i),I.finish()}toJson(A){const e=this.getType(),g=e.runtime.json,i=g.makeWriteOptions(A);return g.writeMessage(this,i)}toJsonString(A){var e;const g=this.toJson(A);return JSON.stringify(g,null,(e=A==null?void 0:A.prettySpaces)!==null&&e!==void 0?e:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Bh(t,A,e,g){var i;const I=(i=g==null?void 0:g.localName)!==null&&i!==void 0?i:A.substring(A.lastIndexOf(".")+1),C={[I]:function(o){t.util.initFields(this),t.util.initPartial(o,this)}}[I];return Object.setPrototypeOf(C.prototype,new Ea),Object.assign(C,{runtime:t,typeName:A,fields:t.util.newFieldList(e),fromBinary(o,a){return new C().fromBinary(o,a)},fromJson(o,a){return new C().fromJson(o,a)},fromJsonString(o,a){return new C().fromJsonString(o,a)},equals(o,a){return t.util.equals(C,o,a)}}),C}function Eh(){let t=0,A=0;for(let g=0;g<28;g+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<g,(i&128)==0)return this.assertBounds(),[t,A]}let e=this.buf[this.pos++];if(t|=(e&15)<<28,A=(e&112)>>4,(e&128)==0)return this.assertBounds(),[t,A];for(let g=3;g<=31;g+=7){let i=this.buf[this.pos++];if(A|=(i&127)<<g,(i&128)==0)return this.assertBounds(),[t,A]}throw new Error("invalid varint")}function ra(t,A,e){for(let I=0;I<28;I=I+7){const C=t>>>I,o=!(!(C>>>7)&&A==0),a=(o?C|128:C)&255;if(e.push(a),!o)return}const g=t>>>28&15|(A&7)<<4,i=A>>3!=0;if(e.push((i?g|128:g)&255),!!i){for(let I=3;I<31;I=I+7){const C=A>>>I,o=!!(C>>>7),a=(o?C|128:C)&255;if(e.push(a),!o)return}e.push(A>>>31&1)}}const MC=4294967296;function Vs(t){const A=t[0]==="-";A&&(t=t.slice(1));const e=1e6;let g=0,i=0;function I(C,o){const a=Number(t.slice(C,o));i*=e,g=g*e+a,g>=MC&&(i=i+(g/MC|0),g=g%MC)}return I(-24,-18),I(-18,-12),I(-12,-6),I(-6),A?Ws(g,i):ca(g,i)}function rh(t,A){let e=ca(t,A);const g=e.hi&2147483648;g&&(e=Ws(e.lo,e.hi));const i=js(e.lo,e.hi);return g?"-"+i:i}function js(t,A){if({lo:t,hi:A}=ch(t,A),A<=2097151)return String(MC*A+t);const e=t&16777215,g=(t>>>24|A<<8)&16777215,i=A>>16&65535;let I=e+g*6777216+i*6710656,C=g+i*8147497,o=i*2;const a=1e7;return I>=a&&(C+=Math.floor(I/a),I%=a),C>=a&&(o+=Math.floor(C/a),C%=a),o.toString()+Xs(C)+Xs(I)}function ch(t,A){return{lo:t>>>0,hi:A>>>0}}function ca(t,A){return{lo:t|0,hi:A|0}}function Ws(t,A){return A=~A,t?t=~t+1:A+=1,ca(t,A)}const Xs=t=>{const A=String(t);return"0000000".slice(A.length)+A};function Zs(t,A){if(t>=0){for(;t>127;)A.push(t&127|128),t=t>>>7;A.push(t)}else{for(let e=0;e<9;e++)A.push(t&127|128),t=t>>7;A.push(1)}}function hh(){let t=this.buf[this.pos++],A=t&127;if((t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<7,(t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<14,(t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<21,(t&128)==0)return this.assertBounds(),A;t=this.buf[this.pos++],A|=(t&15)<<28;for(let e=5;(t&128)!==0&&e<10;e++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),A>>>0}function dh(){const t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const i=BigInt("-9223372036854775808"),I=BigInt("9223372036854775807"),C=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(a){const Q=typeof a=="bigint"?a:BigInt(a);if(Q>I||Q<i)throw new Error("int64 invalid: ".concat(a));return Q},uParse(a){const Q=typeof a=="bigint"?a:BigInt(a);if(Q>o||Q<C)throw new Error("uint64 invalid: ".concat(a));return Q},enc(a){return t.setBigInt64(0,this.parse(a),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(a){return t.setBigInt64(0,this.uParse(a),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(a,Q){return t.setInt32(0,a,!0),t.setInt32(4,Q,!0),t.getBigInt64(0,!0)},uDec(a,Q){return t.setInt32(0,a,!0),t.setInt32(4,Q,!0),t.getBigUint64(0,!0)}}}const e=i=>Re(/^-?[0-9]+$/.test(i),"int64 invalid: ".concat(i)),g=i=>Re(/^[0-9]+$/.test(i),"uint64 invalid: ".concat(i));return{zero:"0",supported:!1,parse(i){return typeof i!="string"&&(i=i.toString()),e(i),i},uParse(i){return typeof i!="string"&&(i=i.toString()),g(i),i},enc(i){return typeof i!="string"&&(i=i.toString()),e(i),Vs(i)},uEnc(i){return typeof i!="string"&&(i=i.toString()),g(i),Vs(i)},dec(i,I){return rh(i,I)},uDec(i,I){return js(i,I)}}}const Ne=dh();var $;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})($||($={}));var Pt;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"})(Pt||(Pt={}));function Ot(t,A,e){if(A===e)return!0;if(t==$.BYTES){if(!(A instanceof Uint8Array)||!(e instanceof Uint8Array)||A.length!==e.length)return!1;for(let g=0;g<A.length;g++)if(A[g]!==e[g])return!1;return!0}switch(t){case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return A==e}return!1}function Oi(t,A){switch(t){case $.BOOL:return!1;case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return A==0?Ne.zero:"0";case $.DOUBLE:case $.FLOAT:return 0;case $.BYTES:return new Uint8Array(0);case $.STRING:return"";default:return 0}}function zs(t,A){switch(t){case $.BOOL:return A===!1;case $.STRING:return A==="";case $.BYTES:return A instanceof Uint8Array&&!A.byteLength;default:return A==0}}var Le;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(Le||(Le={}));class xh{constructor(A){this.stack=[],this.textEncoder=A??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let A=0;for(let i=0;i<this.chunks.length;i++)A+=this.chunks[i].length;let e=new Uint8Array(A),g=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],g),g+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let A=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(A.byteLength),this.raw(A)}tag(A,e){return this.uint32((A<<3|e)>>>0)}raw(A){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(A),this}uint32(A){for(Ba(A);A>127;)this.buf.push(A&127|128),A=A>>>7;return this.buf.push(A),this}int32(A){return GC(A),Zs(A,this.buf),this}bool(A){return this.buf.push(A?1:0),this}bytes(A){return this.uint32(A.byteLength),this.raw(A)}string(A){let e=this.textEncoder.encode(A);return this.uint32(e.byteLength),this.raw(e)}float(A){Ts(A);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,A,!0),this.raw(e)}double(A){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,A,!0),this.raw(e)}fixed32(A){Ba(A);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,A,!0),this.raw(e)}sfixed32(A){GC(A);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,A,!0),this.raw(e)}sint32(A){return GC(A),A=(A<<1^A>>31)>>>0,Zs(A,this.buf),this}sfixed64(A){let e=new Uint8Array(8),g=new DataView(e.buffer),i=Ne.enc(A);return g.setInt32(0,i.lo,!0),g.setInt32(4,i.hi,!0),this.raw(e)}fixed64(A){let e=new Uint8Array(8),g=new DataView(e.buffer),i=Ne.uEnc(A);return g.setInt32(0,i.lo,!0),g.setInt32(4,i.hi,!0),this.raw(e)}int64(A){let e=Ne.enc(A);return ra(e.lo,e.hi,this.buf),this}sint64(A){let e=Ne.enc(A),g=e.hi>>31,i=e.lo<<1^g,I=(e.hi<<1|e.lo>>>31)^g;return ra(i,I,this.buf),this}uint64(A){let e=Ne.uEnc(A);return ra(e.lo,e.hi,this.buf),this}}class lh{constructor(A,e){this.varint64=Eh,this.uint32=hh,this.buf=A,this.len=A.length,this.pos=0,this.view=new DataView(A.buffer,A.byteOffset,A.byteLength),this.textDecoder=e??new TextDecoder}tag(){let A=this.uint32(),e=A>>>3,g=A&7;if(e<=0||g<0||g>5)throw new Error("illegal tag: field no "+e+" wire type "+g);return[e,g]}skip(A,e){let g=this.pos;switch(A){case Le.Varint:for(;this.buf[this.pos++]&128;);break;case Le.Bit64:this.pos+=4;case Le.Bit32:this.pos+=4;break;case Le.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Le.StartGroup:for(;;){const[I,C]=this.tag();if(C===Le.EndGroup){if(e!==void 0&&I!==e)throw new Error("invalid end group tag");break}this.skip(C,I)}break;default:throw new Error("cant skip wire type "+A)}return this.assertBounds(),this.buf.subarray(g,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let A=this.uint32();return A>>>1^-(A&1)}int64(){return Ne.dec(...this.varint64())}uint64(){return Ne.uDec(...this.varint64())}sint64(){let[A,e]=this.varint64(),g=-(A&1);return A=(A>>>1|(e&1)<<31)^g,e=e>>>1^g,Ne.dec(A,e)}bool(){let[A,e]=this.varint64();return A!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ne.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ne.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 A=this.uint32(),e=this.pos;return this.pos+=A,this.assertBounds(),this.buf.subarray(e,e+A)}string(){return this.textDecoder.decode(this.bytes())}}function fh(t,A,e,g){let i;return{typeName:A,extendee:e,get field(){if(!i){const I=typeof g=="function"?g():g;I.name=A.split(".").pop(),I.jsonName="[".concat(A,"]"),i=t.util.newFieldList([I]).list()[0]}return i},runtime:t}}function $s(t){const A=t.field.localName,e=Object.create(null);return e[A]=uh(t),[e,()=>e[A]]}function uh(t){const A=t.field;if(A.repeated)return[];if(A.default!==void 0)return A.default;switch(A.kind){case"enum":return A.T.values[0].no;case"scalar":return Oi(A.T,A.L);case"message":const e=A.T,g=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(g):g;case"map":throw"map fields are not allowed to be extensions"}}function Dh(t,A){if(!A.repeated&&(A.kind=="enum"||A.kind=="scalar")){for(let e=t.length-1;e>=0;--e)if(t[e].no==A.no)return[t[e]];return[]}return t.filter(e=>e.no===A.no)}let dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),FC=[];for(let t=0;t<dt.length;t++)FC[dt[t].charCodeAt(0)]=t;FC[45]=dt.indexOf("+"),FC[95]=dt.indexOf("/");const AB={dec(t){let A=t.length*3/4;t[t.length-2]=="="?A-=2:t[t.length-1]=="="&&(A-=1);let e=new Uint8Array(A),g=0,i=0,I,C=0;for(let o=0;o<t.length;o++){if(I=FC[t.charCodeAt(o)],I===void 0)switch(t[o]){case"=":i=0;case`
|
|
48
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:C=I,i=1;break;case 1:e[g++]=C<<2|(I&48)>>4,C=I,i=2;break;case 2:e[g++]=(C&15)<<4|(I&60)>>2,C=I,i=3;break;case 3:e[g++]=(C&3)<<6|I,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,g)},enc(t){let A="",e=0,g,i=0;for(let I=0;I<t.length;I++)switch(g=t[I],e){case 0:A+=dt[g>>2],i=(g&3)<<4,e=1;break;case 1:A+=dt[i|g>>4],i=(g&15)<<2,e=2;break;case 2:A+=dt[i|g>>6],A+=dt[g&63],e=0;break}return e&&(A+=dt[i],A+="=",e==1&&(A+="=")),A}};function _h(t,A,e){gB(A,t);const g=A.runtime.bin.makeReadOptions(e),i=Dh(t.getType().runtime.bin.listUnknownFields(t),A.field),[I,C]=$s(A);for(const o of i)A.runtime.bin.readField(I,g.readerFactory(o.data),A.field,o.wireType,g);return C()}function wh(t,A,e,g){gB(A,t);const i=A.runtime.bin.makeReadOptions(g),I=A.runtime.bin.makeWriteOptions(g);if(eB(t,A)){const Q=t.getType().runtime.bin.listUnknownFields(t).filter(n=>n.no!=A.field.no);t.getType().runtime.bin.discardUnknownFields(t);for(const n of Q)t.getType().runtime.bin.onUnknownField(t,n.no,n.wireType,n.data)}const C=I.writerFactory();let o=A.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},A.field),{opt:!0})),A.runtime.bin.writeField(o,e,C,I);const a=i.readerFactory(C.finish());for(;a.pos<a.len;){const[Q,n]=a.tag(),s=a.skip(n,Q);t.getType().runtime.bin.onUnknownField(t,Q,n,s)}}function eB(t,A){const e=t.getType();return A.extendee.typeName===e.typeName&&!!e.runtime.bin.listUnknownFields(t).find(g=>g.no==A.field.no)}function gB(t,A){Re(t.extendee.typeName==A.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function tB(t,A){const e=t.localName;if(t.repeated)return A[e].length>0;if(t.oneof)return A[t.oneof.localName].case===e;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?A[e]!==void 0:t.kind=="enum"?A[e]!==t.T.values[0].no:!zs(t.T,A[e]);case"message":return A[e]!==void 0;case"map":return Object.keys(A[e]).length>0}}function iB(t,A){const e=t.localName,g=!t.opt&&!t.req;if(t.repeated)A[e]=[];else if(t.oneof)A[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":A[e]={};break;case"enum":A[e]=g?t.T.values[0].no:void 0;break;case"scalar":A[e]=g?Oi(t.T,t.L):void 0;break;case"message":A[e]=void 0;break}}function xt(t,A){if(t===null||typeof t!="object"||!Object.getOwnPropertyNames(Ea.prototype).every(g=>g in t&&typeof t[g]=="function"))return!1;const e=t.getType();return e===null||typeof e!="function"||!("typeName"in e)||typeof e.typeName!="string"?!1:A===void 0?!0:e.typeName==A.typeName}function IB(t,A){return xt(A)||!t.fieldWrapper?A:t.fieldWrapper.wrapField(A)}$.DOUBLE,$.FLOAT,$.INT64,$.UINT64,$.INT32,$.UINT32,$.BOOL,$.STRING,$.BYTES;const CB={ignoreUnknownFields:!1},oB={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ph(t){return t?Object.assign(Object.assign({},CB),t):CB}function mh(t){return t?Object.assign(Object.assign({},oB),t):oB}const UC=Symbol(),LC=Symbol();function yh(){return{makeReadOptions:ph,makeWriteOptions:mh,readMessage(t,A,e,g){if(A==null||Array.isArray(A)||typeof A!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(zg(A)));g=g??new t;const i=new Map,I=e.typeRegistry;for(const[C,o]of Object.entries(A)){const a=t.fields.findJsonName(C);if(a){if(a.oneof){if(o===null&&a.kind=="scalar")continue;const Q=i.get(a.oneof);if(Q!==void 0)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(a.oneof.name,'" present: "').concat(Q,'", "').concat(C,'"'));i.set(a.oneof,C)}aB(g,o,a,e,t)}else{let Q=!1;if(I!=null&&I.findExtension&&C.startsWith("[")&&C.endsWith("]")){const n=I.findExtension(C.substring(1,C.length-1));if(n&&n.extendee.typeName==t.typeName){Q=!0;const[s,B]=$s(n);aB(s,o,n.field,e,n),wh(g,n,B(),e)}}if(!Q&&!e.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(C,'" is unknown'))}}return g},writeMessage(t,A){const e=t.getType(),g={};let i;try{for(i of e.fields.byNumber()){if(!tB(i,t)){if(i.req)throw"required field not set";if(!A.emitDefaultValues||!Nh(i))continue}const C=i.oneof?t[i.oneof.localName].value:t[i.localName],o=QB(i,C,A);o!==void 0&&(g[A.useProtoFieldName?i.name:i.jsonName]=o)}const I=A.typeRegistry;if(I!=null&&I.findExtensionFor)for(const C of e.runtime.bin.listUnknownFields(t)){const o=I.findExtensionFor(e.typeName,C.no);if(o&&eB(t,o)){const a=_h(t,o,A),Q=QB(o.field,a,A);Q!==void 0&&(g[o.field.jsonName]=Q)}}}catch(I){const C=i?"cannot encode field ".concat(e.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(e.typeName," to JSON"),o=I instanceof Error?I.message:String(I);throw new Error(C+(o.length>0?": ".concat(o):""))}return g},readScalar(t,A,e){return YI(t,A,e??Pt.BIGINT,!0)},writeScalar(t,A,e){if(A!==void 0&&(e||zs(t,A)))return KC(t,A)},debug:zg}}function zg(t){if(t===null)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return String(t)}}function aB(t,A,e,g,i){let I=e.localName;if(e.repeated){if(Re(e.kind!="map"),A===null)return;if(!Array.isArray(A))throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A)));const C=t[I];for(const o of A){if(o===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(o)));switch(e.kind){case"message":C.push(e.T.fromJson(o,g));break;case"enum":const a=ha(e.T,o,g.ignoreUnknownFields,!0);a!==LC&&C.push(a);break;case"scalar":try{C.push(YI(e.T,o,e.L,!0))}catch(Q){let n="cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(o));throw Q instanceof Error&&Q.message.length>0&&(n+=": ".concat(Q.message)),new Error(n)}break}}}else if(e.kind=="map"){if(A===null)return;if(typeof A!="object"||Array.isArray(A))throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A)));const C=t[I];for(const[o,a]of Object.entries(A)){if(a===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: map value null"));let Q;try{Q=bh(e.K,o)}catch(n){let s="cannot decode map key for field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw n instanceof Error&&n.message.length>0&&(s+=": ".concat(n.message)),new Error(s)}switch(e.V.kind){case"message":C[Q]=e.V.T.fromJson(a,g);break;case"enum":const n=ha(e.V.T,a,g.ignoreUnknownFields,!0);n!==LC&&(C[Q]=n);break;case"scalar":try{C[Q]=YI(e.V.T,a,Pt.BIGINT,!0)}catch(s){let B="cannot decode map value for field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw s instanceof Error&&s.message.length>0&&(B+=": ".concat(s.message)),new Error(B)}break}}}else switch(e.oneof&&(t=t[e.oneof.localName]={case:I},I="value"),e.kind){case"message":const C=e.T;if(A===null&&C.typeName!="google.protobuf.Value")return;let o=t[I];xt(o)?o.fromJson(A,g):(t[I]=o=C.fromJson(A,g),C.fieldWrapper&&!e.oneof&&(t[I]=C.fieldWrapper.unwrapField(o)));break;case"enum":const a=ha(e.T,A,g.ignoreUnknownFields,!1);switch(a){case UC:iB(e,t);break;case LC:break;default:t[I]=a;break}break;case"scalar":try{const Q=YI(e.T,A,e.L,!1);switch(Q){case UC:iB(e,t);break;default:t[I]=Q;break}}catch(Q){let n="cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw Q instanceof Error&&Q.message.length>0&&(n+=": ".concat(Q.message)),new Error(n)}break}}function bh(t,A){if(t===$.BOOL)switch(A){case"true":A=!0;break;case"false":A=!1;break}return YI(t,A,Pt.BIGINT,!0).toString()}function YI(t,A,e,g){if(A===null)return g?Oi(t,e):UC;switch(t){case $.DOUBLE:case $.FLOAT:if(A==="NaN")return Number.NaN;if(A==="Infinity")return Number.POSITIVE_INFINITY;if(A==="-Infinity")return Number.NEGATIVE_INFINITY;if(A===""||typeof A=="string"&&A.trim().length!==A.length||typeof A!="string"&&typeof A!="number")break;const i=Number(A);if(Number.isNaN(i)||!Number.isFinite(i))break;return t==$.FLOAT&&Ts(i),i;case $.INT32:case $.FIXED32:case $.SFIXED32:case $.SINT32:case $.UINT32:let I;if(typeof A=="number"?I=A:typeof A=="string"&&A.length>0&&A.trim().length===A.length&&(I=Number(A)),I===void 0)break;return t==$.UINT32||t==$.FIXED32?Ba(I):GC(I),I;case $.INT64:case $.SFIXED64:case $.SINT64:if(typeof A!="number"&&typeof A!="string")break;const C=Ne.parse(A);return e?C.toString():C;case $.FIXED64:case $.UINT64:if(typeof A!="number"&&typeof A!="string")break;const o=Ne.uParse(A);return e?o.toString():o;case $.BOOL:if(typeof A!="boolean")break;return A;case $.STRING:if(typeof A!="string")break;try{encodeURIComponent(A)}catch{throw new Error("invalid UTF8")}return A;case $.BYTES:if(A==="")return new Uint8Array(0);if(typeof A!="string")break;return AB.dec(A)}throw new Error}function ha(t,A,e,g){if(A===null)return t.typeName=="google.protobuf.NullValue"?0:g?t.values[0].no:UC;switch(typeof A){case"number":if(Number.isInteger(A))return A;break;case"string":const i=t.findName(A);if(i!==void 0)return i.no;if(e)return LC;break}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(zg(A)))}function Nh(t){return t.repeated||t.kind=="map"?!0:!(t.oneof||t.kind=="message"||t.opt||t.req)}function QB(t,A,e){if(t.kind=="map"){Re(typeof A=="object"&&A!=null);const g={},i=Object.entries(A);switch(t.V.kind){case"scalar":for(const[C,o]of i)g[C.toString()]=KC(t.V.T,o);break;case"message":for(const[C,o]of i)g[C.toString()]=o.toJson(e);break;case"enum":const I=t.V.T;for(const[C,o]of i)g[C.toString()]=da(I,o,e.enumAsInteger);break}return e.emitDefaultValues||i.length>0?g:void 0}if(t.repeated){Re(Array.isArray(A));const g=[];switch(t.kind){case"scalar":for(let i=0;i<A.length;i++)g.push(KC(t.T,A[i]));break;case"enum":for(let i=0;i<A.length;i++)g.push(da(t.T,A[i],e.enumAsInteger));break;case"message":for(let i=0;i<A.length;i++)g.push(A[i].toJson(e));break}return e.emitDefaultValues||g.length>0?g:void 0}switch(t.kind){case"scalar":return KC(t.T,A);case"enum":return da(t.T,A,e.enumAsInteger);case"message":return IB(t.T,A).toJson(e)}}function da(t,A,e){var g;if(Re(typeof A=="number"),t.typeName=="google.protobuf.NullValue")return null;if(e)return A;const i=t.findNumber(A);return(g=i==null?void 0:i.name)!==null&&g!==void 0?g:A}function KC(t,A){switch(t){case $.INT32:case $.SFIXED32:case $.SINT32:case $.FIXED32:case $.UINT32:return Re(typeof A=="number"),A;case $.FLOAT:case $.DOUBLE:return Re(typeof A=="number"),Number.isNaN(A)?"NaN":A===Number.POSITIVE_INFINITY?"Infinity":A===Number.NEGATIVE_INFINITY?"-Infinity":A;case $.STRING:return Re(typeof A=="string"),A;case $.BOOL:return Re(typeof A=="boolean"),A;case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return Re(typeof A=="bigint"||typeof A=="string"||typeof A=="number"),A.toString();case $.BYTES:return Re(A instanceof Uint8Array),AB.enc(A)}}const Vi=Symbol("@bufbuild/protobuf/unknown-fields"),nB={readUnknownFields:!0,readerFactory:t=>new lh(t)},sB={writeUnknownFields:!0,writerFactory:()=>new xh};function Sh(t){return t?Object.assign(Object.assign({},nB),t):nB}function kh(t){return t?Object.assign(Object.assign({},sB),t):sB}function Rh(){return{makeReadOptions:Sh,makeWriteOptions:kh,listUnknownFields(t){var A;return(A=t[Vi])!==null&&A!==void 0?A:[]},discardUnknownFields(t){delete t[Vi]},writeUnknownFields(t,A){const g=t[Vi];if(g)for(const i of g)A.tag(i.no,i.wireType).raw(i.data)},onUnknownField(t,A,e,g){const i=t;Array.isArray(i[Vi])||(i[Vi]=[]),i[Vi].push({no:A,wireType:e,data:g})},readMessage(t,A,e,g,i){const I=t.getType(),C=i?A.len:A.pos+e;let o,a;for(;A.pos<C&&([o,a]=A.tag(),!(i===!0&&a==Le.EndGroup));){const Q=I.fields.find(o);if(!Q){const n=A.skip(a,o);g.readUnknownFields&&this.onUnknownField(t,o,a,n);continue}BB(t,A,Q,a,g)}if(i&&(a!=Le.EndGroup||o!==e))throw new Error("invalid end group tag")},readField:BB,writeMessage(t,A,e){const g=t.getType();for(const i of g.fields.byNumber()){if(!tB(i,t)){if(i.req)throw new Error("cannot encode field ".concat(g.typeName,".").concat(i.name," to binary: required field not set"));continue}const I=i.oneof?t[i.oneof.localName].value:t[i.localName];EB(i,I,A,e)}return e.writeUnknownFields&&this.writeUnknownFields(t,A),A},writeField(t,A,e,g){A!==void 0&&EB(t,A,e,g)}}}function BB(t,A,e,g,i){let{repeated:I,localName:C}=e;switch(e.oneof&&(t=t[e.oneof.localName],t.case!=C&&delete t.value,t.case=C,C="value"),e.kind){case"scalar":case"enum":const o=e.kind=="enum"?$.INT32:e.T;let a=JC;if(e.kind=="scalar"&&e.L>0&&(a=Mh),I){let B=t[C];if(g==Le.LengthDelimited&&o!=$.STRING&&o!=$.BYTES){let d=A.uint32()+A.pos;for(;A.pos<d;)B.push(a(A,o))}else B.push(a(A,o))}else t[C]=a(A,o);break;case"message":const Q=e.T;I?t[C].push(vC(A,new Q,i,e)):xt(t[C])?vC(A,t[C],i,e):(t[C]=vC(A,new Q,i,e),Q.fieldWrapper&&!e.oneof&&!e.repeated&&(t[C]=Q.fieldWrapper.unwrapField(t[C])));break;case"map":let[n,s]=Gh(e,A,i);t[C][n]=s;break}}function vC(t,A,e,g){const i=A.getType().runtime.bin,I=g==null?void 0:g.delimited;return i.readMessage(A,t,I?g.no:t.uint32(),e,I),A}function Gh(t,A,e){const g=A.uint32(),i=A.pos+g;let I,C;for(;A.pos<i;){const[o]=A.tag();switch(o){case 1:I=JC(A,t.K);break;case 2:switch(t.V.kind){case"scalar":C=JC(A,t.V.T);break;case"enum":C=A.int32();break;case"message":C=vC(A,new t.V.T,e,void 0);break}break}}if(I===void 0&&(I=Oi(t.K,Pt.BIGINT)),typeof I!="string"&&typeof I!="number"&&(I=I.toString()),C===void 0)switch(t.V.kind){case"scalar":C=Oi(t.V.T,Pt.BIGINT);break;case"enum":C=t.V.T.values[0].no;break;case"message":C=new t.V.T;break}return[I,C]}function Mh(t,A){const e=JC(t,A);return typeof e=="bigint"?e.toString():e}function JC(t,A){switch(A){case $.STRING:return t.string();case $.BOOL:return t.bool();case $.DOUBLE:return t.double();case $.FLOAT:return t.float();case $.INT32:return t.int32();case $.INT64:return t.int64();case $.UINT64:return t.uint64();case $.FIXED64:return t.fixed64();case $.BYTES:return t.bytes();case $.FIXED32:return t.fixed32();case $.SFIXED32:return t.sfixed32();case $.SFIXED64:return t.sfixed64();case $.SINT64:return t.sint64();case $.UINT32:return t.uint32();case $.SINT32:return t.sint32()}}function EB(t,A,e,g){Re(A!==void 0);const i=t.repeated;switch(t.kind){case"scalar":case"enum":let I=t.kind=="enum"?$.INT32:t.T;if(i)if(Re(Array.isArray(A)),t.packed)Uh(e,I,t.no,A);else for(const C of A)TI(e,I,t.no,C);else TI(e,I,t.no,A);break;case"message":if(i){Re(Array.isArray(A));for(const C of A)rB(e,g,t,C)}else rB(e,g,t,A);break;case"map":Re(typeof A=="object"&&A!=null);for(const[C,o]of Object.entries(A))Fh(e,g,t,C,o);break}}function Fh(t,A,e,g,i){t.tag(e.no,Le.LengthDelimited),t.fork();let I=g;switch(e.K){case $.INT32:case $.FIXED32:case $.UINT32:case $.SFIXED32:case $.SINT32:I=Number.parseInt(g);break;case $.BOOL:Re(g=="true"||g=="false"),I=g=="true";break}switch(TI(t,e.K,1,I),e.V.kind){case"scalar":TI(t,e.V.T,2,i);break;case"enum":TI(t,$.INT32,2,i);break;case"message":Re(i!==void 0),t.tag(2,Le.LengthDelimited).bytes(i.toBinary(A));break}t.join()}function rB(t,A,e,g){const i=IB(e.T,g);e.delimited?t.tag(e.no,Le.StartGroup).raw(i.toBinary(A)).tag(e.no,Le.EndGroup):t.tag(e.no,Le.LengthDelimited).bytes(i.toBinary(A))}function TI(t,A,e,g){Re(g!==void 0);let[i,I]=cB(A);t.tag(e,i)[I](g)}function Uh(t,A,e,g){if(!g.length)return;t.tag(e,Le.LengthDelimited).fork();let[,i]=cB(A);for(let I=0;I<g.length;I++)t[i](g[I]);t.join()}function cB(t){let A=Le.Varint;switch(t){case $.BYTES:case $.STRING:A=Le.LengthDelimited;break;case $.DOUBLE:case $.FIXED64:case $.SFIXED64:A=Le.Bit64;break;case $.FIXED32:case $.SFIXED32:case $.FLOAT:A=Le.Bit32;break}const e=$[t].toLowerCase();return[A,e]}function Lh(){return{setEnumType:Hs,initPartial(t,A){if(t===void 0)return;const e=A.getType();for(const g of e.fields.byMember()){const i=g.localName,I=A,C=t;if(C[i]!=null)switch(g.kind){case"oneof":const o=C[i].case;if(o===void 0)continue;const a=g.findField(o);let Q=C[i].value;a&&a.kind=="message"&&!xt(Q,a.T)?Q=new a.T(Q):a&&a.kind==="scalar"&&a.T===$.BYTES&&(Q=qI(Q)),I[i]={case:o,value:Q};break;case"scalar":case"enum":let n=C[i];g.T===$.BYTES&&(n=g.repeated?n.map(qI):qI(n)),I[i]=n;break;case"map":switch(g.V.kind){case"scalar":case"enum":if(g.V.T===$.BYTES)for(const[E,d]of Object.entries(C[i]))I[i][E]=qI(d);else Object.assign(I[i],C[i]);break;case"message":const B=g.V.T;for(const E of Object.keys(C[i])){let d=C[i][E];B.fieldWrapper||(d=new B(d)),I[i][E]=d}break}break;case"message":const s=g.T;if(g.repeated)I[i]=C[i].map(B=>xt(B,s)?B:new s(B));else{const B=C[i];s.fieldWrapper?s.typeName==="google.protobuf.BytesValue"?I[i]=qI(B):I[i]=B:I[i]=xt(B,s)?B:new s(B)}break}}},equals(t,A,e){return A===e?!0:!A||!e?!1:t.fields.byMember().every(g=>{const i=A[g.localName],I=e[g.localName];if(g.repeated){if(i.length!==I.length)return!1;switch(g.kind){case"message":return i.every((C,o)=>g.T.equals(C,I[o]));case"scalar":return i.every((C,o)=>Ot(g.T,C,I[o]));case"enum":return i.every((C,o)=>Ot($.INT32,C,I[o]))}throw new Error("repeated cannot contain ".concat(g.kind))}switch(g.kind){case"message":let C=i,o=I;return g.T.fieldWrapper&&(C!==void 0&&!xt(C)&&(C=g.T.fieldWrapper.wrapField(C)),o!==void 0&&!xt(o)&&(o=g.T.fieldWrapper.wrapField(o))),g.T.equals(C,o);case"enum":return Ot($.INT32,i,I);case"scalar":return Ot(g.T,i,I);case"oneof":if(i.case!==I.case)return!1;const a=g.findField(i.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(i.value,I.value);case"enum":return Ot($.INT32,i.value,I.value);case"scalar":return Ot(a.T,i.value,I.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const Q=Object.keys(i).concat(Object.keys(I));switch(g.V.kind){case"message":const n=g.V.T;return Q.every(B=>n.equals(i[B],I[B]));case"enum":return Q.every(B=>Ot($.INT32,i[B],I[B]));case"scalar":const s=g.V.T;return Q.every(B=>Ot(s,i[B],I[B]))}break}})},clone(t){const A=t.getType(),e=new A,g=e;for(const i of A.fields.byMember()){const I=t[i.localName];let C;if(i.repeated)C=I.map(YC);else if(i.kind=="map"){C=g[i.localName];for(const[o,a]of Object.entries(I))C[o]=YC(a)}else i.kind=="oneof"?C=i.findField(I.case)?{case:I.case,value:YC(I.value)}:{case:void 0}:C=YC(I);g[i.localName]=C}for(const i of A.runtime.bin.listUnknownFields(t))A.runtime.bin.onUnknownField(g,i.no,i.wireType,i.data);return e}}}function YC(t){if(t===void 0)return t;if(xt(t))return t.clone();if(t instanceof Uint8Array){const A=new Uint8Array(t.byteLength);return A.set(t),A}return t}function qI(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Kh(t,A,e){return{syntax:t,json:yh(),bin:Rh(),util:Object.assign(Object.assign({},Lh()),{newFieldList:A,initFields:e}),makeMessageType(g,i,I){return Bh(this,g,i,I)},makeEnum:sh,makeEnumType:Ps,getEnumType:nh,makeExtension(g,i,I){return fh(this,g,i,I)}}}class vh{constructor(A,e){this._fields=A,this._normalizer=e}findJsonName(A){if(!this.jsonNames){const e={};for(const g of this.list())e[g.jsonName]=e[g.name]=g;this.jsonNames=e}return this.jsonNames[A]}find(A){if(!this.numbers){const e={};for(const g of this.list())e[g.no]=g;this.numbers=e}return this.numbers[A]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((A,e)=>A.no-e.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const A=this.members;let e;for(const g of this.list())g.oneof?g.oneof!==e&&(e=g.oneof,A.push(e)):A.push(g)}return this.members}}function hB(t,A){const e=dB(t);return A?e:Ph(Hh(e))}function Jh(t){return hB(t,!1)}const Yh=dB;function dB(t){let A=!1;const e=[];for(let g=0;g<t.length;g++){let i=t.charAt(g);switch(i){case"_":A=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":e.push(i),A=!1;break;default:A&&(A=!1,i=i.toUpperCase()),e.push(i);break}}return e.join("")}const Th=new Set(["constructor","toString","toJSON","valueOf"]),qh=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xB=t=>"".concat(t,"$"),Hh=t=>qh.has(t)?xB(t):t,Ph=t=>Th.has(t)?xB(t):t;class Oh{constructor(A){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=A,this.localName=Jh(A)}addField(A){Re(A.oneof===this,"field ".concat(A.name," not one of ").concat(this.name)),this.fields.push(A)}findField(A){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[A]}}function Vh(t,A){var e,g,i,I,C,o;const a=[];let Q;for(const n of typeof t=="function"?t():t){const s=n;if(s.localName=hB(n.name,n.oneof!==void 0),s.jsonName=(e=n.jsonName)!==null&&e!==void 0?e:Yh(n.name),s.repeated=(g=n.repeated)!==null&&g!==void 0?g:!1,n.kind=="scalar"&&(s.L=(i=n.L)!==null&&i!==void 0?i:Pt.BIGINT),s.delimited=(I=n.delimited)!==null&&I!==void 0?I:!1,s.req=(C=n.req)!==null&&C!==void 0?C:!1,s.opt=(o=n.opt)!==null&&o!==void 0?o:!1,n.packed===void 0&&(s.packed=n.kind=="enum"||n.kind=="scalar"&&n.T!=$.BYTES&&n.T!=$.STRING),n.oneof!==void 0){const B=typeof n.oneof=="string"?n.oneof:n.oneof.name;(!Q||Q.name!=B)&&(Q=new Oh(B)),s.oneof=Q,Q.addField(s)}a.push(s)}return a}const T=Kh("proto3",t=>new vh(t,A=>Vh(A)),t=>{for(const A of t.getType().fields.byMember()){if(A.opt)continue;const e=A.localName,g=t;if(A.repeated){g[e]=[];continue}switch(A.kind){case"oneof":g[e]={case:void 0};break;case"enum":g[e]=0;break;case"map":g[e]={};break;case"scalar":g[e]=Oi(A.T,A.L);break}}});class Bg extends Ea{constructor(A){super(),this.seconds=Ne.zero,this.nanos=0,T.util.initPartial(A,this)}fromJson(A,e){if(typeof A!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(T.json.debug(A)));const g=A.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(!g)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(g[1]+"-"+g[2]+"-"+g[3]+"T"+g[4]+":"+g[5]+":"+g[6]+(g[8]?g[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=Ne.parse(i/1e3),this.nanos=0,g[7]&&(this.nanos=parseInt("1"+g[7]+"0".repeat(9-g[7].length))-1e9),this}toJson(A){const e=Number(this.seconds)*1e3;if(e<Date.parse("0001-01-01T00:00:00Z")||e>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 g="Z";if(this.nanos>0){const i=(this.nanos+1e9).toString().substring(1);i.substring(3)==="000000"?g="."+i.substring(0,3)+"Z":i.substring(6)==="000"?g="."+i.substring(0,6)+"Z":g="."+i+"Z"}return new Date(e).toISOString().replace(".000Z",g)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Bg.fromDate(new Date)}static fromDate(A){const e=A.getTime();return new Bg({seconds:Ne.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(A,e){return new Bg().fromBinary(A,e)}static fromJson(A,e){return new Bg().fromJson(A,e)}static fromJsonString(A,e){return new Bg().fromJsonString(A,e)}static equals(A,e){return T.util.equals(Bg,A,e)}}Bg.runtime=T,Bg.typeName="google.protobuf.Timestamp",Bg.fields=T.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const jh=T.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Bg},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Wh,repeated:!0},{no:5,name:"events",kind:"message",T:Zh,repeated:!0}]),Wh=T.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:Xh,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Xh=T.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Bg},{no:3,name:"value",kind:"scalar",T:2}]),Zh=T.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:Bg},{no:7,name:"normalized_end_timestamp",kind:"message",T:Bg,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),lB=T.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ug=T.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ve=T.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"}]),xa=T.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),HI=T.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),PI=T.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Lg=T.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"}]),ji=T.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"}]),zh=T.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),je=T.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"}]),TC=T.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:qC,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:GB}]),qC=T.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),$h=T.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:T.getEnumType(ve),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}]),di=T.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:T.getEnumType(Wi)},{no:4,name:"tracks",kind:"message",T:Xi,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:$h},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:T.getEnumType(OI)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:T.getEnumType(Lg)},{no:18,name:"kind_details",kind:"enum",T:T.getEnumType(Ad),repeated:!0}]),Wi=T.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),OI=T.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Ad=T.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),lg=T.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ed=T.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:xi,repeated:!0}]),Xi=T.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:T.getEnumType(Ug)},{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:T.getEnumType(ve)},{no:10,name:"layers",kind:"message",T:xi,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:ed,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:T.getEnumType(lg)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:GB},{no:19,name:"audio_features",kind:"enum",T:T.getEnumType(je),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(lB)}]),xi=T.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(xa)},{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}]),Eg=T.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:T.getEnumType(HA)},{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:uB,oneof:"value"},{no:3,name:"speaker",kind:"message",T:gd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:DB,oneof:"value"},{no:7,name:"transcription",kind:"message",T:td,oneof:"value"},{no:8,name:"metrics",kind:"message",T:jh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:la,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:_B,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:wB,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:pB,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ua,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Da,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:_a,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),HA=T.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),gd=T.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:fB,repeated:!0}]),fB=T.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}]),uB=T.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}]),DB=T.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),td=T.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:id,repeated:!0}]),id=T.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),la=T.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}]),_B=T.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}]),wB=T.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),pB=T.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:mB,oneof:"value"}]),mB=T.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}]),yB=T.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),bB=T.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:T.getEnumType(NB)},{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}]),NB=T.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Id=T.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:T.getEnumType(SB)},{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}]),SB=T.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"}]),kB=T.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:RB},{no:2,name:"screen",kind:"message",T:RB},{no:3,name:"resume_connection",kind:"enum",T:T.getEnumType(PI)},{no:4,name:"disabled_codecs",kind:"message",T:Cd},{no:5,name:"force_relay",kind:"enum",T:T.getEnumType(PI)}]),RB=T.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:T.getEnumType(PI)}]),Cd=T.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:qC,repeated:!0},{no:2,name:"publish",kind:"message",T:qC,repeated:!0}]),GB=T.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),fa=T.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),MB=T.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:T.getEnumType(fa)},{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"}),FB=T.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ua=T.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:T.getEnumType(lg)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:MB,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:FB,oneof:"content_header"}],{localName:"DataStream_Header"}),Da=T.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"}),_a=T.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"}),Kg=T.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),wa=T.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),od=T.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ad=T.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:li,oneof:"message"},{no:2,name:"answer",kind:"message",T:li,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ya,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ma,oneof:"message"},{no:5,name:"mute",kind:"message",T:ba,oneof:"message"},{no:6,name:"subscription",kind:"message",T:HC,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:LB,oneof:"message"},{no:8,name:"leave",kind:"message",T:PC,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:vB,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qB,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:HB,oneof:"message"},{no:13,name:"simulate",kind:"message",T:$g,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:JB,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:VB,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:KB,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ed,oneof:"message"}]),UB=T.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Qd,oneof:"message"},{no:2,name:"answer",kind:"message",T:li,oneof:"message"},{no:3,name:"offer",kind:"message",T:li,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ya,oneof:"message"},{no:5,name:"update",kind:"message",T:Bd,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Na,oneof:"message"},{no:8,name:"leave",kind:"message",T:PC,oneof:"message"},{no:9,name:"mute",kind:"message",T:ba,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:rd,oneof:"message"},{no:11,name:"room_update",kind:"message",T:cd,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:dd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ld,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ud,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Dd,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:sd,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:nd,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:wd,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:yd,oneof:"message"},{no:22,name:"request_response",kind:"message",T:bd,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Nd,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:_d,oneof:"message"}]),pa=T.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),ma=T.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:T.getEnumType(Ug)},{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:T.getEnumType(ve)},{no:9,name:"layers",kind:"message",T:xi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:pa,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:T.getEnumType(lg)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(lB)},{no:17,name:"audio_features",kind:"enum",T:T.getEnumType(je),repeated:!0}]),ya=T.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:T.getEnumType(Kg)},{no:3,name:"final",kind:"scalar",T:8}]),ba=T.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Qd=T.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:TC},{no:2,name:"participant",kind:"message",T:di},{no:3,name:"other_participants",kind:"message",T:di,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:YB,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:kB},{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:bB},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:qC,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),nd=T.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:YB,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:kB},{no:3,name:"server_info",kind:"message",T:bB},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Na=T.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Xi}]),sd=T.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),li=T.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}]),Bd=T.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:di,repeated:!0}]),HC=T.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:yB,repeated:!0}]),LB=T.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:T.getEnumType(xa)},{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}]),KB=T.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:T.getEnumType(je),repeated:!0}]),Ed=T.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}]),PC=T.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:T.getEnumType(Lg)},{no:3,name:"action",kind:"enum",T:T.getEnumType(Zi)},{no:4,name:"regions",kind:"message",T:pd}]),Zi=T.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),vB=T.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:xi,repeated:!0}]),JB=T.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}]),YB=T.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}]),rd=T.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:fB,repeated:!0}]),cd=T.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:TC}]),hd=T.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:T.getEnumType(HI)},{no:3,name:"score",kind:"scalar",T:2}]),dd=T.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:hd,repeated:!0}]),xd=T.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:T.getEnumType(wa)}]),ld=T.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:xd,repeated:!0}]),Sa=T.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(xa)},{no:2,name:"enabled",kind:"scalar",T:8}]),fd=T.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Sa,repeated:!0}]),ud=T.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Sa,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:fd,repeated:!0}]),TB=T.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}]),qB=T.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:TB,repeated:!0}]),Dd=T.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}]),_d=T.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:TC},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:di},{no:4,name:"other_participants",kind:"message",T:di,repeated:!0}]),HB=T.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:li},{no:2,name:"subscription",kind:"message",T:HC},{no:3,name:"publish_tracks",kind:"message",T:Na,repeated:!0},{no:4,name:"data_channels",kind:"message",T:OB,repeated:!0},{no:5,name:"offer",kind:"message",T:li},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:PB,repeated:!0}]),PB=T.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),OB=T.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:T.getEnumType(Kg)}]),$g=T.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:T.getEnumType(od),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"}]),VB=T.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),wd=T.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),pd=T.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:md,repeated:!0}]),md=T.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}]),yd=T.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:T.getEnumType(zh)}]),bd=T.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:T.getEnumType(ka)},{no:3,name:"message",kind:"scalar",T:9}]),ka=T.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Nd=T.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Sd(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var OC={exports:{}},kd=OC.exports,jB;function Rd(){return jB||(jB=1,function(t){(function(A,e){t.exports?t.exports=e():A.log=e()})(kd,function(){var A=function(){},e="undefined",g=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],I={},C=null;function o(c,h){var r=c[h];if(typeof r.bind=="function")return r.bind(c);try{return Function.prototype.bind.call(r,c)}catch{return function(){return Function.prototype.apply.apply(r,[c,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function Q(c){return c==="debug"&&(c="log"),typeof console===e?!1:c==="trace"&&g?a:console[c]!==void 0?o(console,c):console.log!==void 0?o(console,"log"):A}function n(){for(var c=this.getLevel(),h=0;h<i.length;h++){var r=i[h];this[r]=h<c?A:this.methodFactory(r,c,this.name)}if(this.log=this.debug,typeof console===e&&c<this.levels.SILENT)return"No console available for logging"}function s(c){return function(){typeof console!==e&&(n.call(this),this[c].apply(this,arguments))}}function B(c,h,r){return Q(c)||s.apply(this,arguments)}function E(c,h){var r=this,f,_,l,D="loglevel";typeof c=="string"?D+=":"+c:typeof c=="symbol"&&(D=void 0);function p(N){var U=(i[N]||"silent").toUpperCase();if(!(typeof window===e||!D)){try{window.localStorage[D]=U;return}catch{}try{window.document.cookie=encodeURIComponent(D)+"="+U+";"}catch{}}}function y(){var N;if(!(typeof window===e||!D)){try{N=window.localStorage[D]}catch{}if(typeof N===e)try{var U=window.document.cookie,K=encodeURIComponent(D),P=U.indexOf(K+"=");P!==-1&&(N=/^([^;]+)/.exec(U.slice(P+K.length+1))[1])}catch{}return r.levels[N]===void 0&&(N=void 0),N}}function k(){if(!(typeof window===e||!D)){try{window.localStorage.removeItem(D)}catch{}try{window.document.cookie=encodeURIComponent(D)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function x(N){var U=N;if(typeof U=="string"&&r.levels[U.toUpperCase()]!==void 0&&(U=r.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=r.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+N)}r.name=c,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=h||B,r.getLevel=function(){return l??_??f},r.setLevel=function(N,U){return l=x(N),U!==!1&&p(l),n.call(r)},r.setDefaultLevel=function(N){_=x(N),y()||r.setLevel(N,!1)},r.resetLevel=function(){l=null,k(),n.call(r)},r.enableAll=function(N){r.setLevel(r.levels.TRACE,N)},r.disableAll=function(N){r.setLevel(r.levels.SILENT,N)},r.rebuild=function(){if(C!==r&&(f=x(C.getLevel())),n.call(r),C===r)for(var N in I)I[N].rebuild()},f=x(C?C.getLevel():"WARN");var w=y();w!=null&&(l=x(w)),n.call(r)}C=new E,C.getLogger=function(h){if(typeof h!="symbol"&&typeof h!="string"||h==="")throw new TypeError("You must supply a name when creating a logger.");var r=I[h];return r||(r=I[h]=new E(h,C.methodFactory)),r};var d=typeof window!==e?window.log:void 0;return C.noConflict=function(){return typeof window!==e&&window.log===C&&(window.log=d),C},C.getLoggers=function(){return I},C.default=C,C})}(OC)),OC.exports}var VC=Rd(),Ra;(function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"})(Ra||(Ra={}));var vg;(function(t){t.Default="livekit",t.Room="livekit-room",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"})(vg||(vg={}));let $A=VC.getLogger("livekit");Object.values(vg).map(t=>VC.getLogger(t)),$A.setDefaultLevel(Ra.info);function lt(t){const A=VC.getLogger(t);return A.setDefaultLevel($A.getLevel()),A}const Gd=VC.getLogger("lk-e2ee"),VI=7e3,Md=[0,300,2*2*300,3*3*300,4*4*300,VI,VI,VI,VI,VI];class Fd{constructor(A){this._retryDelays=A!==void 0?[...A]:Md}nextRetryDelayInMs(A){if(A.retryCount>=this._retryDelays.length)return null;const e=this._retryDelays[A.retryCount];return A.retryCount<=1?e:e+Math.random()*1e3}}function Ud(t,A){var e={};for(var g in t)Object.prototype.hasOwnProperty.call(t,g)&&A.indexOf(g)<0&&(e[g]=t[g]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,g=Object.getOwnPropertySymbols(t);i<g.length;i++)A.indexOf(g[i])<0&&Object.prototype.propertyIsEnumerable.call(t,g[i])&&(e[g[i]]=t[g[i]]);return e}function S(t,A,e,g){function i(I){return I instanceof e?I:new e(function(C){C(I)})}return new(e||(e=Promise))(function(I,C){function o(n){try{Q(g.next(n))}catch(s){C(s)}}function a(n){try{Q(g.throw(n))}catch(s){C(s)}}function Q(n){n.done?I(n.value):i(n.value).then(o,a)}Q((g=g.apply(t,A||[])).next())})}function WB(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")}function ft(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var A=t[Symbol.asyncIterator],e;return A?A.call(t):(t=typeof WB=="function"?WB(t):t[Symbol.iterator](),e={},g("next"),g("throw"),g("return"),e[Symbol.asyncIterator]=function(){return this},e);function g(I){e[I]=t[I]&&function(C){return new Promise(function(o,a){C=t[I](C),i(o,a,C.done,C.value)})}}function i(I,C,o,a){Promise.resolve(a).then(function(Q){I({value:Q,done:o})},C)}}typeof SuppressedError=="function"&&SuppressedError;var jC={exports:{}},XB;function Ld(){if(XB)return jC.exports;XB=1;var t=typeof Reflect=="object"?Reflect:null,A=t&&typeof t.apply=="function"?t.apply:function(D,p,y){return Function.prototype.apply.call(D,p,y)},e;t&&typeof t.ownKeys=="function"?e=t.ownKeys:Object.getOwnPropertySymbols?e=function(D){return Object.getOwnPropertyNames(D).concat(Object.getOwnPropertySymbols(D))}:e=function(D){return Object.getOwnPropertyNames(D)};function g(l){console&&console.warn&&console.warn(l)}var i=Number.isNaN||function(D){return D!==D};function I(){I.init.call(this)}jC.exports=I,jC.exports.once=r,I.EventEmitter=I,I.prototype._events=void 0,I.prototype._eventsCount=0,I.prototype._maxListeners=void 0;var C=10;function o(l){if(typeof l!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof l)}Object.defineProperty(I,"defaultMaxListeners",{enumerable:!0,get:function(){return C},set:function(l){if(typeof l!="number"||l<0||i(l))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+l+".");C=l}}),I.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},I.prototype.setMaxListeners=function(D){if(typeof D!="number"||D<0||i(D))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+D+".");return this._maxListeners=D,this};function a(l){return l._maxListeners===void 0?I.defaultMaxListeners:l._maxListeners}I.prototype.getMaxListeners=function(){return a(this)},I.prototype.emit=function(D){for(var p=[],y=1;y<arguments.length;y++)p.push(arguments[y]);var k=D==="error",x=this._events;if(x!==void 0)k=k&&x.error===void 0;else if(!k)return!1;if(k){var w;if(p.length>0&&(w=p[0]),w instanceof Error)throw w;var N=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw N.context=w,N}var U=x[D];if(U===void 0)return!1;if(typeof U=="function")A(U,this,p);else for(var K=U.length,P=d(U,K),y=0;y<K;++y)A(P[y],this,p);return!0};function Q(l,D,p,y){var k,x,w;if(o(p),x=l._events,x===void 0?(x=l._events=Object.create(null),l._eventsCount=0):(x.newListener!==void 0&&(l.emit("newListener",D,p.listener?p.listener:p),x=l._events),w=x[D]),w===void 0)w=x[D]=p,++l._eventsCount;else if(typeof w=="function"?w=x[D]=y?[p,w]:[w,p]:y?w.unshift(p):w.push(p),k=a(l),k>0&&w.length>k&&!w.warned){w.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(D)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=l,N.type=D,N.count=w.length,g(N)}return l}I.prototype.addListener=function(D,p){return Q(this,D,p,!1)},I.prototype.on=I.prototype.addListener,I.prototype.prependListener=function(D,p){return Q(this,D,p,!0)};function n(){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 s(l,D,p){var y={fired:!1,wrapFn:void 0,target:l,type:D,listener:p},k=n.bind(y);return k.listener=p,y.wrapFn=k,k}I.prototype.once=function(D,p){return o(p),this.on(D,s(this,D,p)),this},I.prototype.prependOnceListener=function(D,p){return o(p),this.prependListener(D,s(this,D,p)),this},I.prototype.removeListener=function(D,p){var y,k,x,w,N;if(o(p),k=this._events,k===void 0)return this;if(y=k[D],y===void 0)return this;if(y===p||y.listener===p)--this._eventsCount===0?this._events=Object.create(null):(delete k[D],k.removeListener&&this.emit("removeListener",D,y.listener||p));else if(typeof y!="function"){for(x=-1,w=y.length-1;w>=0;w--)if(y[w]===p||y[w].listener===p){N=y[w].listener,x=w;break}if(x<0)return this;x===0?y.shift():c(y,x),y.length===1&&(k[D]=y[0]),k.removeListener!==void 0&&this.emit("removeListener",D,N||p)}return this},I.prototype.off=I.prototype.removeListener,I.prototype.removeAllListeners=function(D){var p,y,k;if(y=this._events,y===void 0)return this;if(y.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):y[D]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete y[D]),this;if(arguments.length===0){var x=Object.keys(y),w;for(k=0;k<x.length;++k)w=x[k],w!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(p=y[D],typeof p=="function")this.removeListener(D,p);else if(p!==void 0)for(k=p.length-1;k>=0;k--)this.removeListener(D,p[k]);return this};function B(l,D,p){var y=l._events;if(y===void 0)return[];var k=y[D];return k===void 0?[]:typeof k=="function"?p?[k.listener||k]:[k]:p?h(k):d(k,k.length)}I.prototype.listeners=function(D){return B(this,D,!0)},I.prototype.rawListeners=function(D){return B(this,D,!1)},I.listenerCount=function(l,D){return typeof l.listenerCount=="function"?l.listenerCount(D):E.call(l,D)},I.prototype.listenerCount=E;function E(l){var D=this._events;if(D!==void 0){var p=D[l];if(typeof p=="function")return 1;if(p!==void 0)return p.length}return 0}I.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]};function d(l,D){for(var p=new Array(D),y=0;y<D;++y)p[y]=l[y];return p}function c(l,D){for(;D+1<l.length;D++)l[D]=l[D+1];l.pop()}function h(l){for(var D=new Array(l.length),p=0;p<D.length;++p)D[p]=l[p].listener||l[p];return D}function r(l,D){return new Promise(function(p,y){function k(w){l.removeListener(D,x),y(w)}function x(){typeof l.removeListener=="function"&&l.removeListener("error",k),p([].slice.call(arguments))}_(l,D,x,{once:!0}),D!=="error"&&f(l,k,{once:!0})})}function f(l,D,p){typeof l.on=="function"&&_(l,"error",D,p)}function _(l,D,p,y){if(typeof l.on=="function")y.once?l.once(D,p):l.on(D,p);else if(typeof l.addEventListener=="function")l.addEventListener(D,function k(x){y.once&&l.removeEventListener(D,k),p(x)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof l)}return jC.exports}var At=Ld();let ZB=!0,zB=!0;function jI(t,A,e){const g=t.match(A);return g&&g.length>=e&&parseFloat(g[e],10)}function fi(t,A,e){if(!t.RTCPeerConnection)return;const g=t.RTCPeerConnection.prototype,i=g.addEventListener;g.addEventListener=function(C,o){if(C!==A)return i.apply(this,arguments);const a=Q=>{const n=e(Q);n&&(o.handleEvent?o.handleEvent(n):o(n))};return this._eventMap=this._eventMap||{},this._eventMap[A]||(this._eventMap[A]=new Map),this._eventMap[A].set(o,a),i.apply(this,[C,a])};const I=g.removeEventListener;g.removeEventListener=function(C,o){if(C!==A||!this._eventMap||!this._eventMap[A])return I.apply(this,arguments);if(!this._eventMap[A].has(o))return I.apply(this,arguments);const a=this._eventMap[A].get(o);return this._eventMap[A].delete(o),this._eventMap[A].size===0&&delete this._eventMap[A],Object.keys(this._eventMap).length===0&&delete this._eventMap,I.apply(this,[C,a])},Object.defineProperty(g,"on"+A,{get(){return this["_on"+A]},set(C){this["_on"+A]&&(this.removeEventListener(A,this["_on"+A]),delete this["_on"+A]),C&&this.addEventListener(A,this["_on"+A]=C)},enumerable:!0,configurable:!0})}function Kd(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(ZB=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function vd(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(zB=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function $B(){if(typeof window=="object"){if(ZB)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Ga(t,A){zB&&console.warn(t+" is deprecated, please use "+A+" instead.")}function Jd(t){const A={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return A.browser="Not a browser.",A;const{navigator:e}=t;if(e.userAgentData&&e.userAgentData.brands){const g=e.userAgentData.brands.find(i=>i.brand==="Chromium");if(g)return{browser:"chrome",version:parseInt(g.version,10)}}if(e.mozGetUserMedia)A.browser="firefox",A.version=parseInt(jI(e.userAgent,/Firefox\/(\d+)\./,1));else if(e.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)A.browser="chrome",A.version=parseInt(jI(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(t.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))A.browser="safari",A.version=parseInt(jI(e.userAgent,/AppleWebKit\/(\d+)\./,1)),A.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,A._safariVersion=jI(e.userAgent,/Version\/(\d+(\.?\d+))/,1);else return A.browser="Not a supported browser.",A;return A}function AE(t){return Object.prototype.toString.call(t)==="[object Object]"}function eE(t){return AE(t)?Object.keys(t).reduce(function(A,e){const g=AE(t[e]),i=g?eE(t[e]):t[e],I=g&&!Object.keys(i).length;return i===void 0||I?A:Object.assign(A,{[e]:i})},{}):t}function Ma(t,A,e){!A||e.has(A.id)||(e.set(A.id,A),Object.keys(A).forEach(g=>{g.endsWith("Id")?Ma(t,t.get(A[g]),e):g.endsWith("Ids")&&A[g].forEach(i=>{Ma(t,t.get(i),e)})}))}function gE(t,A,e){const g=e?"outbound-rtp":"inbound-rtp",i=new Map;if(A===null)return i;const I=[];return t.forEach(C=>{C.type==="track"&&C.trackIdentifier===A.id&&I.push(C)}),I.forEach(C=>{t.forEach(o=>{o.type===g&&o.trackId===C.id&&Ma(t,o,i)})}),i}const tE=$B;function iE(t,A){const e=t&&t.navigator;if(!e.mediaDevices)return;const g=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const a={};return Object.keys(o).forEach(Q=>{if(Q==="require"||Q==="advanced"||Q==="mediaSource")return;const n=typeof o[Q]=="object"?o[Q]:{ideal:o[Q]};n.exact!==void 0&&typeof n.exact=="number"&&(n.min=n.max=n.exact);const s=function(B,E){return B?B+E.charAt(0).toUpperCase()+E.slice(1):E==="deviceId"?"sourceId":E};if(n.ideal!==void 0){a.optional=a.optional||[];let B={};typeof n.ideal=="number"?(B[s("min",Q)]=n.ideal,a.optional.push(B),B={},B[s("max",Q)]=n.ideal,a.optional.push(B)):(B[s("",Q)]=n.ideal,a.optional.push(B))}n.exact!==void 0&&typeof n.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[s("",Q)]=n.exact):["min","max"].forEach(B=>{n[B]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[s(B,Q)]=n[B])})}),o.advanced&&(a.optional=(a.optional||[]).concat(o.advanced)),a},i=function(o,a){if(A.version>=61)return a(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const Q=function(n,s,B){s in n&&!(B in n)&&(n[B]=n[s],delete n[s])};o=JSON.parse(JSON.stringify(o)),Q(o.audio,"autoGainControl","googAutoGainControl"),Q(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=g(o.audio)}if(o&&typeof o.video=="object"){let Q=o.video.facingMode;Q=Q&&(typeof Q=="object"?Q:{ideal:Q});const n=A.version<66;if(Q&&(Q.exact==="user"||Q.exact==="environment"||Q.ideal==="user"||Q.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!n)){delete o.video.facingMode;let s;if(Q.exact==="environment"||Q.ideal==="environment"?s=["back","rear"]:(Q.exact==="user"||Q.ideal==="user")&&(s=["front"]),s)return e.mediaDevices.enumerateDevices().then(B=>{B=B.filter(d=>d.kind==="videoinput");let E=B.find(d=>s.some(c=>d.label.toLowerCase().includes(c)));return!E&&B.length&&s.includes("back")&&(E=B[B.length-1]),E&&(o.video.deviceId=Q.exact?{exact:E.deviceId}:{ideal:E.deviceId}),o.video=g(o.video),tE("chrome: "+JSON.stringify(o)),a(o)})}o.video=g(o.video)}return tE("chrome: "+JSON.stringify(o)),a(o)},I=function(o){return A.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},C=function(o,a,Q){i(o,n=>{e.webkitGetUserMedia(n,a,s=>{Q&&Q(I(s))})})};if(e.getUserMedia=C.bind(e),e.mediaDevices.getUserMedia){const o=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(a){return i(a,Q=>o(Q).then(n=>{if(Q.audio&&!n.getAudioTracks().length||Q.video&&!n.getVideoTracks().length)throw n.getTracks().forEach(s=>{s.stop()}),new DOMException("","NotFoundError");return n},n=>Promise.reject(I(n))))}}}function IE(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function CE(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const A=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=g=>{g.stream.addEventListener("addtrack",i=>{let I;t.RTCPeerConnection.prototype.getReceivers?I=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):I={track:i.track};const C=new Event("track");C.track=i.track,C.receiver=I,C.transceiver={receiver:I},C.streams=[g.stream],this.dispatchEvent(C)}),g.stream.getTracks().forEach(i=>{let I;t.RTCPeerConnection.prototype.getReceivers?I=this.getReceivers().find(o=>o.track&&o.track.id===i.id):I={track:i};const C=new Event("track");C.track=i,C.receiver=I,C.transceiver={receiver:I},C.streams=[g.stream],this.dispatchEvent(C)})},this.addEventListener("addstream",this._ontrackpoly)),A.apply(this,arguments)}}else fi(t,"track",A=>(A.transceiver||Object.defineProperty(A,"transceiver",{value:{receiver:A.receiver}}),A))}function oE(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const A=function(i,I){return{track:I,get dtmf(){return this._dtmf===void 0&&(I.kind==="audio"?this._dtmf=i.createDTMFSender(I):this._dtmf=null),this._dtmf},_pc:i}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,a){let Q=i.apply(this,arguments);return Q||(Q=A(this,o),this._senders.push(Q)),Q};const I=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){I.apply(this,arguments);const a=this._senders.indexOf(o);a!==-1&&this._senders.splice(a,1)}}const e=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(I){this._senders=this._senders||[],e.apply(this,[I]),I.getTracks().forEach(C=>{this._senders.push(A(this,C))})};const g=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(I){this._senders=this._senders||[],g.apply(this,[I]),I.getTracks().forEach(C=>{const o=this._senders.find(a=>a.track===C);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const A=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const g=A.apply(this,[]);return g.forEach(i=>i._pc=this),g},Object.defineProperty(t.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 aE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const I=e.apply(this,[]);return I.forEach(C=>C._pc=this),I});const g=t.RTCPeerConnection.prototype.addTrack;g&&(t.RTCPeerConnection.prototype.addTrack=function(){const I=g.apply(this,arguments);return I._pc=this,I}),t.RTCRtpSender.prototype.getStats=function(){const I=this;return this._pc.getStats().then(C=>gE(C,I.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(I=>I._pc=this),i}),fi(t,"track",g=>(g.receiver._pc=g.srcElement,g)),t.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(I=>gE(I,i.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;const A=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const g=arguments[0];let i,I,C;return this.getSenders().forEach(o=>{o.track===g&&(i?C=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===g&&(I?C=!0:I=o),o.track===g)),C||i&&I?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():I?I.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return A.apply(this,arguments)}}function QE(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(C=>this._shimmedLocalStreams[C][0])};const A=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(C,o){if(!o)return A.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=A.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(a)===-1&&this._shimmedLocalStreams[o.id].push(a):this._shimmedLocalStreams[o.id]=[o,a],a};const e=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(C){this._shimmedLocalStreams=this._shimmedLocalStreams||{},C.getTracks().forEach(Q=>{if(this.getSenders().find(s=>s.track===Q))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();e.apply(this,arguments);const a=this.getSenders().filter(Q=>o.indexOf(Q)===-1);this._shimmedLocalStreams[C.id]=[C].concat(a)};const g=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[C.id],g.apply(this,arguments)};const i=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},C&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const a=this._shimmedLocalStreams[o].indexOf(C);a!==-1&&this._shimmedLocalStreams[o].splice(a,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function nE(t,A){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&A.version>=65)return QE(t);const e=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const n=e.apply(this);return this._reverseStreams=this._reverseStreams||{},n.map(s=>this._reverseStreams[s.id])};const g=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(n){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.getTracks().forEach(s=>{if(this.getSenders().find(E=>E.track===s))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[n.id]){const s=new t.MediaStream(n.getTracks());this._streams[n.id]=s,this._reverseStreams[s.id]=n,n=s}g.apply(this,[n])};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(n){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[n.id]||n]),delete this._reverseStreams[this._streams[n.id]?this._streams[n.id].id:n.id],delete this._streams[n.id]},t.RTCPeerConnection.prototype.addTrack=function(n,s){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const B=[].slice.call(arguments,1);if(B.length!==1||!B[0].getTracks().find(c=>c===n))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(c=>c.track===n))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const d=this._streams[s.id];if(d)d.addTrack(n),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const c=new t.MediaStream([n]);this._streams[s.id]=c,this._reverseStreams[c.id]=s,this.addStream(c)}return this.getSenders().find(c=>c.track===n)};function I(Q,n){let s=n.sdp;return Object.keys(Q._reverseStreams||[]).forEach(B=>{const E=Q._reverseStreams[B],d=Q._streams[E.id];s=s.replace(new RegExp(d.id,"g"),E.id)}),new RTCSessionDescription({type:n.type,sdp:s})}function C(Q,n){let s=n.sdp;return Object.keys(Q._reverseStreams||[]).forEach(B=>{const E=Q._reverseStreams[B],d=Q._streams[E.id];s=s.replace(new RegExp(E.id,"g"),d.id)}),new RTCSessionDescription({type:n.type,sdp:s})}["createOffer","createAnswer"].forEach(function(Q){const n=t.RTCPeerConnection.prototype[Q],s={[Q](){const B=arguments;return arguments.length&&typeof arguments[0]=="function"?n.apply(this,[d=>{const c=I(this,d);B[0].apply(null,[c])},d=>{B[1]&&B[1].apply(null,d)},arguments[2]]):n.apply(this,arguments).then(d=>I(this,d))}};t.RTCPeerConnection.prototype[Q]=s[Q]});const o=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=C(this,arguments[0]),o.apply(this,arguments))};const a=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const Q=a.get.apply(this);return Q.type===""?Q:I(this,Q)}}),t.RTCPeerConnection.prototype.removeTrack=function(n){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!n._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(n._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let B;Object.keys(this._streams).forEach(E=>{this._streams[E].getTracks().find(c=>n.track===c)&&(B=this._streams[E])}),B&&(B.getTracks().length===1?this.removeStream(this._reverseStreams[B.id]):B.removeTrack(n.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Fa(t,A){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){const g=t.RTCPeerConnection.prototype[e],i={[e](){return arguments[0]=new(e==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),g.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=i[e]})}function sE(t,A){fi(t,"negotiationneeded",e=>{const g=e.target;if(!((A.version<72||g.getConfiguration&&g.getConfiguration().sdpSemantics==="plan-b")&&g.signalingState!=="stable"))return e})}var BE=Object.freeze({__proto__:null,fixNegotiationNeeded:sE,shimAddTrackRemoveTrack:nE,shimAddTrackRemoveTrackWithNative:QE,shimGetSendersWithDtmf:oE,shimGetUserMedia:iE,shimMediaStream:IE,shimOnTrack:CE,shimPeerConnection:Fa,shimSenderReceiverGetStats:aE});function EE(t,A){const e=t&&t.navigator,g=t&&t.MediaStreamTrack;if(e.getUserMedia=function(i,I,C){Ga("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(i).then(I,C)},!(A.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){const i=function(C,o,a){o in C&&!(a in C)&&(C[a]=C[o],delete C[o])},I=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(C){return typeof C=="object"&&typeof C.audio=="object"&&(C=JSON.parse(JSON.stringify(C)),i(C.audio,"autoGainControl","mozAutoGainControl"),i(C.audio,"noiseSuppression","mozNoiseSuppression")),I(C)},g&&g.prototype.getSettings){const C=g.prototype.getSettings;g.prototype.getSettings=function(){const o=C.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(g&&g.prototype.applyConstraints){const C=g.prototype.applyConstraints;g.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),C.apply(this,[o])}}}}function Yd(t,A){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(g){if(!(g&&g.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return g.video===!0?g.video={mediaSource:A}:g.video.mediaSource=A,t.navigator.mediaDevices.getUserMedia(g)})}function rE(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ua(t,A){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const I=t.RTCPeerConnection.prototype[i],C={[i](){return arguments[0]=new(i==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)}};t.RTCPeerConnection.prototype[i]=C[i]});const e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},g=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[I,C,o]=arguments;return g.apply(this,[I||null]).then(a=>{if(A.version<53&&!C)try{a.forEach(Q=>{Q.type=e[Q.type]||Q.type})}catch(Q){if(Q.name!=="TypeError")throw Q;a.forEach((n,s)=>{a.set(s,Object.assign({},n,{type:e[n.type]||n.type}))})}return a}).then(C,o)}}function cE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const A=t.RTCPeerConnection.prototype.getSenders;A&&(t.RTCPeerConnection.prototype.getSenders=function(){const i=A.apply(this,[]);return i.forEach(I=>I._pc=this),i});const e=t.RTCPeerConnection.prototype.addTrack;e&&(t.RTCPeerConnection.prototype.addTrack=function(){const i=e.apply(this,arguments);return i._pc=this,i}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function hE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const A=t.RTCPeerConnection.prototype.getReceivers;A&&(t.RTCPeerConnection.prototype.getReceivers=function(){const g=A.apply(this,[]);return g.forEach(i=>i._pc=this),g}),fi(t,"track",e=>(e.receiver._pc=e.srcElement,e)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function dE(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(e){Ga("removeStream","removeTrack"),this.getSenders().forEach(g=>{g.track&&e.getTracks().includes(g.track)&&this.removeTrack(g)})})}function xE(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function lE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.addTransceiver;A&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let g=arguments[1]&&arguments[1].sendEncodings;g===void 0&&(g=[]),g=[...g];const i=g.length>0;i&&g.forEach(C=>{if("rid"in C&&!/^[a-z0-9]{0,16}$/i.test(C.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in C&&!(parseFloat(C.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in C&&!(parseFloat(C.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const I=A.apply(this,arguments);if(i){const{sender:C}=I,o=C.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=g,C.sendEncodings=g,this.setParametersPromises.push(C.setParameters(o).then(()=>{delete C.sendEncodings}).catch(()=>{delete C.sendEncodings})))}return I})}function fE(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;const A=t.RTCRtpSender.prototype.getParameters;A&&(t.RTCRtpSender.prototype.getParameters=function(){const g=A.apply(this,arguments);return"encodings"in g||(g.encodings=[].concat(this.sendEncodings||[{}])),g})}function uE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}function DE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}var _E=Object.freeze({__proto__:null,shimAddTransceiver:lE,shimCreateAnswer:DE,shimCreateOffer:uE,shimGetDisplayMedia:Yd,shimGetParameters:fE,shimGetUserMedia:EE,shimOnTrack:rE,shimPeerConnection:Ua,shimRTCDataChannel:xE,shimReceiverGetStats:hE,shimRemoveStream:dE,shimSenderGetStats:cE});function wE(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const A=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(g){this._localStreams||(this._localStreams=[]),this._localStreams.includes(g)||this._localStreams.push(g),g.getAudioTracks().forEach(i=>A.call(this,i,g)),g.getVideoTracks().forEach(i=>A.call(this,i,g))},t.RTCPeerConnection.prototype.addTrack=function(g){for(var i=arguments.length,I=new Array(i>1?i-1:0),C=1;C<i;C++)I[C-1]=arguments[C];return I&&I.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),A.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const g=this._localStreams.indexOf(e);if(g===-1)return;this._localStreams.splice(g,1);const i=e.getTracks();this.getSenders().forEach(I=>{i.includes(I.track)&&this.removeTrack(I)})})}}function pE(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=g=>{g.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const I=new Event("addstream");I.stream=i,this.dispatchEvent(I)})})}});const A=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const g=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(I=>{if(g._remoteStreams||(g._remoteStreams=[]),g._remoteStreams.indexOf(I)>=0)return;g._remoteStreams.push(I);const C=new Event("addstream");C.stream=I,g.dispatchEvent(C)})}),A.apply(g,arguments)}}}function mE(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const A=t.RTCPeerConnection.prototype,e=A.createOffer,g=A.createAnswer,i=A.setLocalDescription,I=A.setRemoteDescription,C=A.addIceCandidate;A.createOffer=function(Q,n){const s=arguments.length>=2?arguments[2]:arguments[0],B=e.apply(this,[s]);return n?(B.then(Q,n),Promise.resolve()):B},A.createAnswer=function(Q,n){const s=arguments.length>=2?arguments[2]:arguments[0],B=g.apply(this,[s]);return n?(B.then(Q,n),Promise.resolve()):B};let o=function(a,Q,n){const s=i.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s};A.setLocalDescription=o,o=function(a,Q,n){const s=I.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s},A.setRemoteDescription=o,o=function(a,Q,n){const s=C.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s},A.addIceCandidate=o}function yE(t){const A=t&&t.navigator;if(A.mediaDevices&&A.mediaDevices.getUserMedia){const e=A.mediaDevices,g=e.getUserMedia.bind(e);A.mediaDevices.getUserMedia=i=>g(bE(i))}!A.getUserMedia&&A.mediaDevices&&A.mediaDevices.getUserMedia&&(A.getUserMedia=(function(g,i,I){A.mediaDevices.getUserMedia(g).then(i,I)}).bind(A))}function bE(t){return t&&t.video!==void 0?Object.assign({},t,{video:eE(t.video)}):t}function NE(t){if(!t.RTCPeerConnection)return;const A=t.RTCPeerConnection;t.RTCPeerConnection=function(g,i){if(g&&g.iceServers){const I=[];for(let C=0;C<g.iceServers.length;C++){let o=g.iceServers[C];o.urls===void 0&&o.url?(Ga("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,I.push(o)):I.push(g.iceServers[C])}g.iceServers=I}return new A(g,i)},t.RTCPeerConnection.prototype=A.prototype,"generateCertificate"in A&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return A.generateCertificate}})}function SE(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function kE(t){const A=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(g){if(g){typeof g.offerToReceiveAudio<"u"&&(g.offerToReceiveAudio=!!g.offerToReceiveAudio);const i=this.getTransceivers().find(C=>C.receiver.track.kind==="audio");g.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):g.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof g.offerToReceiveVideo<"u"&&(g.offerToReceiveVideo=!!g.offerToReceiveVideo);const I=this.getTransceivers().find(C=>C.receiver.track.kind==="video");g.offerToReceiveVideo===!1&&I?I.direction==="sendrecv"?I.setDirection?I.setDirection("sendonly"):I.direction="sendonly":I.direction==="recvonly"&&(I.setDirection?I.setDirection("inactive"):I.direction="inactive"):g.offerToReceiveVideo===!0&&!I&&this.addTransceiver("video",{direction:"recvonly"})}return A.apply(this,arguments)}}function RE(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var GE=Object.freeze({__proto__:null,shimAudioContext:RE,shimCallbacksAPI:mE,shimConstraints:bE,shimCreateOfferLegacy:kE,shimGetUserMedia:yE,shimLocalStreamsAPI:wE,shimRTCIceServerUrls:NE,shimRemoteStreamsAPI:pE,shimTrackEventTransceiver:SE}),La={exports:{}},ME;function Td(){return ME||(ME=1,function(t){const A={};A.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},A.localCName=A.generateIdentifier(),A.splitLines=function(e){return e.trim().split(`
|
|
47
|
+
*/const kC=()=>new eh;let eh=class{};const sa=new WeakMap,RC=Wc(class extends Ah{render(t){return ke}update(t,[A]){var g;const e=A!==this.Y;return e&&this.Y!==void 0&&this.rt(void 0),(e||this.lt!==this.ct)&&(this.Y=A,this.ht=(g=t.options)==null?void 0:g.host,this.rt(this.ct=t.element)),ke}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const A=this.ht??globalThis;let e=sa.get(A);e===void 0&&(e=new WeakMap,sa.set(A,e)),e.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),e.set(this.Y,t),t!==void 0&&this.Y.call(this.ht,t)}else this.Y.value=t}get lt(){var t,A;return typeof this.Y=="function"?(t=sa.get(this.ht??globalThis))==null?void 0:t.get(this.Y):(A=this.Y)==null?void 0:A.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function gh(t,A){return A.forEach(function(e){e&&typeof e!="string"&&!Array.isArray(e)&&Object.keys(e).forEach(function(g){if(g!=="default"&&!(g in t)){var i=Object.getOwnPropertyDescriptor(e,g);Object.defineProperty(t,g,i.get?i:{enumerable:!0,get:function(){return e[g]}})}})}),Object.freeze(t)}var th=Object.defineProperty,ih=(t,A,e)=>A in t?th(t,A,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[A]=e,Ys=(t,A,e)=>ih(t,typeof A!="symbol"?A+"":A,e);let sg=class{constructor(){Ys(this,"_locking"),Ys(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let A;const e=new Promise(i=>A=()=>{this._locks-=1,i()}),g=this._locking.then(()=>A);return this._locking=this._locking.then(()=>e),g}};function Re(t,A){if(!t)throw new Error(A)}const Ih=34028234663852886e22,Ch=-34028234663852886e22,oh=4294967295,ah=2147483647,Qh=-2147483648;function GC(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>ah||t<Qh)throw new Error("invalid int 32: "+t)}function Ba(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>oh||t<0)throw new Error("invalid uint 32: "+t)}function Ts(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>Ih||t<Ch))throw new Error("invalid float 32: "+t)}const qs=Symbol("@bufbuild/protobuf/enum-type");function nh(t){const A=t[qs];return Re(A,"missing enum type on enum object"),A}function Hs(t,A,e,g){t[qs]=Ps(A,e.map(i=>({no:i.no,name:i.name,localName:t[i.no]})))}function Ps(t,A,e){const g=Object.create(null),i=Object.create(null),I=[];for(const C of A){const o=Os(C);I.push(o),g[C.name]=o,i[C.no]=o}return{typeName:t,values:I,findName(C){return g[C]},findNumber(C){return i[C]}}}function sh(t,A,e){const g={};for(const i of A){const I=Os(i);g[I.localName]=I.no,g[I.no]=I.localName}return Hs(g,t,A),g}function Os(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class Ea{equals(A){return this.getType().runtime.util.equals(this.getType(),this,A)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(A,e){const g=this.getType(),i=g.runtime.bin,I=i.makeReadOptions(e);return i.readMessage(this,I.readerFactory(A),A.byteLength,I),this}fromJson(A,e){const g=this.getType(),i=g.runtime.json,I=i.makeReadOptions(e);return i.readMessage(g,A,I,this),this}fromJsonString(A,e){let g;try{g=JSON.parse(A)}catch(i){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(i instanceof Error?i.message:String(i)))}return this.fromJson(g,e)}toBinary(A){const e=this.getType(),g=e.runtime.bin,i=g.makeWriteOptions(A),I=i.writerFactory();return g.writeMessage(this,I,i),I.finish()}toJson(A){const e=this.getType(),g=e.runtime.json,i=g.makeWriteOptions(A);return g.writeMessage(this,i)}toJsonString(A){var e;const g=this.toJson(A);return JSON.stringify(g,null,(e=A==null?void 0:A.prettySpaces)!==null&&e!==void 0?e:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Bh(t,A,e,g){var i;const I=(i=g==null?void 0:g.localName)!==null&&i!==void 0?i:A.substring(A.lastIndexOf(".")+1),C={[I]:function(o){t.util.initFields(this),t.util.initPartial(o,this)}}[I];return Object.setPrototypeOf(C.prototype,new Ea),Object.assign(C,{runtime:t,typeName:A,fields:t.util.newFieldList(e),fromBinary(o,a){return new C().fromBinary(o,a)},fromJson(o,a){return new C().fromJson(o,a)},fromJsonString(o,a){return new C().fromJsonString(o,a)},equals(o,a){return t.util.equals(C,o,a)}}),C}function Eh(){let t=0,A=0;for(let g=0;g<28;g+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<g,(i&128)==0)return this.assertBounds(),[t,A]}let e=this.buf[this.pos++];if(t|=(e&15)<<28,A=(e&112)>>4,(e&128)==0)return this.assertBounds(),[t,A];for(let g=3;g<=31;g+=7){let i=this.buf[this.pos++];if(A|=(i&127)<<g,(i&128)==0)return this.assertBounds(),[t,A]}throw new Error("invalid varint")}function ra(t,A,e){for(let I=0;I<28;I=I+7){const C=t>>>I,o=!(!(C>>>7)&&A==0),a=(o?C|128:C)&255;if(e.push(a),!o)return}const g=t>>>28&15|(A&7)<<4,i=A>>3!=0;if(e.push((i?g|128:g)&255),!!i){for(let I=3;I<31;I=I+7){const C=A>>>I,o=!!(C>>>7),a=(o?C|128:C)&255;if(e.push(a),!o)return}e.push(A>>>31&1)}}const MC=4294967296;function Vs(t){const A=t[0]==="-";A&&(t=t.slice(1));const e=1e6;let g=0,i=0;function I(C,o){const a=Number(t.slice(C,o));i*=e,g=g*e+a,g>=MC&&(i=i+(g/MC|0),g=g%MC)}return I(-24,-18),I(-18,-12),I(-12,-6),I(-6),A?Ws(g,i):ca(g,i)}function rh(t,A){let e=ca(t,A);const g=e.hi&2147483648;g&&(e=Ws(e.lo,e.hi));const i=js(e.lo,e.hi);return g?"-"+i:i}function js(t,A){if({lo:t,hi:A}=ch(t,A),A<=2097151)return String(MC*A+t);const e=t&16777215,g=(t>>>24|A<<8)&16777215,i=A>>16&65535;let I=e+g*6777216+i*6710656,C=g+i*8147497,o=i*2;const a=1e7;return I>=a&&(C+=Math.floor(I/a),I%=a),C>=a&&(o+=Math.floor(C/a),C%=a),o.toString()+Xs(C)+Xs(I)}function ch(t,A){return{lo:t>>>0,hi:A>>>0}}function ca(t,A){return{lo:t|0,hi:A|0}}function Ws(t,A){return A=~A,t?t=~t+1:A+=1,ca(t,A)}const Xs=t=>{const A=String(t);return"0000000".slice(A.length)+A};function Zs(t,A){if(t>=0){for(;t>127;)A.push(t&127|128),t=t>>>7;A.push(t)}else{for(let e=0;e<9;e++)A.push(t&127|128),t=t>>7;A.push(1)}}function hh(){let t=this.buf[this.pos++],A=t&127;if((t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<7,(t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<14,(t&128)==0)return this.assertBounds(),A;if(t=this.buf[this.pos++],A|=(t&127)<<21,(t&128)==0)return this.assertBounds(),A;t=this.buf[this.pos++],A|=(t&15)<<28;for(let e=5;(t&128)!==0&&e<10;e++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),A>>>0}function dh(){const t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const i=BigInt("-9223372036854775808"),I=BigInt("9223372036854775807"),C=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(a){const Q=typeof a=="bigint"?a:BigInt(a);if(Q>I||Q<i)throw new Error("int64 invalid: ".concat(a));return Q},uParse(a){const Q=typeof a=="bigint"?a:BigInt(a);if(Q>o||Q<C)throw new Error("uint64 invalid: ".concat(a));return Q},enc(a){return t.setBigInt64(0,this.parse(a),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(a){return t.setBigInt64(0,this.uParse(a),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(a,Q){return t.setInt32(0,a,!0),t.setInt32(4,Q,!0),t.getBigInt64(0,!0)},uDec(a,Q){return t.setInt32(0,a,!0),t.setInt32(4,Q,!0),t.getBigUint64(0,!0)}}}const e=i=>Re(/^-?[0-9]+$/.test(i),"int64 invalid: ".concat(i)),g=i=>Re(/^[0-9]+$/.test(i),"uint64 invalid: ".concat(i));return{zero:"0",supported:!1,parse(i){return typeof i!="string"&&(i=i.toString()),e(i),i},uParse(i){return typeof i!="string"&&(i=i.toString()),g(i),i},enc(i){return typeof i!="string"&&(i=i.toString()),e(i),Vs(i)},uEnc(i){return typeof i!="string"&&(i=i.toString()),g(i),Vs(i)},dec(i,I){return rh(i,I)},uDec(i,I){return js(i,I)}}}const Ne=dh();var $;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})($||($={}));var Pt;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"})(Pt||(Pt={}));function Ot(t,A,e){if(A===e)return!0;if(t==$.BYTES){if(!(A instanceof Uint8Array)||!(e instanceof Uint8Array)||A.length!==e.length)return!1;for(let g=0;g<A.length;g++)if(A[g]!==e[g])return!1;return!0}switch(t){case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return A==e}return!1}function Vi(t,A){switch(t){case $.BOOL:return!1;case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return A==0?Ne.zero:"0";case $.DOUBLE:case $.FLOAT:return 0;case $.BYTES:return new Uint8Array(0);case $.STRING:return"";default:return 0}}function zs(t,A){switch(t){case $.BOOL:return A===!1;case $.STRING:return A==="";case $.BYTES:return A instanceof Uint8Array&&!A.byteLength;default:return A==0}}var Le;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(Le||(Le={}));class xh{constructor(A){this.stack=[],this.textEncoder=A??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let A=0;for(let i=0;i<this.chunks.length;i++)A+=this.chunks[i].length;let e=new Uint8Array(A),g=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],g),g+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let A=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(A.byteLength),this.raw(A)}tag(A,e){return this.uint32((A<<3|e)>>>0)}raw(A){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(A),this}uint32(A){for(Ba(A);A>127;)this.buf.push(A&127|128),A=A>>>7;return this.buf.push(A),this}int32(A){return GC(A),Zs(A,this.buf),this}bool(A){return this.buf.push(A?1:0),this}bytes(A){return this.uint32(A.byteLength),this.raw(A)}string(A){let e=this.textEncoder.encode(A);return this.uint32(e.byteLength),this.raw(e)}float(A){Ts(A);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,A,!0),this.raw(e)}double(A){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,A,!0),this.raw(e)}fixed32(A){Ba(A);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,A,!0),this.raw(e)}sfixed32(A){GC(A);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,A,!0),this.raw(e)}sint32(A){return GC(A),A=(A<<1^A>>31)>>>0,Zs(A,this.buf),this}sfixed64(A){let e=new Uint8Array(8),g=new DataView(e.buffer),i=Ne.enc(A);return g.setInt32(0,i.lo,!0),g.setInt32(4,i.hi,!0),this.raw(e)}fixed64(A){let e=new Uint8Array(8),g=new DataView(e.buffer),i=Ne.uEnc(A);return g.setInt32(0,i.lo,!0),g.setInt32(4,i.hi,!0),this.raw(e)}int64(A){let e=Ne.enc(A);return ra(e.lo,e.hi,this.buf),this}sint64(A){let e=Ne.enc(A),g=e.hi>>31,i=e.lo<<1^g,I=(e.hi<<1|e.lo>>>31)^g;return ra(i,I,this.buf),this}uint64(A){let e=Ne.uEnc(A);return ra(e.lo,e.hi,this.buf),this}}class lh{constructor(A,e){this.varint64=Eh,this.uint32=hh,this.buf=A,this.len=A.length,this.pos=0,this.view=new DataView(A.buffer,A.byteOffset,A.byteLength),this.textDecoder=e??new TextDecoder}tag(){let A=this.uint32(),e=A>>>3,g=A&7;if(e<=0||g<0||g>5)throw new Error("illegal tag: field no "+e+" wire type "+g);return[e,g]}skip(A,e){let g=this.pos;switch(A){case Le.Varint:for(;this.buf[this.pos++]&128;);break;case Le.Bit64:this.pos+=4;case Le.Bit32:this.pos+=4;break;case Le.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Le.StartGroup:for(;;){const[I,C]=this.tag();if(C===Le.EndGroup){if(e!==void 0&&I!==e)throw new Error("invalid end group tag");break}this.skip(C,I)}break;default:throw new Error("cant skip wire type "+A)}return this.assertBounds(),this.buf.subarray(g,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let A=this.uint32();return A>>>1^-(A&1)}int64(){return Ne.dec(...this.varint64())}uint64(){return Ne.uDec(...this.varint64())}sint64(){let[A,e]=this.varint64(),g=-(A&1);return A=(A>>>1|(e&1)<<31)^g,e=e>>>1^g,Ne.dec(A,e)}bool(){let[A,e]=this.varint64();return A!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ne.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ne.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 A=this.uint32(),e=this.pos;return this.pos+=A,this.assertBounds(),this.buf.subarray(e,e+A)}string(){return this.textDecoder.decode(this.bytes())}}function fh(t,A,e,g){let i;return{typeName:A,extendee:e,get field(){if(!i){const I=typeof g=="function"?g():g;I.name=A.split(".").pop(),I.jsonName="[".concat(A,"]"),i=t.util.newFieldList([I]).list()[0]}return i},runtime:t}}function $s(t){const A=t.field.localName,e=Object.create(null);return e[A]=uh(t),[e,()=>e[A]]}function uh(t){const A=t.field;if(A.repeated)return[];if(A.default!==void 0)return A.default;switch(A.kind){case"enum":return A.T.values[0].no;case"scalar":return Vi(A.T,A.L);case"message":const e=A.T,g=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(g):g;case"map":throw"map fields are not allowed to be extensions"}}function Dh(t,A){if(!A.repeated&&(A.kind=="enum"||A.kind=="scalar")){for(let e=t.length-1;e>=0;--e)if(t[e].no==A.no)return[t[e]];return[]}return t.filter(e=>e.no===A.no)}let dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),FC=[];for(let t=0;t<dt.length;t++)FC[dt[t].charCodeAt(0)]=t;FC[45]=dt.indexOf("+"),FC[95]=dt.indexOf("/");const AB={dec(t){let A=t.length*3/4;t[t.length-2]=="="?A-=2:t[t.length-1]=="="&&(A-=1);let e=new Uint8Array(A),g=0,i=0,I,C=0;for(let o=0;o<t.length;o++){if(I=FC[t.charCodeAt(o)],I===void 0)switch(t[o]){case"=":i=0;case`
|
|
48
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:C=I,i=1;break;case 1:e[g++]=C<<2|(I&48)>>4,C=I,i=2;break;case 2:e[g++]=(C&15)<<4|(I&60)>>2,C=I,i=3;break;case 3:e[g++]=(C&3)<<6|I,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,g)},enc(t){let A="",e=0,g,i=0;for(let I=0;I<t.length;I++)switch(g=t[I],e){case 0:A+=dt[g>>2],i=(g&3)<<4,e=1;break;case 1:A+=dt[i|g>>4],i=(g&15)<<2,e=2;break;case 2:A+=dt[i|g>>6],A+=dt[g&63],e=0;break}return e&&(A+=dt[i],A+="=",e==1&&(A+="=")),A}};function _h(t,A,e){gB(A,t);const g=A.runtime.bin.makeReadOptions(e),i=Dh(t.getType().runtime.bin.listUnknownFields(t),A.field),[I,C]=$s(A);for(const o of i)A.runtime.bin.readField(I,g.readerFactory(o.data),A.field,o.wireType,g);return C()}function wh(t,A,e,g){gB(A,t);const i=A.runtime.bin.makeReadOptions(g),I=A.runtime.bin.makeWriteOptions(g);if(eB(t,A)){const Q=t.getType().runtime.bin.listUnknownFields(t).filter(n=>n.no!=A.field.no);t.getType().runtime.bin.discardUnknownFields(t);for(const n of Q)t.getType().runtime.bin.onUnknownField(t,n.no,n.wireType,n.data)}const C=I.writerFactory();let o=A.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},A.field),{opt:!0})),A.runtime.bin.writeField(o,e,C,I);const a=i.readerFactory(C.finish());for(;a.pos<a.len;){const[Q,n]=a.tag(),s=a.skip(n,Q);t.getType().runtime.bin.onUnknownField(t,Q,n,s)}}function eB(t,A){const e=t.getType();return A.extendee.typeName===e.typeName&&!!e.runtime.bin.listUnknownFields(t).find(g=>g.no==A.field.no)}function gB(t,A){Re(t.extendee.typeName==A.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function tB(t,A){const e=t.localName;if(t.repeated)return A[e].length>0;if(t.oneof)return A[t.oneof.localName].case===e;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?A[e]!==void 0:t.kind=="enum"?A[e]!==t.T.values[0].no:!zs(t.T,A[e]);case"message":return A[e]!==void 0;case"map":return Object.keys(A[e]).length>0}}function iB(t,A){const e=t.localName,g=!t.opt&&!t.req;if(t.repeated)A[e]=[];else if(t.oneof)A[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":A[e]={};break;case"enum":A[e]=g?t.T.values[0].no:void 0;break;case"scalar":A[e]=g?Vi(t.T,t.L):void 0;break;case"message":A[e]=void 0;break}}function xt(t,A){if(t===null||typeof t!="object"||!Object.getOwnPropertyNames(Ea.prototype).every(g=>g in t&&typeof t[g]=="function"))return!1;const e=t.getType();return e===null||typeof e!="function"||!("typeName"in e)||typeof e.typeName!="string"?!1:A===void 0?!0:e.typeName==A.typeName}function IB(t,A){return xt(A)||!t.fieldWrapper?A:t.fieldWrapper.wrapField(A)}$.DOUBLE,$.FLOAT,$.INT64,$.UINT64,$.INT32,$.UINT32,$.BOOL,$.STRING,$.BYTES;const CB={ignoreUnknownFields:!1},oB={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ph(t){return t?Object.assign(Object.assign({},CB),t):CB}function mh(t){return t?Object.assign(Object.assign({},oB),t):oB}const UC=Symbol(),LC=Symbol();function yh(){return{makeReadOptions:ph,makeWriteOptions:mh,readMessage(t,A,e,g){if(A==null||Array.isArray(A)||typeof A!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(zg(A)));g=g??new t;const i=new Map,I=e.typeRegistry;for(const[C,o]of Object.entries(A)){const a=t.fields.findJsonName(C);if(a){if(a.oneof){if(o===null&&a.kind=="scalar")continue;const Q=i.get(a.oneof);if(Q!==void 0)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(a.oneof.name,'" present: "').concat(Q,'", "').concat(C,'"'));i.set(a.oneof,C)}aB(g,o,a,e,t)}else{let Q=!1;if(I!=null&&I.findExtension&&C.startsWith("[")&&C.endsWith("]")){const n=I.findExtension(C.substring(1,C.length-1));if(n&&n.extendee.typeName==t.typeName){Q=!0;const[s,B]=$s(n);aB(s,o,n.field,e,n),wh(g,n,B(),e)}}if(!Q&&!e.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(C,'" is unknown'))}}return g},writeMessage(t,A){const e=t.getType(),g={};let i;try{for(i of e.fields.byNumber()){if(!tB(i,t)){if(i.req)throw"required field not set";if(!A.emitDefaultValues||!Nh(i))continue}const C=i.oneof?t[i.oneof.localName].value:t[i.localName],o=QB(i,C,A);o!==void 0&&(g[A.useProtoFieldName?i.name:i.jsonName]=o)}const I=A.typeRegistry;if(I!=null&&I.findExtensionFor)for(const C of e.runtime.bin.listUnknownFields(t)){const o=I.findExtensionFor(e.typeName,C.no);if(o&&eB(t,o)){const a=_h(t,o,A),Q=QB(o.field,a,A);Q!==void 0&&(g[o.field.jsonName]=Q)}}}catch(I){const C=i?"cannot encode field ".concat(e.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(e.typeName," to JSON"),o=I instanceof Error?I.message:String(I);throw new Error(C+(o.length>0?": ".concat(o):""))}return g},readScalar(t,A,e){return YI(t,A,e??Pt.BIGINT,!0)},writeScalar(t,A,e){if(A!==void 0&&(e||zs(t,A)))return KC(t,A)},debug:zg}}function zg(t){if(t===null)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return String(t)}}function aB(t,A,e,g,i){let I=e.localName;if(e.repeated){if(Re(e.kind!="map"),A===null)return;if(!Array.isArray(A))throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A)));const C=t[I];for(const o of A){if(o===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(o)));switch(e.kind){case"message":C.push(e.T.fromJson(o,g));break;case"enum":const a=ha(e.T,o,g.ignoreUnknownFields,!0);a!==LC&&C.push(a);break;case"scalar":try{C.push(YI(e.T,o,e.L,!0))}catch(Q){let n="cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(o));throw Q instanceof Error&&Q.message.length>0&&(n+=": ".concat(Q.message)),new Error(n)}break}}}else if(e.kind=="map"){if(A===null)return;if(typeof A!="object"||Array.isArray(A))throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A)));const C=t[I];for(const[o,a]of Object.entries(A)){if(a===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: map value null"));let Q;try{Q=bh(e.K,o)}catch(n){let s="cannot decode map key for field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw n instanceof Error&&n.message.length>0&&(s+=": ".concat(n.message)),new Error(s)}switch(e.V.kind){case"message":C[Q]=e.V.T.fromJson(a,g);break;case"enum":const n=ha(e.V.T,a,g.ignoreUnknownFields,!0);n!==LC&&(C[Q]=n);break;case"scalar":try{C[Q]=YI(e.V.T,a,Pt.BIGINT,!0)}catch(s){let B="cannot decode map value for field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw s instanceof Error&&s.message.length>0&&(B+=": ".concat(s.message)),new Error(B)}break}}}else switch(e.oneof&&(t=t[e.oneof.localName]={case:I},I="value"),e.kind){case"message":const C=e.T;if(A===null&&C.typeName!="google.protobuf.Value")return;let o=t[I];xt(o)?o.fromJson(A,g):(t[I]=o=C.fromJson(A,g),C.fieldWrapper&&!e.oneof&&(t[I]=C.fieldWrapper.unwrapField(o)));break;case"enum":const a=ha(e.T,A,g.ignoreUnknownFields,!1);switch(a){case UC:iB(e,t);break;case LC:break;default:t[I]=a;break}break;case"scalar":try{const Q=YI(e.T,A,e.L,!1);switch(Q){case UC:iB(e,t);break;default:t[I]=Q;break}}catch(Q){let n="cannot decode field ".concat(i.typeName,".").concat(e.name," from JSON: ").concat(zg(A));throw Q instanceof Error&&Q.message.length>0&&(n+=": ".concat(Q.message)),new Error(n)}break}}function bh(t,A){if(t===$.BOOL)switch(A){case"true":A=!0;break;case"false":A=!1;break}return YI(t,A,Pt.BIGINT,!0).toString()}function YI(t,A,e,g){if(A===null)return g?Vi(t,e):UC;switch(t){case $.DOUBLE:case $.FLOAT:if(A==="NaN")return Number.NaN;if(A==="Infinity")return Number.POSITIVE_INFINITY;if(A==="-Infinity")return Number.NEGATIVE_INFINITY;if(A===""||typeof A=="string"&&A.trim().length!==A.length||typeof A!="string"&&typeof A!="number")break;const i=Number(A);if(Number.isNaN(i)||!Number.isFinite(i))break;return t==$.FLOAT&&Ts(i),i;case $.INT32:case $.FIXED32:case $.SFIXED32:case $.SINT32:case $.UINT32:let I;if(typeof A=="number"?I=A:typeof A=="string"&&A.length>0&&A.trim().length===A.length&&(I=Number(A)),I===void 0)break;return t==$.UINT32||t==$.FIXED32?Ba(I):GC(I),I;case $.INT64:case $.SFIXED64:case $.SINT64:if(typeof A!="number"&&typeof A!="string")break;const C=Ne.parse(A);return e?C.toString():C;case $.FIXED64:case $.UINT64:if(typeof A!="number"&&typeof A!="string")break;const o=Ne.uParse(A);return e?o.toString():o;case $.BOOL:if(typeof A!="boolean")break;return A;case $.STRING:if(typeof A!="string")break;try{encodeURIComponent(A)}catch{throw new Error("invalid UTF8")}return A;case $.BYTES:if(A==="")return new Uint8Array(0);if(typeof A!="string")break;return AB.dec(A)}throw new Error}function ha(t,A,e,g){if(A===null)return t.typeName=="google.protobuf.NullValue"?0:g?t.values[0].no:UC;switch(typeof A){case"number":if(Number.isInteger(A))return A;break;case"string":const i=t.findName(A);if(i!==void 0)return i.no;if(e)return LC;break}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(zg(A)))}function Nh(t){return t.repeated||t.kind=="map"?!0:!(t.oneof||t.kind=="message"||t.opt||t.req)}function QB(t,A,e){if(t.kind=="map"){Re(typeof A=="object"&&A!=null);const g={},i=Object.entries(A);switch(t.V.kind){case"scalar":for(const[C,o]of i)g[C.toString()]=KC(t.V.T,o);break;case"message":for(const[C,o]of i)g[C.toString()]=o.toJson(e);break;case"enum":const I=t.V.T;for(const[C,o]of i)g[C.toString()]=da(I,o,e.enumAsInteger);break}return e.emitDefaultValues||i.length>0?g:void 0}if(t.repeated){Re(Array.isArray(A));const g=[];switch(t.kind){case"scalar":for(let i=0;i<A.length;i++)g.push(KC(t.T,A[i]));break;case"enum":for(let i=0;i<A.length;i++)g.push(da(t.T,A[i],e.enumAsInteger));break;case"message":for(let i=0;i<A.length;i++)g.push(A[i].toJson(e));break}return e.emitDefaultValues||g.length>0?g:void 0}switch(t.kind){case"scalar":return KC(t.T,A);case"enum":return da(t.T,A,e.enumAsInteger);case"message":return IB(t.T,A).toJson(e)}}function da(t,A,e){var g;if(Re(typeof A=="number"),t.typeName=="google.protobuf.NullValue")return null;if(e)return A;const i=t.findNumber(A);return(g=i==null?void 0:i.name)!==null&&g!==void 0?g:A}function KC(t,A){switch(t){case $.INT32:case $.SFIXED32:case $.SINT32:case $.FIXED32:case $.UINT32:return Re(typeof A=="number"),A;case $.FLOAT:case $.DOUBLE:return Re(typeof A=="number"),Number.isNaN(A)?"NaN":A===Number.POSITIVE_INFINITY?"Infinity":A===Number.NEGATIVE_INFINITY?"-Infinity":A;case $.STRING:return Re(typeof A=="string"),A;case $.BOOL:return Re(typeof A=="boolean"),A;case $.UINT64:case $.FIXED64:case $.INT64:case $.SFIXED64:case $.SINT64:return Re(typeof A=="bigint"||typeof A=="string"||typeof A=="number"),A.toString();case $.BYTES:return Re(A instanceof Uint8Array),AB.enc(A)}}const ji=Symbol("@bufbuild/protobuf/unknown-fields"),nB={readUnknownFields:!0,readerFactory:t=>new lh(t)},sB={writeUnknownFields:!0,writerFactory:()=>new xh};function Sh(t){return t?Object.assign(Object.assign({},nB),t):nB}function kh(t){return t?Object.assign(Object.assign({},sB),t):sB}function Rh(){return{makeReadOptions:Sh,makeWriteOptions:kh,listUnknownFields(t){var A;return(A=t[ji])!==null&&A!==void 0?A:[]},discardUnknownFields(t){delete t[ji]},writeUnknownFields(t,A){const g=t[ji];if(g)for(const i of g)A.tag(i.no,i.wireType).raw(i.data)},onUnknownField(t,A,e,g){const i=t;Array.isArray(i[ji])||(i[ji]=[]),i[ji].push({no:A,wireType:e,data:g})},readMessage(t,A,e,g,i){const I=t.getType(),C=i?A.len:A.pos+e;let o,a;for(;A.pos<C&&([o,a]=A.tag(),!(i===!0&&a==Le.EndGroup));){const Q=I.fields.find(o);if(!Q){const n=A.skip(a,o);g.readUnknownFields&&this.onUnknownField(t,o,a,n);continue}BB(t,A,Q,a,g)}if(i&&(a!=Le.EndGroup||o!==e))throw new Error("invalid end group tag")},readField:BB,writeMessage(t,A,e){const g=t.getType();for(const i of g.fields.byNumber()){if(!tB(i,t)){if(i.req)throw new Error("cannot encode field ".concat(g.typeName,".").concat(i.name," to binary: required field not set"));continue}const I=i.oneof?t[i.oneof.localName].value:t[i.localName];EB(i,I,A,e)}return e.writeUnknownFields&&this.writeUnknownFields(t,A),A},writeField(t,A,e,g){A!==void 0&&EB(t,A,e,g)}}}function BB(t,A,e,g,i){let{repeated:I,localName:C}=e;switch(e.oneof&&(t=t[e.oneof.localName],t.case!=C&&delete t.value,t.case=C,C="value"),e.kind){case"scalar":case"enum":const o=e.kind=="enum"?$.INT32:e.T;let a=JC;if(e.kind=="scalar"&&e.L>0&&(a=Mh),I){let B=t[C];if(g==Le.LengthDelimited&&o!=$.STRING&&o!=$.BYTES){let d=A.uint32()+A.pos;for(;A.pos<d;)B.push(a(A,o))}else B.push(a(A,o))}else t[C]=a(A,o);break;case"message":const Q=e.T;I?t[C].push(vC(A,new Q,i,e)):xt(t[C])?vC(A,t[C],i,e):(t[C]=vC(A,new Q,i,e),Q.fieldWrapper&&!e.oneof&&!e.repeated&&(t[C]=Q.fieldWrapper.unwrapField(t[C])));break;case"map":let[n,s]=Gh(e,A,i);t[C][n]=s;break}}function vC(t,A,e,g){const i=A.getType().runtime.bin,I=g==null?void 0:g.delimited;return i.readMessage(A,t,I?g.no:t.uint32(),e,I),A}function Gh(t,A,e){const g=A.uint32(),i=A.pos+g;let I,C;for(;A.pos<i;){const[o]=A.tag();switch(o){case 1:I=JC(A,t.K);break;case 2:switch(t.V.kind){case"scalar":C=JC(A,t.V.T);break;case"enum":C=A.int32();break;case"message":C=vC(A,new t.V.T,e,void 0);break}break}}if(I===void 0&&(I=Vi(t.K,Pt.BIGINT)),typeof I!="string"&&typeof I!="number"&&(I=I.toString()),C===void 0)switch(t.V.kind){case"scalar":C=Vi(t.V.T,Pt.BIGINT);break;case"enum":C=t.V.T.values[0].no;break;case"message":C=new t.V.T;break}return[I,C]}function Mh(t,A){const e=JC(t,A);return typeof e=="bigint"?e.toString():e}function JC(t,A){switch(A){case $.STRING:return t.string();case $.BOOL:return t.bool();case $.DOUBLE:return t.double();case $.FLOAT:return t.float();case $.INT32:return t.int32();case $.INT64:return t.int64();case $.UINT64:return t.uint64();case $.FIXED64:return t.fixed64();case $.BYTES:return t.bytes();case $.FIXED32:return t.fixed32();case $.SFIXED32:return t.sfixed32();case $.SFIXED64:return t.sfixed64();case $.SINT64:return t.sint64();case $.UINT32:return t.uint32();case $.SINT32:return t.sint32()}}function EB(t,A,e,g){Re(A!==void 0);const i=t.repeated;switch(t.kind){case"scalar":case"enum":let I=t.kind=="enum"?$.INT32:t.T;if(i)if(Re(Array.isArray(A)),t.packed)Uh(e,I,t.no,A);else for(const C of A)TI(e,I,t.no,C);else TI(e,I,t.no,A);break;case"message":if(i){Re(Array.isArray(A));for(const C of A)rB(e,g,t,C)}else rB(e,g,t,A);break;case"map":Re(typeof A=="object"&&A!=null);for(const[C,o]of Object.entries(A))Fh(e,g,t,C,o);break}}function Fh(t,A,e,g,i){t.tag(e.no,Le.LengthDelimited),t.fork();let I=g;switch(e.K){case $.INT32:case $.FIXED32:case $.UINT32:case $.SFIXED32:case $.SINT32:I=Number.parseInt(g);break;case $.BOOL:Re(g=="true"||g=="false"),I=g=="true";break}switch(TI(t,e.K,1,I),e.V.kind){case"scalar":TI(t,e.V.T,2,i);break;case"enum":TI(t,$.INT32,2,i);break;case"message":Re(i!==void 0),t.tag(2,Le.LengthDelimited).bytes(i.toBinary(A));break}t.join()}function rB(t,A,e,g){const i=IB(e.T,g);e.delimited?t.tag(e.no,Le.StartGroup).raw(i.toBinary(A)).tag(e.no,Le.EndGroup):t.tag(e.no,Le.LengthDelimited).bytes(i.toBinary(A))}function TI(t,A,e,g){Re(g!==void 0);let[i,I]=cB(A);t.tag(e,i)[I](g)}function Uh(t,A,e,g){if(!g.length)return;t.tag(e,Le.LengthDelimited).fork();let[,i]=cB(A);for(let I=0;I<g.length;I++)t[i](g[I]);t.join()}function cB(t){let A=Le.Varint;switch(t){case $.BYTES:case $.STRING:A=Le.LengthDelimited;break;case $.DOUBLE:case $.FIXED64:case $.SFIXED64:A=Le.Bit64;break;case $.FIXED32:case $.SFIXED32:case $.FLOAT:A=Le.Bit32;break}const e=$[t].toLowerCase();return[A,e]}function Lh(){return{setEnumType:Hs,initPartial(t,A){if(t===void 0)return;const e=A.getType();for(const g of e.fields.byMember()){const i=g.localName,I=A,C=t;if(C[i]!=null)switch(g.kind){case"oneof":const o=C[i].case;if(o===void 0)continue;const a=g.findField(o);let Q=C[i].value;a&&a.kind=="message"&&!xt(Q,a.T)?Q=new a.T(Q):a&&a.kind==="scalar"&&a.T===$.BYTES&&(Q=qI(Q)),I[i]={case:o,value:Q};break;case"scalar":case"enum":let n=C[i];g.T===$.BYTES&&(n=g.repeated?n.map(qI):qI(n)),I[i]=n;break;case"map":switch(g.V.kind){case"scalar":case"enum":if(g.V.T===$.BYTES)for(const[E,d]of Object.entries(C[i]))I[i][E]=qI(d);else Object.assign(I[i],C[i]);break;case"message":const B=g.V.T;for(const E of Object.keys(C[i])){let d=C[i][E];B.fieldWrapper||(d=new B(d)),I[i][E]=d}break}break;case"message":const s=g.T;if(g.repeated)I[i]=C[i].map(B=>xt(B,s)?B:new s(B));else{const B=C[i];s.fieldWrapper?s.typeName==="google.protobuf.BytesValue"?I[i]=qI(B):I[i]=B:I[i]=xt(B,s)?B:new s(B)}break}}},equals(t,A,e){return A===e?!0:!A||!e?!1:t.fields.byMember().every(g=>{const i=A[g.localName],I=e[g.localName];if(g.repeated){if(i.length!==I.length)return!1;switch(g.kind){case"message":return i.every((C,o)=>g.T.equals(C,I[o]));case"scalar":return i.every((C,o)=>Ot(g.T,C,I[o]));case"enum":return i.every((C,o)=>Ot($.INT32,C,I[o]))}throw new Error("repeated cannot contain ".concat(g.kind))}switch(g.kind){case"message":let C=i,o=I;return g.T.fieldWrapper&&(C!==void 0&&!xt(C)&&(C=g.T.fieldWrapper.wrapField(C)),o!==void 0&&!xt(o)&&(o=g.T.fieldWrapper.wrapField(o))),g.T.equals(C,o);case"enum":return Ot($.INT32,i,I);case"scalar":return Ot(g.T,i,I);case"oneof":if(i.case!==I.case)return!1;const a=g.findField(i.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(i.value,I.value);case"enum":return Ot($.INT32,i.value,I.value);case"scalar":return Ot(a.T,i.value,I.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const Q=Object.keys(i).concat(Object.keys(I));switch(g.V.kind){case"message":const n=g.V.T;return Q.every(B=>n.equals(i[B],I[B]));case"enum":return Q.every(B=>Ot($.INT32,i[B],I[B]));case"scalar":const s=g.V.T;return Q.every(B=>Ot(s,i[B],I[B]))}break}})},clone(t){const A=t.getType(),e=new A,g=e;for(const i of A.fields.byMember()){const I=t[i.localName];let C;if(i.repeated)C=I.map(YC);else if(i.kind=="map"){C=g[i.localName];for(const[o,a]of Object.entries(I))C[o]=YC(a)}else i.kind=="oneof"?C=i.findField(I.case)?{case:I.case,value:YC(I.value)}:{case:void 0}:C=YC(I);g[i.localName]=C}for(const i of A.runtime.bin.listUnknownFields(t))A.runtime.bin.onUnknownField(g,i.no,i.wireType,i.data);return e}}}function YC(t){if(t===void 0)return t;if(xt(t))return t.clone();if(t instanceof Uint8Array){const A=new Uint8Array(t.byteLength);return A.set(t),A}return t}function qI(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Kh(t,A,e){return{syntax:t,json:yh(),bin:Rh(),util:Object.assign(Object.assign({},Lh()),{newFieldList:A,initFields:e}),makeMessageType(g,i,I){return Bh(this,g,i,I)},makeEnum:sh,makeEnumType:Ps,getEnumType:nh,makeExtension(g,i,I){return fh(this,g,i,I)}}}class vh{constructor(A,e){this._fields=A,this._normalizer=e}findJsonName(A){if(!this.jsonNames){const e={};for(const g of this.list())e[g.jsonName]=e[g.name]=g;this.jsonNames=e}return this.jsonNames[A]}find(A){if(!this.numbers){const e={};for(const g of this.list())e[g.no]=g;this.numbers=e}return this.numbers[A]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((A,e)=>A.no-e.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const A=this.members;let e;for(const g of this.list())g.oneof?g.oneof!==e&&(e=g.oneof,A.push(e)):A.push(g)}return this.members}}function hB(t,A){const e=dB(t);return A?e:Ph(Hh(e))}function Jh(t){return hB(t,!1)}const Yh=dB;function dB(t){let A=!1;const e=[];for(let g=0;g<t.length;g++){let i=t.charAt(g);switch(i){case"_":A=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":e.push(i),A=!1;break;default:A&&(A=!1,i=i.toUpperCase()),e.push(i);break}}return e.join("")}const Th=new Set(["constructor","toString","toJSON","valueOf"]),qh=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xB=t=>"".concat(t,"$"),Hh=t=>qh.has(t)?xB(t):t,Ph=t=>Th.has(t)?xB(t):t;class Oh{constructor(A){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=A,this.localName=Jh(A)}addField(A){Re(A.oneof===this,"field ".concat(A.name," not one of ").concat(this.name)),this.fields.push(A)}findField(A){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[A]}}function Vh(t,A){var e,g,i,I,C,o;const a=[];let Q;for(const n of typeof t=="function"?t():t){const s=n;if(s.localName=hB(n.name,n.oneof!==void 0),s.jsonName=(e=n.jsonName)!==null&&e!==void 0?e:Yh(n.name),s.repeated=(g=n.repeated)!==null&&g!==void 0?g:!1,n.kind=="scalar"&&(s.L=(i=n.L)!==null&&i!==void 0?i:Pt.BIGINT),s.delimited=(I=n.delimited)!==null&&I!==void 0?I:!1,s.req=(C=n.req)!==null&&C!==void 0?C:!1,s.opt=(o=n.opt)!==null&&o!==void 0?o:!1,n.packed===void 0&&(s.packed=n.kind=="enum"||n.kind=="scalar"&&n.T!=$.BYTES&&n.T!=$.STRING),n.oneof!==void 0){const B=typeof n.oneof=="string"?n.oneof:n.oneof.name;(!Q||Q.name!=B)&&(Q=new Oh(B)),s.oneof=Q,Q.addField(s)}a.push(s)}return a}const T=Kh("proto3",t=>new vh(t,A=>Vh(A)),t=>{for(const A of t.getType().fields.byMember()){if(A.opt)continue;const e=A.localName,g=t;if(A.repeated){g[e]=[];continue}switch(A.kind){case"oneof":g[e]={case:void 0};break;case"enum":g[e]=0;break;case"map":g[e]={};break;case"scalar":g[e]=Vi(A.T,A.L);break}}});class Bg extends Ea{constructor(A){super(),this.seconds=Ne.zero,this.nanos=0,T.util.initPartial(A,this)}fromJson(A,e){if(typeof A!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(T.json.debug(A)));const g=A.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(!g)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(g[1]+"-"+g[2]+"-"+g[3]+"T"+g[4]+":"+g[5]+":"+g[6]+(g[8]?g[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=Ne.parse(i/1e3),this.nanos=0,g[7]&&(this.nanos=parseInt("1"+g[7]+"0".repeat(9-g[7].length))-1e9),this}toJson(A){const e=Number(this.seconds)*1e3;if(e<Date.parse("0001-01-01T00:00:00Z")||e>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 g="Z";if(this.nanos>0){const i=(this.nanos+1e9).toString().substring(1);i.substring(3)==="000000"?g="."+i.substring(0,3)+"Z":i.substring(6)==="000"?g="."+i.substring(0,6)+"Z":g="."+i+"Z"}return new Date(e).toISOString().replace(".000Z",g)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Bg.fromDate(new Date)}static fromDate(A){const e=A.getTime();return new Bg({seconds:Ne.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(A,e){return new Bg().fromBinary(A,e)}static fromJson(A,e){return new Bg().fromJson(A,e)}static fromJsonString(A,e){return new Bg().fromJsonString(A,e)}static equals(A,e){return T.util.equals(Bg,A,e)}}Bg.runtime=T,Bg.typeName="google.protobuf.Timestamp",Bg.fields=T.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const jh=T.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Bg},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Wh,repeated:!0},{no:5,name:"events",kind:"message",T:Zh,repeated:!0}]),Wh=T.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:Xh,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Xh=T.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Bg},{no:3,name:"value",kind:"scalar",T:2}]),Zh=T.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:Bg},{no:7,name:"normalized_end_timestamp",kind:"message",T:Bg,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),lB=T.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ug=T.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ve=T.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"}]),xa=T.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),HI=T.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),PI=T.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Lg=T.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"}]),Wi=T.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"}]),zh=T.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),je=T.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"}]),TC=T.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:qC,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:GB}]),qC=T.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),$h=T.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:T.getEnumType(ve),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}]),di=T.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:T.getEnumType(Xi)},{no:4,name:"tracks",kind:"message",T:Zi,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:$h},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:T.getEnumType(OI)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:T.getEnumType(Lg)},{no:18,name:"kind_details",kind:"enum",T:T.getEnumType(Ad),repeated:!0}]),Xi=T.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),OI=T.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Ad=T.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),lg=T.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ed=T.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:xi,repeated:!0}]),Zi=T.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:T.getEnumType(Ug)},{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:T.getEnumType(ve)},{no:10,name:"layers",kind:"message",T:xi,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:ed,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:T.getEnumType(lg)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:GB},{no:19,name:"audio_features",kind:"enum",T:T.getEnumType(je),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(lB)}]),xi=T.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(xa)},{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}]),Eg=T.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:T.getEnumType(PA)},{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:uB,oneof:"value"},{no:3,name:"speaker",kind:"message",T:gd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:DB,oneof:"value"},{no:7,name:"transcription",kind:"message",T:td,oneof:"value"},{no:8,name:"metrics",kind:"message",T:jh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:la,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:_B,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:wB,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:pB,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ua,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Da,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:_a,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),PA=T.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),gd=T.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:fB,repeated:!0}]),fB=T.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}]),uB=T.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}]),DB=T.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),td=T.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:id,repeated:!0}]),id=T.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),la=T.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}]),_B=T.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}]),wB=T.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),pB=T.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:mB,oneof:"value"}]),mB=T.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}]),yB=T.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),bB=T.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:T.getEnumType(NB)},{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}]),NB=T.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Id=T.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:T.getEnumType(SB)},{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}]),SB=T.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"}]),kB=T.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:RB},{no:2,name:"screen",kind:"message",T:RB},{no:3,name:"resume_connection",kind:"enum",T:T.getEnumType(PI)},{no:4,name:"disabled_codecs",kind:"message",T:Cd},{no:5,name:"force_relay",kind:"enum",T:T.getEnumType(PI)}]),RB=T.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:T.getEnumType(PI)}]),Cd=T.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:qC,repeated:!0},{no:2,name:"publish",kind:"message",T:qC,repeated:!0}]),GB=T.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),fa=T.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),MB=T.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:T.getEnumType(fa)},{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"}),FB=T.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ua=T.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:T.getEnumType(lg)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:MB,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:FB,oneof:"content_header"}],{localName:"DataStream_Header"}),Da=T.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"}),_a=T.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"}),Kg=T.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),wa=T.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),od=T.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ad=T.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:li,oneof:"message"},{no:2,name:"answer",kind:"message",T:li,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ya,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ma,oneof:"message"},{no:5,name:"mute",kind:"message",T:ba,oneof:"message"},{no:6,name:"subscription",kind:"message",T:HC,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:LB,oneof:"message"},{no:8,name:"leave",kind:"message",T:PC,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:vB,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qB,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:HB,oneof:"message"},{no:13,name:"simulate",kind:"message",T:$g,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:JB,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:VB,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:KB,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ed,oneof:"message"}]),UB=T.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Qd,oneof:"message"},{no:2,name:"answer",kind:"message",T:li,oneof:"message"},{no:3,name:"offer",kind:"message",T:li,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ya,oneof:"message"},{no:5,name:"update",kind:"message",T:Bd,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Na,oneof:"message"},{no:8,name:"leave",kind:"message",T:PC,oneof:"message"},{no:9,name:"mute",kind:"message",T:ba,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:rd,oneof:"message"},{no:11,name:"room_update",kind:"message",T:cd,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:dd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ld,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ud,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Dd,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:sd,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:nd,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:wd,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:yd,oneof:"message"},{no:22,name:"request_response",kind:"message",T:bd,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Nd,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:_d,oneof:"message"}]),pa=T.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),ma=T.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:T.getEnumType(Ug)},{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:T.getEnumType(ve)},{no:9,name:"layers",kind:"message",T:xi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:pa,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:T.getEnumType(lg)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:T.getEnumType(lB)},{no:17,name:"audio_features",kind:"enum",T:T.getEnumType(je),repeated:!0}]),ya=T.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:T.getEnumType(Kg)},{no:3,name:"final",kind:"scalar",T:8}]),ba=T.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Qd=T.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:TC},{no:2,name:"participant",kind:"message",T:di},{no:3,name:"other_participants",kind:"message",T:di,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:YB,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:kB},{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:bB},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:qC,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),nd=T.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:YB,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:kB},{no:3,name:"server_info",kind:"message",T:bB},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Na=T.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Zi}]),sd=T.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),li=T.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}]),Bd=T.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:di,repeated:!0}]),HC=T.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:yB,repeated:!0}]),LB=T.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:T.getEnumType(xa)},{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}]),KB=T.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:T.getEnumType(je),repeated:!0}]),Ed=T.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}]),PC=T.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:T.getEnumType(Lg)},{no:3,name:"action",kind:"enum",T:T.getEnumType(zi)},{no:4,name:"regions",kind:"message",T:pd}]),zi=T.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),vB=T.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:xi,repeated:!0}]),JB=T.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}]),YB=T.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}]),rd=T.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:fB,repeated:!0}]),cd=T.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:TC}]),hd=T.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:T.getEnumType(HI)},{no:3,name:"score",kind:"scalar",T:2}]),dd=T.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:hd,repeated:!0}]),xd=T.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:T.getEnumType(wa)}]),ld=T.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:xd,repeated:!0}]),Sa=T.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:T.getEnumType(xa)},{no:2,name:"enabled",kind:"scalar",T:8}]),fd=T.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Sa,repeated:!0}]),ud=T.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Sa,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:fd,repeated:!0}]),TB=T.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}]),qB=T.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:TB,repeated:!0}]),Dd=T.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}]),_d=T.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:TC},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:di},{no:4,name:"other_participants",kind:"message",T:di,repeated:!0}]),HB=T.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:li},{no:2,name:"subscription",kind:"message",T:HC},{no:3,name:"publish_tracks",kind:"message",T:Na,repeated:!0},{no:4,name:"data_channels",kind:"message",T:OB,repeated:!0},{no:5,name:"offer",kind:"message",T:li},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:PB,repeated:!0}]),PB=T.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),OB=T.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:T.getEnumType(Kg)}]),$g=T.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:T.getEnumType(od),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"}]),VB=T.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),wd=T.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),pd=T.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:md,repeated:!0}]),md=T.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}]),yd=T.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:T.getEnumType(zh)}]),bd=T.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:T.getEnumType(ka)},{no:3,name:"message",kind:"scalar",T:9}]),ka=T.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Nd=T.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Sd(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var OC={exports:{}},kd=OC.exports,jB;function Rd(){return jB||(jB=1,function(t){(function(A,e){t.exports?t.exports=e():A.log=e()})(kd,function(){var A=function(){},e="undefined",g=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],I={},C=null;function o(c,h){var r=c[h];if(typeof r.bind=="function")return r.bind(c);try{return Function.prototype.bind.call(r,c)}catch{return function(){return Function.prototype.apply.apply(r,[c,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function Q(c){return c==="debug"&&(c="log"),typeof console===e?!1:c==="trace"&&g?a:console[c]!==void 0?o(console,c):console.log!==void 0?o(console,"log"):A}function n(){for(var c=this.getLevel(),h=0;h<i.length;h++){var r=i[h];this[r]=h<c?A:this.methodFactory(r,c,this.name)}if(this.log=this.debug,typeof console===e&&c<this.levels.SILENT)return"No console available for logging"}function s(c){return function(){typeof console!==e&&(n.call(this),this[c].apply(this,arguments))}}function B(c,h,r){return Q(c)||s.apply(this,arguments)}function E(c,h){var r=this,f,_,l,D="loglevel";typeof c=="string"?D+=":"+c:typeof c=="symbol"&&(D=void 0);function p(N){var U=(i[N]||"silent").toUpperCase();if(!(typeof window===e||!D)){try{window.localStorage[D]=U;return}catch{}try{window.document.cookie=encodeURIComponent(D)+"="+U+";"}catch{}}}function y(){var N;if(!(typeof window===e||!D)){try{N=window.localStorage[D]}catch{}if(typeof N===e)try{var U=window.document.cookie,K=encodeURIComponent(D),P=U.indexOf(K+"=");P!==-1&&(N=/^([^;]+)/.exec(U.slice(P+K.length+1))[1])}catch{}return r.levels[N]===void 0&&(N=void 0),N}}function k(){if(!(typeof window===e||!D)){try{window.localStorage.removeItem(D)}catch{}try{window.document.cookie=encodeURIComponent(D)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function x(N){var U=N;if(typeof U=="string"&&r.levels[U.toUpperCase()]!==void 0&&(U=r.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=r.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+N)}r.name=c,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=h||B,r.getLevel=function(){return l??_??f},r.setLevel=function(N,U){return l=x(N),U!==!1&&p(l),n.call(r)},r.setDefaultLevel=function(N){_=x(N),y()||r.setLevel(N,!1)},r.resetLevel=function(){l=null,k(),n.call(r)},r.enableAll=function(N){r.setLevel(r.levels.TRACE,N)},r.disableAll=function(N){r.setLevel(r.levels.SILENT,N)},r.rebuild=function(){if(C!==r&&(f=x(C.getLevel())),n.call(r),C===r)for(var N in I)I[N].rebuild()},f=x(C?C.getLevel():"WARN");var w=y();w!=null&&(l=x(w)),n.call(r)}C=new E,C.getLogger=function(h){if(typeof h!="symbol"&&typeof h!="string"||h==="")throw new TypeError("You must supply a name when creating a logger.");var r=I[h];return r||(r=I[h]=new E(h,C.methodFactory)),r};var d=typeof window!==e?window.log:void 0;return C.noConflict=function(){return typeof window!==e&&window.log===C&&(window.log=d),C},C.getLoggers=function(){return I},C.default=C,C})}(OC)),OC.exports}var VC=Rd(),Ra;(function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"})(Ra||(Ra={}));var vg;(function(t){t.Default="livekit",t.Room="livekit-room",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"})(vg||(vg={}));let Ae=VC.getLogger("livekit");Object.values(vg).map(t=>VC.getLogger(t)),Ae.setDefaultLevel(Ra.info);function lt(t){const A=VC.getLogger(t);return A.setDefaultLevel(Ae.getLevel()),A}const Gd=VC.getLogger("lk-e2ee"),VI=7e3,Md=[0,300,2*2*300,3*3*300,4*4*300,VI,VI,VI,VI,VI];class Fd{constructor(A){this._retryDelays=A!==void 0?[...A]:Md}nextRetryDelayInMs(A){if(A.retryCount>=this._retryDelays.length)return null;const e=this._retryDelays[A.retryCount];return A.retryCount<=1?e:e+Math.random()*1e3}}function Ud(t,A){var e={};for(var g in t)Object.prototype.hasOwnProperty.call(t,g)&&A.indexOf(g)<0&&(e[g]=t[g]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,g=Object.getOwnPropertySymbols(t);i<g.length;i++)A.indexOf(g[i])<0&&Object.prototype.propertyIsEnumerable.call(t,g[i])&&(e[g[i]]=t[g[i]]);return e}function S(t,A,e,g){function i(I){return I instanceof e?I:new e(function(C){C(I)})}return new(e||(e=Promise))(function(I,C){function o(n){try{Q(g.next(n))}catch(s){C(s)}}function a(n){try{Q(g.throw(n))}catch(s){C(s)}}function Q(n){n.done?I(n.value):i(n.value).then(o,a)}Q((g=g.apply(t,A||[])).next())})}function WB(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")}function ft(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var A=t[Symbol.asyncIterator],e;return A?A.call(t):(t=typeof WB=="function"?WB(t):t[Symbol.iterator](),e={},g("next"),g("throw"),g("return"),e[Symbol.asyncIterator]=function(){return this},e);function g(I){e[I]=t[I]&&function(C){return new Promise(function(o,a){C=t[I](C),i(o,a,C.done,C.value)})}}function i(I,C,o,a){Promise.resolve(a).then(function(Q){I({value:Q,done:o})},C)}}typeof SuppressedError=="function"&&SuppressedError;var jC={exports:{}},XB;function Ld(){if(XB)return jC.exports;XB=1;var t=typeof Reflect=="object"?Reflect:null,A=t&&typeof t.apply=="function"?t.apply:function(D,p,y){return Function.prototype.apply.call(D,p,y)},e;t&&typeof t.ownKeys=="function"?e=t.ownKeys:Object.getOwnPropertySymbols?e=function(D){return Object.getOwnPropertyNames(D).concat(Object.getOwnPropertySymbols(D))}:e=function(D){return Object.getOwnPropertyNames(D)};function g(l){console&&console.warn&&console.warn(l)}var i=Number.isNaN||function(D){return D!==D};function I(){I.init.call(this)}jC.exports=I,jC.exports.once=r,I.EventEmitter=I,I.prototype._events=void 0,I.prototype._eventsCount=0,I.prototype._maxListeners=void 0;var C=10;function o(l){if(typeof l!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof l)}Object.defineProperty(I,"defaultMaxListeners",{enumerable:!0,get:function(){return C},set:function(l){if(typeof l!="number"||l<0||i(l))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+l+".");C=l}}),I.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},I.prototype.setMaxListeners=function(D){if(typeof D!="number"||D<0||i(D))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+D+".");return this._maxListeners=D,this};function a(l){return l._maxListeners===void 0?I.defaultMaxListeners:l._maxListeners}I.prototype.getMaxListeners=function(){return a(this)},I.prototype.emit=function(D){for(var p=[],y=1;y<arguments.length;y++)p.push(arguments[y]);var k=D==="error",x=this._events;if(x!==void 0)k=k&&x.error===void 0;else if(!k)return!1;if(k){var w;if(p.length>0&&(w=p[0]),w instanceof Error)throw w;var N=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw N.context=w,N}var U=x[D];if(U===void 0)return!1;if(typeof U=="function")A(U,this,p);else for(var K=U.length,P=d(U,K),y=0;y<K;++y)A(P[y],this,p);return!0};function Q(l,D,p,y){var k,x,w;if(o(p),x=l._events,x===void 0?(x=l._events=Object.create(null),l._eventsCount=0):(x.newListener!==void 0&&(l.emit("newListener",D,p.listener?p.listener:p),x=l._events),w=x[D]),w===void 0)w=x[D]=p,++l._eventsCount;else if(typeof w=="function"?w=x[D]=y?[p,w]:[w,p]:y?w.unshift(p):w.push(p),k=a(l),k>0&&w.length>k&&!w.warned){w.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(D)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=l,N.type=D,N.count=w.length,g(N)}return l}I.prototype.addListener=function(D,p){return Q(this,D,p,!1)},I.prototype.on=I.prototype.addListener,I.prototype.prependListener=function(D,p){return Q(this,D,p,!0)};function n(){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 s(l,D,p){var y={fired:!1,wrapFn:void 0,target:l,type:D,listener:p},k=n.bind(y);return k.listener=p,y.wrapFn=k,k}I.prototype.once=function(D,p){return o(p),this.on(D,s(this,D,p)),this},I.prototype.prependOnceListener=function(D,p){return o(p),this.prependListener(D,s(this,D,p)),this},I.prototype.removeListener=function(D,p){var y,k,x,w,N;if(o(p),k=this._events,k===void 0)return this;if(y=k[D],y===void 0)return this;if(y===p||y.listener===p)--this._eventsCount===0?this._events=Object.create(null):(delete k[D],k.removeListener&&this.emit("removeListener",D,y.listener||p));else if(typeof y!="function"){for(x=-1,w=y.length-1;w>=0;w--)if(y[w]===p||y[w].listener===p){N=y[w].listener,x=w;break}if(x<0)return this;x===0?y.shift():c(y,x),y.length===1&&(k[D]=y[0]),k.removeListener!==void 0&&this.emit("removeListener",D,N||p)}return this},I.prototype.off=I.prototype.removeListener,I.prototype.removeAllListeners=function(D){var p,y,k;if(y=this._events,y===void 0)return this;if(y.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):y[D]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete y[D]),this;if(arguments.length===0){var x=Object.keys(y),w;for(k=0;k<x.length;++k)w=x[k],w!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(p=y[D],typeof p=="function")this.removeListener(D,p);else if(p!==void 0)for(k=p.length-1;k>=0;k--)this.removeListener(D,p[k]);return this};function B(l,D,p){var y=l._events;if(y===void 0)return[];var k=y[D];return k===void 0?[]:typeof k=="function"?p?[k.listener||k]:[k]:p?h(k):d(k,k.length)}I.prototype.listeners=function(D){return B(this,D,!0)},I.prototype.rawListeners=function(D){return B(this,D,!1)},I.listenerCount=function(l,D){return typeof l.listenerCount=="function"?l.listenerCount(D):E.call(l,D)},I.prototype.listenerCount=E;function E(l){var D=this._events;if(D!==void 0){var p=D[l];if(typeof p=="function")return 1;if(p!==void 0)return p.length}return 0}I.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]};function d(l,D){for(var p=new Array(D),y=0;y<D;++y)p[y]=l[y];return p}function c(l,D){for(;D+1<l.length;D++)l[D]=l[D+1];l.pop()}function h(l){for(var D=new Array(l.length),p=0;p<D.length;++p)D[p]=l[p].listener||l[p];return D}function r(l,D){return new Promise(function(p,y){function k(w){l.removeListener(D,x),y(w)}function x(){typeof l.removeListener=="function"&&l.removeListener("error",k),p([].slice.call(arguments))}_(l,D,x,{once:!0}),D!=="error"&&f(l,k,{once:!0})})}function f(l,D,p){typeof l.on=="function"&&_(l,"error",D,p)}function _(l,D,p,y){if(typeof l.on=="function")y.once?l.once(D,p):l.on(D,p);else if(typeof l.addEventListener=="function")l.addEventListener(D,function k(x){y.once&&l.removeEventListener(D,k),p(x)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof l)}return jC.exports}var At=Ld();let ZB=!0,zB=!0;function jI(t,A,e){const g=t.match(A);return g&&g.length>=e&&parseFloat(g[e],10)}function fi(t,A,e){if(!t.RTCPeerConnection)return;const g=t.RTCPeerConnection.prototype,i=g.addEventListener;g.addEventListener=function(C,o){if(C!==A)return i.apply(this,arguments);const a=Q=>{const n=e(Q);n&&(o.handleEvent?o.handleEvent(n):o(n))};return this._eventMap=this._eventMap||{},this._eventMap[A]||(this._eventMap[A]=new Map),this._eventMap[A].set(o,a),i.apply(this,[C,a])};const I=g.removeEventListener;g.removeEventListener=function(C,o){if(C!==A||!this._eventMap||!this._eventMap[A])return I.apply(this,arguments);if(!this._eventMap[A].has(o))return I.apply(this,arguments);const a=this._eventMap[A].get(o);return this._eventMap[A].delete(o),this._eventMap[A].size===0&&delete this._eventMap[A],Object.keys(this._eventMap).length===0&&delete this._eventMap,I.apply(this,[C,a])},Object.defineProperty(g,"on"+A,{get(){return this["_on"+A]},set(C){this["_on"+A]&&(this.removeEventListener(A,this["_on"+A]),delete this["_on"+A]),C&&this.addEventListener(A,this["_on"+A]=C)},enumerable:!0,configurable:!0})}function Kd(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(ZB=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function vd(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(zB=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function $B(){if(typeof window=="object"){if(ZB)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Ga(t,A){zB&&console.warn(t+" is deprecated, please use "+A+" instead.")}function Jd(t){const A={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return A.browser="Not a browser.",A;const{navigator:e}=t;if(e.userAgentData&&e.userAgentData.brands){const g=e.userAgentData.brands.find(i=>i.brand==="Chromium");if(g)return{browser:"chrome",version:parseInt(g.version,10)}}if(e.mozGetUserMedia)A.browser="firefox",A.version=parseInt(jI(e.userAgent,/Firefox\/(\d+)\./,1));else if(e.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)A.browser="chrome",A.version=parseInt(jI(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(t.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))A.browser="safari",A.version=parseInt(jI(e.userAgent,/AppleWebKit\/(\d+)\./,1)),A.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,A._safariVersion=jI(e.userAgent,/Version\/(\d+(\.?\d+))/,1);else return A.browser="Not a supported browser.",A;return A}function AE(t){return Object.prototype.toString.call(t)==="[object Object]"}function eE(t){return AE(t)?Object.keys(t).reduce(function(A,e){const g=AE(t[e]),i=g?eE(t[e]):t[e],I=g&&!Object.keys(i).length;return i===void 0||I?A:Object.assign(A,{[e]:i})},{}):t}function Ma(t,A,e){!A||e.has(A.id)||(e.set(A.id,A),Object.keys(A).forEach(g=>{g.endsWith("Id")?Ma(t,t.get(A[g]),e):g.endsWith("Ids")&&A[g].forEach(i=>{Ma(t,t.get(i),e)})}))}function gE(t,A,e){const g=e?"outbound-rtp":"inbound-rtp",i=new Map;if(A===null)return i;const I=[];return t.forEach(C=>{C.type==="track"&&C.trackIdentifier===A.id&&I.push(C)}),I.forEach(C=>{t.forEach(o=>{o.type===g&&o.trackId===C.id&&Ma(t,o,i)})}),i}const tE=$B;function iE(t,A){const e=t&&t.navigator;if(!e.mediaDevices)return;const g=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const a={};return Object.keys(o).forEach(Q=>{if(Q==="require"||Q==="advanced"||Q==="mediaSource")return;const n=typeof o[Q]=="object"?o[Q]:{ideal:o[Q]};n.exact!==void 0&&typeof n.exact=="number"&&(n.min=n.max=n.exact);const s=function(B,E){return B?B+E.charAt(0).toUpperCase()+E.slice(1):E==="deviceId"?"sourceId":E};if(n.ideal!==void 0){a.optional=a.optional||[];let B={};typeof n.ideal=="number"?(B[s("min",Q)]=n.ideal,a.optional.push(B),B={},B[s("max",Q)]=n.ideal,a.optional.push(B)):(B[s("",Q)]=n.ideal,a.optional.push(B))}n.exact!==void 0&&typeof n.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[s("",Q)]=n.exact):["min","max"].forEach(B=>{n[B]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[s(B,Q)]=n[B])})}),o.advanced&&(a.optional=(a.optional||[]).concat(o.advanced)),a},i=function(o,a){if(A.version>=61)return a(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const Q=function(n,s,B){s in n&&!(B in n)&&(n[B]=n[s],delete n[s])};o=JSON.parse(JSON.stringify(o)),Q(o.audio,"autoGainControl","googAutoGainControl"),Q(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=g(o.audio)}if(o&&typeof o.video=="object"){let Q=o.video.facingMode;Q=Q&&(typeof Q=="object"?Q:{ideal:Q});const n=A.version<66;if(Q&&(Q.exact==="user"||Q.exact==="environment"||Q.ideal==="user"||Q.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!n)){delete o.video.facingMode;let s;if(Q.exact==="environment"||Q.ideal==="environment"?s=["back","rear"]:(Q.exact==="user"||Q.ideal==="user")&&(s=["front"]),s)return e.mediaDevices.enumerateDevices().then(B=>{B=B.filter(d=>d.kind==="videoinput");let E=B.find(d=>s.some(c=>d.label.toLowerCase().includes(c)));return!E&&B.length&&s.includes("back")&&(E=B[B.length-1]),E&&(o.video.deviceId=Q.exact?{exact:E.deviceId}:{ideal:E.deviceId}),o.video=g(o.video),tE("chrome: "+JSON.stringify(o)),a(o)})}o.video=g(o.video)}return tE("chrome: "+JSON.stringify(o)),a(o)},I=function(o){return A.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},C=function(o,a,Q){i(o,n=>{e.webkitGetUserMedia(n,a,s=>{Q&&Q(I(s))})})};if(e.getUserMedia=C.bind(e),e.mediaDevices.getUserMedia){const o=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(a){return i(a,Q=>o(Q).then(n=>{if(Q.audio&&!n.getAudioTracks().length||Q.video&&!n.getVideoTracks().length)throw n.getTracks().forEach(s=>{s.stop()}),new DOMException("","NotFoundError");return n},n=>Promise.reject(I(n))))}}}function IE(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function CE(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const A=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=g=>{g.stream.addEventListener("addtrack",i=>{let I;t.RTCPeerConnection.prototype.getReceivers?I=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):I={track:i.track};const C=new Event("track");C.track=i.track,C.receiver=I,C.transceiver={receiver:I},C.streams=[g.stream],this.dispatchEvent(C)}),g.stream.getTracks().forEach(i=>{let I;t.RTCPeerConnection.prototype.getReceivers?I=this.getReceivers().find(o=>o.track&&o.track.id===i.id):I={track:i};const C=new Event("track");C.track=i,C.receiver=I,C.transceiver={receiver:I},C.streams=[g.stream],this.dispatchEvent(C)})},this.addEventListener("addstream",this._ontrackpoly)),A.apply(this,arguments)}}else fi(t,"track",A=>(A.transceiver||Object.defineProperty(A,"transceiver",{value:{receiver:A.receiver}}),A))}function oE(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const A=function(i,I){return{track:I,get dtmf(){return this._dtmf===void 0&&(I.kind==="audio"?this._dtmf=i.createDTMFSender(I):this._dtmf=null),this._dtmf},_pc:i}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,a){let Q=i.apply(this,arguments);return Q||(Q=A(this,o),this._senders.push(Q)),Q};const I=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){I.apply(this,arguments);const a=this._senders.indexOf(o);a!==-1&&this._senders.splice(a,1)}}const e=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(I){this._senders=this._senders||[],e.apply(this,[I]),I.getTracks().forEach(C=>{this._senders.push(A(this,C))})};const g=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(I){this._senders=this._senders||[],g.apply(this,[I]),I.getTracks().forEach(C=>{const o=this._senders.find(a=>a.track===C);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const A=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const g=A.apply(this,[]);return g.forEach(i=>i._pc=this),g},Object.defineProperty(t.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 aE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const I=e.apply(this,[]);return I.forEach(C=>C._pc=this),I});const g=t.RTCPeerConnection.prototype.addTrack;g&&(t.RTCPeerConnection.prototype.addTrack=function(){const I=g.apply(this,arguments);return I._pc=this,I}),t.RTCRtpSender.prototype.getStats=function(){const I=this;return this._pc.getStats().then(C=>gE(C,I.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(I=>I._pc=this),i}),fi(t,"track",g=>(g.receiver._pc=g.srcElement,g)),t.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(I=>gE(I,i.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;const A=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const g=arguments[0];let i,I,C;return this.getSenders().forEach(o=>{o.track===g&&(i?C=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===g&&(I?C=!0:I=o),o.track===g)),C||i&&I?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():I?I.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return A.apply(this,arguments)}}function QE(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(C=>this._shimmedLocalStreams[C][0])};const A=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(C,o){if(!o)return A.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=A.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(a)===-1&&this._shimmedLocalStreams[o.id].push(a):this._shimmedLocalStreams[o.id]=[o,a],a};const e=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(C){this._shimmedLocalStreams=this._shimmedLocalStreams||{},C.getTracks().forEach(Q=>{if(this.getSenders().find(s=>s.track===Q))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();e.apply(this,arguments);const a=this.getSenders().filter(Q=>o.indexOf(Q)===-1);this._shimmedLocalStreams[C.id]=[C].concat(a)};const g=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[C.id],g.apply(this,arguments)};const i=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},C&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const a=this._shimmedLocalStreams[o].indexOf(C);a!==-1&&this._shimmedLocalStreams[o].splice(a,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function nE(t,A){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&A.version>=65)return QE(t);const e=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const n=e.apply(this);return this._reverseStreams=this._reverseStreams||{},n.map(s=>this._reverseStreams[s.id])};const g=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(n){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.getTracks().forEach(s=>{if(this.getSenders().find(E=>E.track===s))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[n.id]){const s=new t.MediaStream(n.getTracks());this._streams[n.id]=s,this._reverseStreams[s.id]=n,n=s}g.apply(this,[n])};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(n){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[n.id]||n]),delete this._reverseStreams[this._streams[n.id]?this._streams[n.id].id:n.id],delete this._streams[n.id]},t.RTCPeerConnection.prototype.addTrack=function(n,s){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const B=[].slice.call(arguments,1);if(B.length!==1||!B[0].getTracks().find(c=>c===n))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(c=>c.track===n))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const d=this._streams[s.id];if(d)d.addTrack(n),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const c=new t.MediaStream([n]);this._streams[s.id]=c,this._reverseStreams[c.id]=s,this.addStream(c)}return this.getSenders().find(c=>c.track===n)};function I(Q,n){let s=n.sdp;return Object.keys(Q._reverseStreams||[]).forEach(B=>{const E=Q._reverseStreams[B],d=Q._streams[E.id];s=s.replace(new RegExp(d.id,"g"),E.id)}),new RTCSessionDescription({type:n.type,sdp:s})}function C(Q,n){let s=n.sdp;return Object.keys(Q._reverseStreams||[]).forEach(B=>{const E=Q._reverseStreams[B],d=Q._streams[E.id];s=s.replace(new RegExp(E.id,"g"),d.id)}),new RTCSessionDescription({type:n.type,sdp:s})}["createOffer","createAnswer"].forEach(function(Q){const n=t.RTCPeerConnection.prototype[Q],s={[Q](){const B=arguments;return arguments.length&&typeof arguments[0]=="function"?n.apply(this,[d=>{const c=I(this,d);B[0].apply(null,[c])},d=>{B[1]&&B[1].apply(null,d)},arguments[2]]):n.apply(this,arguments).then(d=>I(this,d))}};t.RTCPeerConnection.prototype[Q]=s[Q]});const o=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=C(this,arguments[0]),o.apply(this,arguments))};const a=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const Q=a.get.apply(this);return Q.type===""?Q:I(this,Q)}}),t.RTCPeerConnection.prototype.removeTrack=function(n){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!n._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(n._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let B;Object.keys(this._streams).forEach(E=>{this._streams[E].getTracks().find(c=>n.track===c)&&(B=this._streams[E])}),B&&(B.getTracks().length===1?this.removeStream(this._reverseStreams[B.id]):B.removeTrack(n.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Fa(t,A){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){const g=t.RTCPeerConnection.prototype[e],i={[e](){return arguments[0]=new(e==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),g.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=i[e]})}function sE(t,A){fi(t,"negotiationneeded",e=>{const g=e.target;if(!((A.version<72||g.getConfiguration&&g.getConfiguration().sdpSemantics==="plan-b")&&g.signalingState!=="stable"))return e})}var BE=Object.freeze({__proto__:null,fixNegotiationNeeded:sE,shimAddTrackRemoveTrack:nE,shimAddTrackRemoveTrackWithNative:QE,shimGetSendersWithDtmf:oE,shimGetUserMedia:iE,shimMediaStream:IE,shimOnTrack:CE,shimPeerConnection:Fa,shimSenderReceiverGetStats:aE});function EE(t,A){const e=t&&t.navigator,g=t&&t.MediaStreamTrack;if(e.getUserMedia=function(i,I,C){Ga("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(i).then(I,C)},!(A.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){const i=function(C,o,a){o in C&&!(a in C)&&(C[a]=C[o],delete C[o])},I=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(C){return typeof C=="object"&&typeof C.audio=="object"&&(C=JSON.parse(JSON.stringify(C)),i(C.audio,"autoGainControl","mozAutoGainControl"),i(C.audio,"noiseSuppression","mozNoiseSuppression")),I(C)},g&&g.prototype.getSettings){const C=g.prototype.getSettings;g.prototype.getSettings=function(){const o=C.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(g&&g.prototype.applyConstraints){const C=g.prototype.applyConstraints;g.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),C.apply(this,[o])}}}}function Yd(t,A){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(g){if(!(g&&g.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return g.video===!0?g.video={mediaSource:A}:g.video.mediaSource=A,t.navigator.mediaDevices.getUserMedia(g)})}function rE(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ua(t,A){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),A.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const I=t.RTCPeerConnection.prototype[i],C={[i](){return arguments[0]=new(i==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)}};t.RTCPeerConnection.prototype[i]=C[i]});const e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},g=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[I,C,o]=arguments;return g.apply(this,[I||null]).then(a=>{if(A.version<53&&!C)try{a.forEach(Q=>{Q.type=e[Q.type]||Q.type})}catch(Q){if(Q.name!=="TypeError")throw Q;a.forEach((n,s)=>{a.set(s,Object.assign({},n,{type:e[n.type]||n.type}))})}return a}).then(C,o)}}function cE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const A=t.RTCPeerConnection.prototype.getSenders;A&&(t.RTCPeerConnection.prototype.getSenders=function(){const i=A.apply(this,[]);return i.forEach(I=>I._pc=this),i});const e=t.RTCPeerConnection.prototype.addTrack;e&&(t.RTCPeerConnection.prototype.addTrack=function(){const i=e.apply(this,arguments);return i._pc=this,i}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function hE(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const A=t.RTCPeerConnection.prototype.getReceivers;A&&(t.RTCPeerConnection.prototype.getReceivers=function(){const g=A.apply(this,[]);return g.forEach(i=>i._pc=this),g}),fi(t,"track",e=>(e.receiver._pc=e.srcElement,e)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function dE(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(e){Ga("removeStream","removeTrack"),this.getSenders().forEach(g=>{g.track&&e.getTracks().includes(g.track)&&this.removeTrack(g)})})}function xE(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function lE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.addTransceiver;A&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let g=arguments[1]&&arguments[1].sendEncodings;g===void 0&&(g=[]),g=[...g];const i=g.length>0;i&&g.forEach(C=>{if("rid"in C&&!/^[a-z0-9]{0,16}$/i.test(C.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in C&&!(parseFloat(C.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in C&&!(parseFloat(C.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const I=A.apply(this,arguments);if(i){const{sender:C}=I,o=C.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=g,C.sendEncodings=g,this.setParametersPromises.push(C.setParameters(o).then(()=>{delete C.sendEncodings}).catch(()=>{delete C.sendEncodings})))}return I})}function fE(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;const A=t.RTCRtpSender.prototype.getParameters;A&&(t.RTCRtpSender.prototype.getParameters=function(){const g=A.apply(this,arguments);return"encodings"in g||(g.encodings=[].concat(this.sendEncodings||[{}])),g})}function uE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}function DE(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const A=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>A.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):A.apply(this,arguments)}}var _E=Object.freeze({__proto__:null,shimAddTransceiver:lE,shimCreateAnswer:DE,shimCreateOffer:uE,shimGetDisplayMedia:Yd,shimGetParameters:fE,shimGetUserMedia:EE,shimOnTrack:rE,shimPeerConnection:Ua,shimRTCDataChannel:xE,shimReceiverGetStats:hE,shimRemoveStream:dE,shimSenderGetStats:cE});function wE(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const A=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(g){this._localStreams||(this._localStreams=[]),this._localStreams.includes(g)||this._localStreams.push(g),g.getAudioTracks().forEach(i=>A.call(this,i,g)),g.getVideoTracks().forEach(i=>A.call(this,i,g))},t.RTCPeerConnection.prototype.addTrack=function(g){for(var i=arguments.length,I=new Array(i>1?i-1:0),C=1;C<i;C++)I[C-1]=arguments[C];return I&&I.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),A.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const g=this._localStreams.indexOf(e);if(g===-1)return;this._localStreams.splice(g,1);const i=e.getTracks();this.getSenders().forEach(I=>{i.includes(I.track)&&this.removeTrack(I)})})}}function pE(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=g=>{g.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const I=new Event("addstream");I.stream=i,this.dispatchEvent(I)})})}});const A=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const g=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(I=>{if(g._remoteStreams||(g._remoteStreams=[]),g._remoteStreams.indexOf(I)>=0)return;g._remoteStreams.push(I);const C=new Event("addstream");C.stream=I,g.dispatchEvent(C)})}),A.apply(g,arguments)}}}function mE(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const A=t.RTCPeerConnection.prototype,e=A.createOffer,g=A.createAnswer,i=A.setLocalDescription,I=A.setRemoteDescription,C=A.addIceCandidate;A.createOffer=function(Q,n){const s=arguments.length>=2?arguments[2]:arguments[0],B=e.apply(this,[s]);return n?(B.then(Q,n),Promise.resolve()):B},A.createAnswer=function(Q,n){const s=arguments.length>=2?arguments[2]:arguments[0],B=g.apply(this,[s]);return n?(B.then(Q,n),Promise.resolve()):B};let o=function(a,Q,n){const s=i.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s};A.setLocalDescription=o,o=function(a,Q,n){const s=I.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s},A.setRemoteDescription=o,o=function(a,Q,n){const s=C.apply(this,[a]);return n?(s.then(Q,n),Promise.resolve()):s},A.addIceCandidate=o}function yE(t){const A=t&&t.navigator;if(A.mediaDevices&&A.mediaDevices.getUserMedia){const e=A.mediaDevices,g=e.getUserMedia.bind(e);A.mediaDevices.getUserMedia=i=>g(bE(i))}!A.getUserMedia&&A.mediaDevices&&A.mediaDevices.getUserMedia&&(A.getUserMedia=(function(g,i,I){A.mediaDevices.getUserMedia(g).then(i,I)}).bind(A))}function bE(t){return t&&t.video!==void 0?Object.assign({},t,{video:eE(t.video)}):t}function NE(t){if(!t.RTCPeerConnection)return;const A=t.RTCPeerConnection;t.RTCPeerConnection=function(g,i){if(g&&g.iceServers){const I=[];for(let C=0;C<g.iceServers.length;C++){let o=g.iceServers[C];o.urls===void 0&&o.url?(Ga("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,I.push(o)):I.push(g.iceServers[C])}g.iceServers=I}return new A(g,i)},t.RTCPeerConnection.prototype=A.prototype,"generateCertificate"in A&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return A.generateCertificate}})}function SE(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function kE(t){const A=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(g){if(g){typeof g.offerToReceiveAudio<"u"&&(g.offerToReceiveAudio=!!g.offerToReceiveAudio);const i=this.getTransceivers().find(C=>C.receiver.track.kind==="audio");g.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):g.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof g.offerToReceiveVideo<"u"&&(g.offerToReceiveVideo=!!g.offerToReceiveVideo);const I=this.getTransceivers().find(C=>C.receiver.track.kind==="video");g.offerToReceiveVideo===!1&&I?I.direction==="sendrecv"?I.setDirection?I.setDirection("sendonly"):I.direction="sendonly":I.direction==="recvonly"&&(I.setDirection?I.setDirection("inactive"):I.direction="inactive"):g.offerToReceiveVideo===!0&&!I&&this.addTransceiver("video",{direction:"recvonly"})}return A.apply(this,arguments)}}function RE(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var GE=Object.freeze({__proto__:null,shimAudioContext:RE,shimCallbacksAPI:mE,shimConstraints:bE,shimCreateOfferLegacy:kE,shimGetUserMedia:yE,shimLocalStreamsAPI:wE,shimRTCIceServerUrls:NE,shimRemoteStreamsAPI:pE,shimTrackEventTransceiver:SE}),La={exports:{}},ME;function Td(){return ME||(ME=1,function(t){const A={};A.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},A.localCName=A.generateIdentifier(),A.splitLines=function(e){return e.trim().split(`
|
|
49
49
|
`).map(g=>g.trim())},A.splitSections=function(e){return e.split(`
|
|
50
50
|
m=`).map((i,I)=>(I>0?"m="+i:i).trim()+`\r
|
|
51
51
|
`)},A.getDescription=function(e){const g=A.splitSections(e);return g&&g[0]},A.getMediaSections=function(e){const g=A.splitSections(e);return g.shift(),g},A.matchPrefix=function(e,g){return A.splitLines(e).filter(i=>i.indexOf(g)===0)},A.parseCandidate=function(e){let g;e.indexOf("a=candidate:")===0?g=e.substring(12).split(" "):g=e.substring(10).split(" ");const i={foundation:g[0],component:{1:"rtp",2:"rtcp"}[g[1]]||g[1],protocol:g[2].toLowerCase(),priority:parseInt(g[3],10),ip:g[4],address:g[4],port:parseInt(g[5],10),type:g[7]};for(let I=8;I<g.length;I+=2)switch(g[I]){case"raddr":i.relatedAddress=g[I+1];break;case"rport":i.relatedPort=parseInt(g[I+1],10);break;case"tcptype":i.tcpType=g[I+1];break;case"ufrag":i.ufrag=g[I+1],i.usernameFragment=g[I+1];break;default:i[g[I]]===void 0&&(i[g[I]]=g[I+1]);break}return i},A.writeCandidate=function(e){const g=[];g.push(e.foundation);const i=e.component;i==="rtp"?g.push(1):i==="rtcp"?g.push(2):g.push(i),g.push(e.protocol.toUpperCase()),g.push(e.priority),g.push(e.address||e.ip),g.push(e.port);const I=e.type;return g.push("typ"),g.push(I),I!=="host"&&e.relatedAddress&&e.relatedPort&&(g.push("raddr"),g.push(e.relatedAddress),g.push("rport"),g.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()==="tcp"&&(g.push("tcptype"),g.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(g.push("ufrag"),g.push(e.usernameFragment||e.ufrag)),"candidate:"+g.join(" ")},A.parseIceOptions=function(e){return e.substring(14).split(" ")},A.parseRtpMap=function(e){let g=e.substring(9).split(" ");const i={payloadType:parseInt(g.shift(),10)};return g=g[0].split("/"),i.name=g[0],i.clockRate=parseInt(g[1],10),i.channels=g.length===3?parseInt(g[2],10):1,i.numChannels=i.channels,i},A.writeRtpMap=function(e){let g=e.payloadType;e.preferredPayloadType!==void 0&&(g=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+g+" "+e.name+"/"+e.clockRate+(i!==1?"/"+i:"")+`\r
|
|
@@ -76,12 +76,12 @@ a=ice-pwd:`+e.password+`\r
|
|
|
76
76
|
o=`+(i||"thisisadapterortc")+" "+I+" "+C+` IN IP4 127.0.0.1\r
|
|
77
77
|
s=-\r
|
|
78
78
|
t=0 0\r
|
|
79
|
-
`},A.getDirection=function(e,g){const i=A.splitLines(e);for(let I=0;I<i.length;I++)switch(i[I]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[I].substring(2)}return g?A.getDirection(g):"sendrecv"},A.getKind=function(e){return A.splitLines(e)[0].split(" ")[0].substring(2)},A.isRejected=function(e){return e.split(" ",2)[1]==="0"},A.parseMLine=function(e){const i=A.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},A.parseOLine=function(e){const i=A.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},A.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;const g=A.splitLines(e);for(let i=0;i<g.length;i++)if(g[i].length<2||g[i].charAt(1)!=="=")return!1;return!0},t.exports=A}(La)),La.exports}var FE=Td()
|
|
79
|
+
`},A.getDirection=function(e,g){const i=A.splitLines(e);for(let I=0;I<i.length;I++)switch(i[I]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[I].substring(2)}return g?A.getDirection(g):"sendrecv"},A.getKind=function(e){return A.splitLines(e)[0].split(" ")[0].substring(2)},A.isRejected=function(e){return e.split(" ",2)[1]==="0"},A.parseMLine=function(e){const i=A.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},A.parseOLine=function(e){const i=A.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},A.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;const g=A.splitLines(e);for(let i=0;i<g.length;i++)if(g[i].length<2||g[i].charAt(1)!=="=")return!1;return!0},t.exports=A}(La)),La.exports}var FE=Td(),$i=Sd(FE),qd=gh({__proto__:null,default:$i},[FE]);function WC(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const A=t.RTCIceCandidate;t.RTCIceCandidate=function(g){if(typeof g=="object"&&g.candidate&&g.candidate.indexOf("a=")===0&&(g=JSON.parse(JSON.stringify(g)),g.candidate=g.candidate.substring(2)),g.candidate&&g.candidate.length){const i=new A(g),I=$i.parseCandidate(g.candidate);for(const C in I)C in i||Object.defineProperty(i,C,{value:I[C]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new A(g)},t.RTCIceCandidate.prototype=A.prototype,fi(t,"icecandidate",e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new t.RTCIceCandidate(e.candidate),writable:"false"}),e))}function Ka(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||fi(t,"icecandidate",A=>{if(A.candidate){const e=$i.parseCandidate(A.candidate.candidate);e.type==="relay"&&(A.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[e.priority>>24])}return A})}function XC(t,A){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const e=function(o){if(!o||!o.sdp)return!1;const a=$i.splitSections(o.sdp);return a.shift(),a.some(Q=>{const n=$i.parseMLine(Q);return n&&n.kind==="application"&&n.protocol.indexOf("SCTP")!==-1})},g=function(o){const a=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(a===null||a.length<2)return-1;const Q=parseInt(a[1],10);return Q!==Q?-1:Q},i=function(o){let a=65536;return A.browser==="firefox"&&(A.version<57?o===-1?a=16384:a=2147483637:A.version<60?a=A.version===57?65535:65536:a=2147483637),a},I=function(o,a){let Q=65536;A.browser==="firefox"&&A.version===57&&(Q=65535);const n=$i.matchPrefix(o.sdp,"a=max-message-size:");return n.length>0?Q=parseInt(n[0].substring(19),10):A.browser==="firefox"&&a!==-1&&(Q=2147483637),Q},C=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,A.browser==="chrome"&&A.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(e(arguments[0])){const a=g(arguments[0]),Q=i(a),n=I(arguments[0],a);let s;Q===0&&n===0?s=Number.POSITIVE_INFINITY:Q===0||n===0?s=Math.max(Q,n):s=Math.min(Q,n);const B={};Object.defineProperty(B,"maxMessageSize",{get(){return s}}),this._sctp=B}return C.apply(this,arguments)}}function ZC(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function A(g,i){const I=g.send;g.send=function(){const o=arguments[0],a=o.length||o.size||o.byteLength;if(g.readyState==="open"&&i.sctp&&a>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return I.apply(g,arguments)}}const e=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const i=e.apply(this,arguments);return A(i,this),i},fi(t,"datachannel",g=>(A(g.channel,g.target),g))}function va(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const A=t.RTCPeerConnection.prototype;Object.defineProperty(A,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(A,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const g=A[e];A[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const I=i.target;if(I._lastConnectionState!==I.connectionState){I._lastConnectionState=I.connectionState;const C=new Event("connectionstatechange",i);I.dispatchEvent(C)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),g.apply(this,arguments)}})}function Ja(t,A){if(!t.RTCPeerConnection||A.browser==="chrome"&&A.version>=71||A.browser==="safari"&&A._safariVersion>=13.1)return;const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
80
80
|
a=extmap-allow-mixed`)!==-1){const I=i.sdp.split(`
|
|
81
81
|
`).filter(C=>C.trim()!=="a=extmap-allow-mixed").join(`
|
|
82
|
-
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:I}):i.sdp=I}return e.apply(this,arguments)}}function zC(t,A){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const e=t.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(A.browser==="chrome"&&A.version<78||A.browser==="firefox"&&A.version<68||A.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function $C(t,A){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const e=t.RTCPeerConnection.prototype.setLocalDescription;!e||e.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return e.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?e.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(C=>e.apply(this,[C]))})}var Hd=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ja,shimAddIceCandidateNullOrEmpty:zC,shimConnectionState:va,shimMaxMessageSize:XC,shimParameterlessSetLocalDescription:$C,shimRTCIceCandidate:WC,shimRTCIceCandidateRelayProtocol:Ka,shimSendThrowTypeError:ZC});function Pd(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const e=$B,g=Jd(t),i={browserDetails:g,commonShim:Hd,extractVersion:jI,disableLog:Kd,disableWarnings:vd,sdp:qd};switch(g.browser){case"chrome":if(!BE||!Fa||!A.shimChrome)return e("Chrome shim is not included in this adapter release."),i;if(g.version===null)return e("Chrome shim can not determine version, not shimming."),i;e("adapter.js shimming chrome."),i.browserShim=BE,zC(t,g),$C(t),iE(t,g),IE(t),Fa(t,g),CE(t),nE(t,g),oE(t),aE(t),sE(t,g),WC(t),Ka(t),va(t),XC(t,g),ZC(t),Ja(t,g);break;case"firefox":if(!_E||!Ua||!A.shimFirefox)return e("Firefox shim is not included in this adapter release."),i;e("adapter.js shimming firefox."),i.browserShim=_E,zC(t,g),$C(t),EE(t,g),Ua(t,g),rE(t),dE(t),cE(t),hE(t),xE(t),lE(t),fE(t),uE(t),DE(t),WC(t),va(t),XC(t,g),ZC(t);break;case"safari":if(!GE||!A.shimSafari)return e("Safari shim is not included in this adapter release."),i;e("adapter.js shimming safari."),i.browserShim=GE,zC(t,g),$C(t),NE(t),kE(t),mE(t),wE(t),pE(t),SE(t),yE(t),RE(t),WC(t),Ka(t),XC(t,g),ZC(t),Ja(t,g);break;default:e("Unsupported browser!");break}return i}Pd({window:typeof window>"u"?void 0:window});const Od=10,WI="lk_e2ee",Vd={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Od,keyringSize:16};var Vt;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(Vt||(Vt={}));var UE;(function(t){t.KeyRatcheted="keyRatcheted"})(UE||(UE={}));var jt;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(jt||(jt={}));var LE;(function(t){t.Error="cryptorError"})(LE||(LE={}));function jd(){return Wd()||Ya()}function Ya(){return typeof window.RTCRtpScriptTransform<"u"}function Wd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Ep extends At.EventEmitter{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(e,g,i)=>{$A.debug("key ratcheted event received",{ratchetResult:e,participantId:g,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Vd),A),this.on(Vt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(A,e,g){const i={key:A,participantIdentity:e,keyIndex:g};if(!this.options.sharedKey&&!e)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(e??"shared","-").concat(g??0),i),this.emit(Vt.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(A,e){this.emit(Vt.RatchetRequest,A,e)}}class ut extends Error{constructor(A,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=A}}var ie;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(ie||(ie={}));class ue extends ut{constructor(A,e,g,i){super(1,A),this.name="ConnectionError",this.status=g,this.reason=e,this.context=i,this.reasonName=ie[e]}}class Ta extends ut{constructor(A){super(21,A??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Dt extends ut{constructor(A){super(20,A??"track is invalid"),this.name="TrackInvalidError"}}class Xd extends ut{constructor(A){super(10,A??"unsupported server"),this.name="UnsupportedServer"}}class Pe extends ut{constructor(A){super(12,A??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class qa extends ut{constructor(A){super(13,A??"unable to negotiate"),this.name="NegotiationError"}}class KE extends ut{constructor(A,e){super(15,A),this.name="PublishTrackError",this.status=e}}class vE extends ut{constructor(A,e){super(15,A),this.reason=e,this.reasonName=typeof e=="string"?e:ka[e]}}var Jg;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(Jg||(Jg={}));class Wt extends ut{constructor(A,e){super(16,A),this.name="DataStreamError",this.reason=e,this.reasonName=Jg[e]}}var Ao;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Ao||(Ao={})),function(t){function A(e){if(e&&"name"in e)return e.name==="NotFoundError"||e.name==="DevicesNotFoundError"?t.NotFound:e.name==="NotAllowedError"||e.name==="PermissionDeniedError"?t.PermissionDenied:e.name==="NotReadableError"||e.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=A}(Ao||(Ao={}));var JE;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(JE||(JE={}));var tA;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(tA||(tA={}));var QA;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(QA||(QA={}));var nA;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(nA||(nA={}));var oA;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(oA||(oA={}));function Zd(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const zd=/version\/(\d+(\.?_?\d+)+)/i;let Ha;function fg(t){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const e=navigator.userAgent.toLowerCase();if(Ha===void 0||A){const g=$d.find(i=>{let{test:I}=i;return I.test(e)});Ha=g==null?void 0:g.describe(e)}return Ha}const $d=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:eo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Pa(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:eo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Pa(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:eo(zd,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Pa(t)}}}];function eo(t,A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const g=A.match(t);return g&&g.length>=e&&g[e]||""}function Pa(t){return t.includes("mac os")?eo(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var Ax="2.15.6";const ex=Ax,gx=16;class ze{}ze.setTimeout=function(){return setTimeout(...arguments)},ze.setInterval=function(){return setInterval(...arguments)},ze.clearTimeout=function(){return clearTimeout(...arguments)},ze.clearInterval=function(){return clearInterval(...arguments)};const tx=5e3,XI=[];var ug;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(ug||(ug={}));class AA extends At.EventEmitter{get streamState(){return this._streamState}setStreamState(A){this._streamState=A}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=AA.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=$A,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),tx):this.handleAppVisibilityChanged()},this.log=lt((i=g.loggerName)!==null&&i!==void 0?i:vg.Track),this.loggerContextCb=g.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=A,this._mediaStreamID=A.id,this.source=AA.Source.Unknown}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),WA(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(A){let e="audio";this.kind===AA.Kind.Video&&(e="video"),this.attachedElements.length===0&&this.kind===AA.Kind.Video&&this.addAppVisibilityListener(),A||(e==="audio"&&(XI.forEach(I=>{I.parentElement===null&&!A&&(A=I)}),A&&XI.splice(XI.indexOf(A),1)),A||(A=document.createElement(e))),this.attachedElements.includes(A)||this.attachedElements.push(A),$i(this.mediaStreamTrack,A);const g=A.srcObject.getTracks(),i=g.some(I=>I.kind==="audio");return A.play().then(()=>{this.emit(i?oA.AudioPlaybackStarted:oA.VideoPlaybackStarted)}).catch(I=>{I.name==="NotAllowedError"?this.emit(i?oA.AudioPlaybackFailed:oA.VideoPlaybackFailed,I):I.name==="AbortError"?$A.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):$A.warn("could not playback ".concat(i?"audio":"video"),I),i&&A&&g.some(C=>C.kind==="video")&&I.name==="NotAllowedError"&&(A.muted=!0,A.play().catch(()=>{}))}),this.emit(oA.ElementAttached,A),A}detach(A){try{if(A){AI(this.mediaStreamTrack,A);const g=this.attachedElements.indexOf(A);return g>=0&&(this.attachedElements.splice(g,1),this.recycleElement(A),this.emit(oA.ElementDetached,A)),A}const e=[];return this.attachedElements.forEach(g=>{AI(this.mediaStreamTrack,g),e.push(g),this.recycleElement(g),this.emit(oA.ElementDetached,g)}),this.attachedElements=[],e}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(A){A.loggerName&&(this.log=lt(A.loggerName)),A.loggerContextCb&&(this.loggerContextCb=A.loggerContextCb)}recycleElement(A){if(A instanceof HTMLAudioElement){let e=!0;A.pause(),XI.forEach(g=>{g.parentElement||(e=!1)}),e&&XI.push(A)}}handleAppVisibilityChanged(){return S(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===AA.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(A=>A.play().catch(()=>{})),0)})}addAppVisibilityListener(){cg()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){cg()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function $i(t,A){let e;A.srcObject instanceof MediaStream?e=A.srcObject:e=new MediaStream;let g;t.kind==="audio"?g=e.getAudioTracks():g=e.getVideoTracks(),g.includes(t)||(g.forEach(i=>{e.removeTrack(i)}),e.addTrack(t)),(!Di()||!(A instanceof HTMLVideoElement))&&(A.autoplay=!0),A.muted=e.getAudioTracks().length===0,A instanceof HTMLVideoElement&&(A.playsInline=!0),A.srcObject!==e&&(A.srcObject=e,(Di()||ui())&&A instanceof HTMLVideoElement&&setTimeout(()=>{A.srcObject=e,A.play().catch(()=>{})},0))}function AI(t,A){if(A.srcObject instanceof MediaStream){const e=A.srcObject;e.removeTrack(t),e.getTracks().length>0?A.srcObject=e:A.srcObject=null}}(function(t){let A;(function(Q){Q.Audio="audio",Q.Video="video",Q.Unknown="unknown"})(A=t.Kind||(t.Kind={}));let e;(function(Q){Q.Camera="camera",Q.Microphone="microphone",Q.ScreenShare="screen_share",Q.ScreenShareAudio="screen_share_audio",Q.Unknown="unknown"})(e=t.Source||(t.Source={}));let g;(function(Q){Q.Active="active",Q.Paused="paused",Q.Unknown="unknown"})(g=t.StreamState||(t.StreamState={}));function i(Q){switch(Q){case A.Audio:return Ug.AUDIO;case A.Video:return Ug.VIDEO;default:return Ug.DATA}}t.kindToProto=i;function I(Q){switch(Q){case Ug.AUDIO:return A.Audio;case Ug.VIDEO:return A.Video;default:return A.Unknown}}t.kindFromProto=I;function C(Q){switch(Q){case e.Camera:return ve.CAMERA;case e.Microphone:return ve.MICROPHONE;case e.ScreenShare:return ve.SCREEN_SHARE;case e.ScreenShareAudio:return ve.SCREEN_SHARE_AUDIO;default:return ve.UNKNOWN}}t.sourceToProto=C;function o(Q){switch(Q){case ve.CAMERA:return e.Camera;case ve.MICROPHONE:return e.Microphone;case ve.SCREEN_SHARE:return e.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return e.ScreenShareAudio;default:return e.Unknown}}t.sourceFromProto=o;function a(Q){switch(Q){case wa.ACTIVE:return g.Active;case wa.PAUSED:return g.Paused;default:return g.Unknown}}t.streamStateFromProto=a})(AA||(AA={}));class xe{constructor(A,e,g,i,I){if(typeof A=="object")this.width=A.width,this.height=A.height,this.aspectRatio=A.aspectRatio,this.encoding={maxBitrate:A.maxBitrate,maxFramerate:A.maxFramerate,priority:A.priority};else if(e!==void 0&&g!==void 0)this.width=A,this.height=e,this.aspectRatio=A/e,this.encoding={maxBitrate:g,maxFramerate:i,priority:I};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 ix=["vp8","h264"],Ix=["vp8","h264","vp9","av1","h265"];function Cx(t){return!!ix.find(A=>A===t)}var YE;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(YE||(YE={}));var Oa;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(Oa||(Oa={}));const ZI={h90:new xe(160,90,9e4,20),h180:new xe(320,180,16e4,20),h216:new xe(384,216,18e4,20),h360:new xe(640,360,45e4,20),h540:new xe(960,540,8e5,25),h720:new xe(1280,720,17e5,30),h1080:new xe(1920,1080,3e6,30),h1440:new xe(2560,1440,5e6,30),h2160:new xe(3840,2160,8e6,30)},Va={h120:new xe(160,120,7e4,20),h180:new xe(240,180,125e3,20),h240:new xe(320,240,14e4,20),h360:new xe(480,360,33e4,20),h480:new xe(640,480,5e5,20),h540:new xe(720,540,6e5,25),h720:new xe(960,720,13e5,30),h1080:new xe(1440,1080,23e5,30),h1440:new xe(1920,1440,38e5,30)},ja={h360fps3:new xe(640,360,2e5,3,"medium"),h360fps15:new xe(640,360,4e5,15,"medium"),h720fps5:new xe(1280,720,8e5,5,"medium"),h720fps15:new xe(1280,720,15e5,15,"medium"),h720fps30:new xe(1280,720,2e6,30,"medium"),h1080fps15:new xe(1920,1080,25e5,15,"medium"),h1080fps30:new xe(1920,1080,5e6,30,"medium"),original:new xe(0,0,7e6,30,"medium")},ox="|",TE="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ax(t){const A=t.split(ox);return A.length>1?[A[0],t.substr(A[0].length+1)]:[t,""]}function rg(t){return S(this,void 0,void 0,function*(){return new Promise(A=>ze.setTimeout(A,t))})}function Wa(){return"addTransceiver"in RTCPeerConnection.prototype}function Xa(){return"addTrack"in RTCPeerConnection.prototype}function Qx(){if(!("getCapabilities"in RTCRtpSender)||Di()||ui())return!1;const t=RTCRtpSender.getCapabilities("video");let A=!1;if(t){for(const e of t.codecs)if(e.mimeType==="video/AV1"){A=!0;break}}return A}function nx(){if(!("getCapabilities"in RTCRtpSender)||ui())return!1;if(Di()){const e=fg();if(e!=null&&e.version&&tt(e.version,"16")<0||(e==null?void 0:e.os)==="iOS"&&(e!=null&&e.osVersion)&&tt(e.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let A=!1;if(t){for(const e of t.codecs)if(e.mimeType==="video/VP9"){A=!0;break}}return A}function et(t){return t==="av1"||t==="vp9"}function Za(t){return!document||zI()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function sx(){return typeof RTCPeerConnection>"u"?!1:Wa()||Xa()}function ui(){var t;return((t=fg())===null||t===void 0?void 0:t.name)==="Firefox"}function Di(){var t;return((t=fg())===null||t===void 0?void 0:t.name)==="Safari"}function zI(){const t=fg();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function Bx(){const t=fg();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&tt(t.osVersion,"17")>=0}function Ex(t){return t||(t=fg()),(t==null?void 0:t.name)==="Safari"&&tt(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&tt(t.osVersion,"18.3")>0}function qE(){var t,A;return cg()?(A=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&A!==void 0?A:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function rx(){const t=fg(),A="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&tt(t.osVersion,A)>=0?!0:t.name==="Safari"&&tt(t.version,A)>=0}function cg(){return typeof document<"u"}function gt(){return navigator.product=="ReactNative"}function za(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function HE(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function PE(){if(!gt())return;let t=HE();if(t)return t.platform}function OE(){if(cg())return window.devicePixelRatio;if(gt()){let t=HE();if(t)return t.devicePixelRatio}return 1}function tt(t,A){const e=t.split("."),g=A.split("."),i=Math.min(e.length,g.length);for(let I=0;I<i;++I){const C=parseInt(e[I],10),o=parseInt(g[I],10);if(C>o)return 1;if(C<o)return-1;if(I===i-1&&C===o)return 0}return t===""&&A!==""?-1:A===""?1:e.length==g.length?0:e.length<g.length?-1:1}function cx(t){for(const A of t)A.target.handleResize(A)}function hx(t){for(const A of t)A.target.handleVisibilityChanged(A)}let $a=null;const VE=()=>($a||($a=new ResizeObserver(cx)),$a);let AQ=null;const jE=()=>(AQ||(AQ=new IntersectionObserver(hx,{root:null,rootMargin:"0px"})),AQ);function dx(){var t;const A=new Id({sdk:SB.JS,protocol:gx,version:ex});return gt()&&(A.os=(t=PE())!==null&&t!==void 0?t:""),A}function WE(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=t,i.height=A;const I=i.getContext("2d");I==null||I.fillRect(0,0,i.width,i.height),g&&I&&(I.beginPath(),I.arc(t/2,A/2,50,0,Math.PI*2,!0),I.closePath(),I.fillStyle="grey",I.fill());const C=i.captureStream(),[o]=C.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=e,o}let $I;function eQ(){if(!$I){const t=new AudioContext,A=t.createOscillator(),e=t.createGain();e.gain.setValueAtTime(0,0);const g=t.createMediaStreamDestination();if(A.connect(e),e.connect(g),A.start(),[$I]=g.stream.getAudioTracks(),!$I)throw Error("Could not get empty media stream audio track");$I.enabled=!1}return $I.clone()}class it{get isResolved(){return this._isResolved}constructor(A,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise((g,i)=>S(this,void 0,void 0,function*(){this.resolve=g,this.reject=i,A&&(yield A(g,i))})).finally(()=>{var g;this._isResolved=!0,(g=this.onFinally)===null||g===void 0||g.call(this)})}}function xx(t){return Ix.includes(t)}function Xt(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function lx(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function gQ(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function fx(t,A){return t.segments.map(e=>{let{id:g,text:i,language:I,startTime:C,endTime:o,final:a}=e;var Q;const n=(Q=A.get(g))!==null&&Q!==void 0?Q:Date.now(),s=Date.now();return a?A.delete(g):A.set(g,n),{id:g,text:i,startTime:Number.parseInt(C.toString()),endTime:Number.parseInt(o.toString()),final:a,language:I,firstReceivedTime:n,lastReceivedTime:s}})}function ux(t){const{id:A,timestamp:e,message:g,editTimestamp:i}=t;return{id:A,timestamp:Number.parseInt(e.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:g}}function XE(t){switch(t.reason){case ie.LeaveRequest:return t.context;case ie.Cancelled:return Lg.CLIENT_INITIATED;case ie.NotAllowed:return Lg.USER_REJECTED;case ie.ServerUnreachable:return Lg.JOIN_FAILURE;default:return Lg.UNKNOWN_REASON}}function go(t){return t!==void 0?Number(t):void 0}function _i(t){return t!==void 0?BigInt(t):void 0}function eI(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function It(t){return!!t&&t.kind==AA.Kind.Audio}function Zt(t){return!!t&&t.kind==AA.Kind.Video}function zt(t){return eI(t)&&Zt(t)}function _t(t){return eI(t)&&It(t)}function tQ(t){return!!t&&!t.isLocal}function Dx(t){return!!t&&!t.isLocal}function iQ(t){return tQ(t)&&Zt(t)}function _x(t){return t.isLocal}function wx(t,A){const e=[];let g=new TextEncoder().encode(t);for(;g.length>A;){let i=A;for(;i>0;){const I=g[i];if(I!==void 0&&(I&192)!==128)break;i--}e.push(g.slice(0,i)),g=g.slice(i)}return g.length>0&&e.push(g),e}function ZE(t,A,e){var g,i,I,C;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:Q}=Ar(t??{}),n=A==null?void 0:A.processor,s=e==null?void 0:e.processor,B=o??{};return B.audio===!0&&(B.audio={}),B.video===!0&&(B.video={}),B.audio&&(IQ(B.audio,A),(g=(I=B.audio).deviceId)!==null&&g!==void 0||(I.deviceId={ideal:"default"}),(a||n)&&(B.audio.processor=a??n)),B.video&&(IQ(B.video,e),(i=(C=B.video).deviceId)!==null&&i!==void 0||(C.deviceId={ideal:"default"}),(Q||s)&&(B.video.processor=Q??s)),B}function IQ(t,A){return Object.keys(A).forEach(e=>{t[e]===void 0&&(t[e]=A[e])}),t}function CQ(t){var A,e,g,i;const I={};if(t.video)if(typeof t.video=="object"){const C={},o=C,a=t.video;Object.keys(a).forEach(Q=>{switch(Q){case"resolution":IQ(o,a.resolution);break;default:o[Q]=a[Q]}}),I.video=C,(A=(g=I.video).deviceId)!==null&&A!==void 0||(g.deviceId={ideal:"default"})}else I.video=t.video?{deviceId:{ideal:"default"}}:!1;else I.video=!1;return t.audio?typeof t.audio=="object"?(I.audio=t.audio,(e=(i=I.audio).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})):I.audio={deviceId:{ideal:"default"}}:I.audio=!1,I}function zE(t){return S(this,arguments,void 0,function(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const g=$E();if(g){const i=g.createAnalyser();i.fftSize=2048;const I=i.frequencyBinCount,C=new Uint8Array(I);g.createMediaStreamSource(new MediaStream([A.mediaStreamTrack])).connect(i),yield rg(e),i.getByteTimeDomainData(C);const a=C.some(Q=>Q!==128&&Q!==0);return g.close(),!a}return!1}()})}function $E(){var t;const A=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(A){const e=new A({latencyHint:"interactive"});if(e.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const g=()=>S(this,void 0,void 0,function*(){var i;try{e.state==="suspended"&&(yield e.resume())}catch(I){console.warn("Error trying to auto-resume audio context",I)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",g)});window.document.body.addEventListener("click",g)}return e}}function px(t){return t==="audioinput"?AA.Source.Microphone:t==="videoinput"?AA.Source.Camera:AA.Source.Unknown}function oQ(t){return t===AA.Source.Microphone?"audioinput":t===AA.Source.Camera?"videoinput":void 0}function mx(t){var A,e;let g=(A=t.video)!==null&&A!==void 0?A:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(g=typeof g=="boolean"?{}:g,Di()?g=Object.assign(Object.assign({},g),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):g=Object.assign(Object.assign({},g),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(e=t.audio)!==null&&e!==void 0?e:!1,video:g,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function AC(t){return t.split("/")[1].toLowerCase()}function yx(t){const A=[];return t.forEach(e=>{e.track!==void 0&&A.push(new Na({cid:e.track.mediaStreamID,track:e.trackInfo}))}),A}function WA(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?WA(t.track):{})}}function bx(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Nx(t,A){var e;t===void 0&&(t={}),A===void 0&&(A={});const g=[...Object.keys(A),...Object.keys(t)],i={};for(const I of g)t[I]!==A[I]&&(i[I]=(e=A[I])!==null&&e!==void 0?e:"");return i}function Ar(t){const A=Object.assign({},t);let e,g;return typeof A.audio=="object"&&A.audio.processor&&(e=A.audio.processor,A.audio=Object.assign(Object.assign({},A.audio),{processor:void 0})),typeof A.video=="object"&&A.video.processor&&(g=A.video.processor,A.video=Object.assign(Object.assign({},A.video),{processor:void 0})),{audioProcessor:e,videoProcessor:g,optionsWithoutProcessor:Zd(A)}}function Sx(t){switch(t){case ve.CAMERA:return AA.Source.Camera;case ve.MICROPHONE:return AA.Source.Microphone;case ve.SCREEN_SHARE:return AA.Source.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return AA.Source.ScreenShareAudio;default:return AA.Source.Unknown}}function er(t,A){return t.width*t.height<A.width*A.height}function kx(t,A){var e;return(e=t.layers)===null||e===void 0?void 0:e.find(g=>g.quality===A)}class Rx extends At.EventEmitter{constructor(A){super(),this.onWorkerMessage=e=>{var g,i;const{kind:I,data:C}=e.data;switch(I){case"error":$A.error(C.error.message),this.emit(jt.EncryptionError,C.error);break;case"initAck":C.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(C.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==C.enabled&&C.participantIdentity===((g=this.room)===null||g===void 0?void 0:g.localParticipant.identity))this.emit(jt.ParticipantEncryptionStatusChanged,C.enabled,this.room.localParticipant),this.encryptionEnabled=C.enabled;else if(C.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(C.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(C.participantIdentity));this.emit(jt.ParticipantEncryptionStatusChanged,C.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Vt.KeyRatcheted,C.ratchetResult,C.participantIdentity,C.keyIndex);break}},this.onWorkerError=e=>{$A.error("e2ee worker encountered an error:",{error:e.error}),this.emit(jt.EncryptionError,e.error)},this.keyProvider=A.keyProvider,this.worker=A.worker,this.encryptionEnabled=!1}setup(A){if(!jd())throw new Ta("tried to setup end-to-end encryption on an unsupported browser");if($A.info("setting up e2ee"),A!==this.room){this.room=A,this.setupEventListeners(A,this.keyProvider);const e={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Gd.getLevel()}};this.worker&&($A.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(A,e){$A.debug("set e2ee to ".concat(A," for participant ").concat(e)),this.postEnable(A,e)}setSifTrailer(A){!A||A.length===0?$A.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(A)}setupEngine(A){A.on(nA.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(A,e){A.on(tA.TrackPublished,(g,i)=>this.setParticipantCryptorEnabled(g.trackInfo.encryption!==lg.NONE,i.identity)),A.on(tA.ConnectionStateChanged,g=>{g===se.Connected&&A.remoteParticipants.forEach(i=>{i.trackPublications.forEach(I=>{this.setParticipantCryptorEnabled(I.trackInfo.encryption!==lg.NONE,i.identity)})})}).on(tA.TrackUnsubscribed,(g,i,I)=>{var C;const o={kind:"removeTransform",data:{participantIdentity:I.identity,trackId:g.mediaStreamID}};(C=this.worker)===null||C===void 0||C.postMessage(o)}).on(tA.TrackSubscribed,(g,i,I)=>{this.setupE2EEReceiver(g,I.identity,i.trackInfo)}).on(tA.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");e.getKeys().forEach(g=>{this.postKey(g)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),A.localParticipant.on(QA.LocalSenderCreated,(g,i)=>S(this,void 0,void 0,function*(){this.setupE2EESender(i,g)})),A.localParticipant.on(QA.LocalTrackPublished,g=>{if(!Zt(g.track)||!zI())return;const i={kind:"updateCodec",data:{trackId:g.track.mediaStreamID,codec:AC(g.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}),e.on(Vt.SetKey,g=>this.postKey(g)).on(Vt.RatchetRequest,(g,i)=>this.postRatchetRequest(g,i))}postRatchetRequest(A,e){if(!this.worker)throw Error("could not ratchet key, worker is missing");const g={kind:"ratchetRequest",data:{participantIdentity:A,keyIndex:e}};this.worker.postMessage(g)}postKey(A){let{key:e,participantIdentity:g,keyIndex:i}=A;var I;if(!this.worker)throw Error("could not set key, worker is missing");const C={kind:"setKey",data:{participantIdentity:g,isPublisher:g===((I=this.room)===null||I===void 0?void 0:I.localParticipant.identity),key:e,keyIndex:i}};this.worker.postMessage(C)}postEnable(A,e){if(this.worker){const g={kind:"enable",data:{enabled:A,participantIdentity:e}};this.worker.postMessage(g)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(A){var e;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((e=this.room)===null||e===void 0)&&e.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const g={kind:"setRTPMap",data:{map:A,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(g)}postSifTrailer(A){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const e={kind:"setSifTrailer",data:{trailer:A}};this.worker.postMessage(e)}setupE2EEReceiver(A,e,g){if(A.receiver){if(!(g!=null&&g.mimeType)||g.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(A.receiver,A.mediaStreamID,e,A.kind==="video"?AC(g.mimeType):void 0)}}setupE2EESender(A,e){if(!eI(A)||!e){e||$A.warn("early return because sender is not ready");return}this.handleSender(e,A.mediaStreamID,void 0)}handleReceiver(A,e,g,i){return S(this,void 0,void 0,function*(){if(this.worker){if(Ya()){const I={kind:"decode",participantIdentity:g,trackId:e,codec:i};A.transform=new RTCRtpScriptTransform(this.worker,I)}else{if(WI in A&&i){const a={kind:"updateCodec",data:{trackId:e,codec:i,participantIdentity:g}};this.worker.postMessage(a);return}let I=A.writableStream,C=A.readableStream;if(!I||!C){const a=A.createEncodedStreams();A.writableStream=a.writable,I=a.writable,A.readableStream=a.readable,C=a.readable}const o={kind:"decode",data:{readableStream:C,writableStream:I,trackId:e,codec:i,participantIdentity:g,isReuse:WI in A}};this.worker.postMessage(o,[C,I])}A[WI]=!0}})}handleSender(A,e,g){var i;if(!(WI in A||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ya()){$A.info("initialize script transform");const I={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:g};A.transform=new RTCRtpScriptTransform(this.worker,I)}else{$A.info("initialize encoded streams");const I=A.createEncodedStreams(),C={kind:"encode",data:{readableStream:I.readable,writableStream:I.writable,codec:g,trackId:e,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(C,[I.readable,I.writable])}A[WI]=!0}}}const aQ="default";class We{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new We),this.instance}get previousDevices(){return this._previousDevices}getDevices(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var I;if(((I=We.userMediaPromiseMap)===null||I===void 0?void 0:I.size)>0){$A.debug("awaiting getUserMedia promise");try{e?yield We.userMediaPromiseMap.get(e):yield Promise.all(We.userMediaPromiseMap.values())}catch{$A.warn("error waiting for media permissons")}}let C=yield navigator.mediaDevices.enumerateDevices();if(i&&!(Di()&&g.hasDeviceInUse(e))&&(C.filter(a=>a.kind===e).length===0||C.some(a=>{const Q=a.label==="",n=e?a.kind===e:!0;return Q&&n}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"&&{deviceId:{ideal:"default"}}},Q=yield navigator.mediaDevices.getUserMedia(a);C=yield navigator.mediaDevices.enumerateDevices(),Q.getTracks().forEach(n=>{n.stop()})}return g._previousDevices=C,e&&(C=C.filter(o=>o.kind===e)),C}()})}normalizeDeviceId(A,e,g){return S(this,void 0,void 0,function*(){if(e!==aQ)return e;const i=yield this.getDevices(A),I=i.find(o=>o.deviceId===aQ);if(!I){$A.warn("could not reliably determine default device");return}const C=i.find(o=>o.deviceId!==aQ&&o.groupId===(g??I.groupId));if(!C){$A.warn("could not reliably determine default device");return}return C==null?void 0:C.deviceId})}hasDeviceInUse(A){return A?We.userMediaPromiseMap.has(A):We.userMediaPromiseMap.size>0}}We.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],We.userMediaPromiseMap=new Map;var eC;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(eC||(eC={}));class Gx{constructor(){this.pendingTasks=new Map,this.taskMutex=new sg,this.nextTaskIndex=0}run(A){return S(this,void 0,void 0,function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eC.WAITING};this.pendingTasks.set(e.id,e);const g=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=eC.RUNNING,yield A()}finally{e.status=eC.COMPLETED,this.pendingTasks.delete(e.id),g()}})}flush(){return S(this,void 0,void 0,function*(){return this.run(()=>S(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function Mx(t,A){const e=new URL(lx(t));return A.forEach((g,i)=>{e.searchParams.set(i,g)}),gr(e,"rtc")}function Fx(t){const A=new URL(gQ(t));return gr(A,"validate")}function Ux(t){return t.endsWith("/")?t:"".concat(t,"/")}function gr(t,A){return t.pathname="".concat(Ux(t.pathname)).concat(A),t.toString()}const Lx=["syncState","trickle","offer","answer","simulate","leave"];function Kx(t){const A=Lx.indexOf(t.case)>=0;return $A.trace("request allowed to bypass queue:",{canPass:A,req:t}),A}var ye;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(ye||(ye={}));class QQ{get currentState(){return this.state}get isDisconnected(){return this.state===ye.DISCONNECTING||this.state===ye.DISCONNECTED}get isEstablishingConnection(){return this.state===ye.CONNECTING||this.state===ye.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var g;this.rtt=0,this.state=ye.DISCONNECTED,this.log=$A,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=lt((g=e.loggerName)!==null&&g!==void 0?g:vg.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=A,this.requestQueue=new Gx,this.queuedRequests=[],this.closingLock=new sg,this.connectionLock=new sg,this.state=ye.DISCONNECTED}get logContext(){var A,e;return(e=(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this))!==null&&e!==void 0?e:{}}join(A,e,g,i){return S(this,void 0,void 0,function*(){return this.state=ye.CONNECTING,this.options=g,yield this.connect(A,e,g,i)})}reconnect(A,e,g,i){return S(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=ye.RECONNECTING,this.clearPingInterval(),yield this.connect(A,e,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:g,reconnectReason:i}))})}connect(A,e,g,i){this.connectOptions=g;const I=dx(),C=vx(e,I,g),o=Mx(A,C),a=Fx(o);return new Promise((Q,n)=>S(this,void 0,void 0,function*(){const s=yield this.connectionLock.lock();try{const B=()=>S(this,void 0,void 0,function*(){this.close(),clearTimeout(E),n(new ue("room connection has been cancelled (signal)",ie.Cancelled))}),E=setTimeout(()=>{this.close(),n(new ue("room connection has timed out (signal)",ie.ServerUnreachable))},g.websocketTimeout);i!=null&&i.aborted&&B(),i==null||i.addEventListener("abort",B);const d=new URL(o);d.searchParams.has("access_token")&&d.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(d),Object.assign({reconnect:g.reconnect,reconnectReason:g.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(E)},this.ws.onerror=c=>S(this,void 0,void 0,function*(){if(this.state!==ye.CONNECTED){this.state=ye.DISCONNECTED,clearTimeout(E);try{const h=yield fetch(a);if(h.status.toFixed(0).startsWith("4")){const r=yield h.text();n(new ue(r,ie.NotAllowed,h.status))}else n(new ue("Encountered unknown websocket error during connection: ".concat(c.toString()),ie.InternalError,h.status))}catch(h){n(new ue(h instanceof Error?h.message:"server was not reachable",ie.ServerUnreachable))}return}this.handleWSError(c)}),this.ws.onmessage=c=>S(this,void 0,void 0,function*(){var h,r,f;let _;if(typeof c.data=="string"){const l=JSON.parse(c.data);_=UB.fromJson(l,{ignoreUnknownFields:!0})}else if(c.data instanceof ArrayBuffer)_=UB.fromBinary(new Uint8Array(c.data));else{this.log.error("could not decode websocket message: ".concat(typeof c.data),this.logContext);return}if(this.state!==ye.CONNECTED){let l=!1;if(((h=_.message)===null||h===void 0?void 0:h.case)==="join"?(this.state=ye.CONNECTED,i==null||i.removeEventListener("abort",B),this.pingTimeoutDuration=_.message.value.pingTimeout,this.pingIntervalDuration=_.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),Q(_.message.value)):this.state===ye.RECONNECTING&&_.message.case!=="leave"?(this.state=ye.CONNECTED,i==null||i.removeEventListener("abort",B),this.startPingInterval(),((r=_.message)===null||r===void 0?void 0:r.case)==="reconnect"?Q(_.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),Q(void 0),l=!0)):this.isEstablishingConnection&&_.message.case==="leave"?n(new ue("Received leave request while trying to (re)connect",ie.LeaveRequest,void 0,_.message.value.reason)):g.reconnect||n(new ue("did not receive join response, got ".concat((f=_.message)===null||f===void 0?void 0:f.case," instead"),ie.InternalError)),!l)return}this.signalLatency&&(yield rg(this.signalLatency)),this.handleSignalResponse(_)}),this.ws.onclose=c=>{this.isEstablishingConnection&&n(new ue("Websocket got closed during a (re)connection attempt",ie.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:c.reason,code:c.code,wasClean:c.wasClean,state:this.state})),this.handleOnClose(c.reason)}}finally{s()}}))}close(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const g=yield A.closingLock.lock();try{if(A.clearPingInterval(),e&&(A.state=ye.DISCONNECTING),A.ws){A.ws.onmessage=null,A.ws.onopen=null,A.ws.onclose=null;const i=new Promise(I=>{A.ws?A.ws.onclose=()=>{I()}:I()});A.ws.readyState<A.ws.CLOSING&&(A.ws.close(),yield Promise.race([i,rg(250)])),A.ws=void 0}}finally{e&&(A.state=ye.DISCONNECTED),g()}}()})}sendOffer(A,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:A.sdp})),this.sendRequest({case:"offer",value:to(A,e)})}sendAnswer(A,e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:A.sdp})),this.sendRequest({case:"answer",value:to(A,e)})}sendIceCandidate(A,e){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:A})),this.sendRequest({case:"trickle",value:new ya({candidateInit:JSON.stringify(A),target:e})})}sendMuteTrack(A,e){return this.sendRequest({case:"mute",value:new ba({sid:A,muted:e})})}sendAddTrack(A){return this.sendRequest({case:"addTrack",value:A})}sendUpdateLocalMetadata(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=I.getNextRequestId();return yield I.sendRequest({case:"updateMetadata",value:new JB({requestId:o,metadata:g,name:i,attributes:C})}),o}()})}sendUpdateTrackSettings(A){this.sendRequest({case:"trackSetting",value:A})}sendUpdateSubscription(A){return this.sendRequest({case:"subscription",value:A})}sendSyncState(A){return this.sendRequest({case:"syncState",value:A})}sendUpdateVideoLayers(A,e){return this.sendRequest({case:"updateLayers",value:new vB({trackSid:A,layers:e})})}sendUpdateSubscriptionPermissions(A,e){return this.sendRequest({case:"subscriptionPermission",value:new qB({allParticipants:A,trackPermissions:e})})}sendSimulateScenario(A){return this.sendRequest({case:"simulate",value:A})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ne.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new VB({timestamp:Ne.parse(Date.now()),rtt:Ne.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(A,e){return this.sendRequest({case:"updateAudioTrack",value:new KB({trackSid:A,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new PC({reason:Lg.CLIENT_INITIATED,action:Zi.DISCONNECT})})}sendRequest(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!Kx(e)&&g.state===ye.RECONNECTING){g.queuedRequests.push(()=>S(g,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(i||(yield g.requestQueue.flush()),g.signalLatency&&(yield rg(g.signalLatency)),g.isDisconnected){g.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));return}if(!g.ws||g.ws.readyState!==g.ws.OPEN){g.log.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case),g.logContext);return}const C=new ad({message:e});try{g.useJSON?g.ws.send(C.toJsonString()):g.ws.send(C.toBinary())}catch(o){g.log.error("error sending signal message",Object.assign(Object.assign({},g.logContext),{error:o}))}}()})}handleSignalResponse(A){var e,g;const i=A.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let I=!1;if(i.case==="answer"){const C=tr(i.value);this.onAnswer&&this.onAnswer(C,i.value.id)}else if(i.case==="offer"){const C=tr(i.value);this.onOffer&&this.onOffer(C,i.value.id)}else if(i.case==="trickle"){const C=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(C,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((e=i.value.participants)!==null&&e!==void 0?e:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((g=i.value.speakers)!==null&&g!==void 0?g:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),I=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));I||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const A=this.queuedRequests.shift();A&&this.requestQueue.run(A)}}handleOnClose(A){return S(this,void 0,void 0,function*(){if(this.state===ye.DISCONNECTED)return;const e=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(A),Object.assign(Object.assign({},this.logContext),{reason:A})),e&&e(A)})}handleWSError(A){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:A}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=ze.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&&ze.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=ze.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ze.clearInterval(this.pingInterval)}}function tr(t){const A={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":A.type=t.type;break}return A}function to(t,A){return new li({sdp:t.sdp,type:t.type,id:A})}function vx(t,A,e){var g;const i=new URLSearchParams;return i.set("access_token",t),e.reconnect&&(i.set("reconnect","1"),e.sid&&i.set("sid",e.sid)),i.set("auto_subscribe",e.autoSubscribe?"1":"0"),i.set("sdk",gt()?"reactnative":"js"),i.set("version",A.version),i.set("protocol",A.protocol.toString()),A.deviceModel&&i.set("device_model",A.deviceModel),A.os&&i.set("os",A.os),A.osVersion&&i.set("os_version",A.osVersion),A.browser&&i.set("browser",A.browser),A.browserVersion&&i.set("browser_version",A.browserVersion),e.adaptiveStream&&i.set("adaptive_stream","1"),e.reconnectReason&&i.set("reconnect_reason",e.reconnectReason.toString()),!((g=navigator.connection)===null||g===void 0)&&g.type&&i.set("network",navigator.connection.type),i}class ir{constructor(){this.buffer=[],this._totalSize=0}push(A){this.buffer.push(A),this._totalSize+=A.data.byteLength}pop(){const A=this.buffer.shift();return A&&(this._totalSize-=A.data.byteLength),A}getAll(){return this.buffer.slice()}popToSequence(A){for(;this.buffer.length>0&&this.buffer[0].sequence<=A;)this.pop()}alignBufferedAmount(A){for(;this.buffer.length>0;){const e=this.buffer[0];if(this._totalSize-e.data.byteLength<=A)break;this.pop()}}get length(){return this.buffer.length}}class Jx{constructor(A){this._map=new Map,this._lastCleanup=0,this.ttl=A}set(A,e){const g=Date.now();g-this._lastCleanup>this.ttl/2&&this.cleanup();const i=g+this.ttl;return this._map.set(A,{value:e,expiresAt:i}),this}get(A){const e=this._map.get(A);if(e){if(e.expiresAt<Date.now()){this._map.delete(A);return}return e.value}}has(A){const e=this._map.get(A);return e?e.expiresAt<Date.now()?(this._map.delete(A),!1):!0:!1}delete(A){return this._map.delete(A)}clear(){this._map.clear()}cleanup(){const A=Date.now();for(const[e,g]of this._map.entries())g.expiresAt<A&&this._map.delete(e);this._lastCleanup=A}get size(){return this.cleanup(),this._map.size}forEach(A){this.cleanup();for(const[e,g]of this._map.entries())g.expiresAt>=Date.now()&&A(g.value,e,this.asValueMap())}map(A){this.cleanup();const e=[],g=this.asValueMap();for(const[i,I]of g.entries())e.push(A(I,i,g));return e}asValueMap(){const A=new Map;for(const[e,g]of this._map.entries())g.expiresAt>=Date.now()&&A.set(e,g.value);return A}}var Yg={},nQ={},sQ={exports:{}},Ir;function BQ(){if(Ir)return sQ.exports;Ir=1;var t=sQ.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(A){return A.encoding?"rtpmap:%d %s/%s/%s":A.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(A){return A.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(A){return A.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(A){return"extmap:%d"+(A.direction?"/%s":"%v")+(A["encrypt-uri"]?" %s":"%v")+" %s"+(A.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(A){return A.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(A){var e="candidate:%s %d %s %d %s %d typ %s";return e+=A.raddr!=null?" raddr %s rport %d":"%v%v",e+=A.tcptype!=null?" tcptype %s":"%v",A.generation!=null&&(e+=" generation %d"),e+=A["network-id"]!=null?" network-id %d":"%v",e+=A["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(A){var e="ssrc:%d";return A.attribute!=null&&(e+=" %s",A.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(A){return A.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(A){return A.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(A){return"imageattr:%s %s %s"+(A.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(A){return"simulcast:%s %s"+(A.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(A){return"ts-refclk:%s"+(A.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(A){var e="mediaclk:";return e+=A.id!=null?"id=%s %s":"%v%s",e+=A.mediaClockValue!=null?"=%s":"",e+=A.rateNumerator!=null?" rate=%s":"",e+=A.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(A){var e=t[A];e.forEach(function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")})}),sQ.exports}var Cr;function Yx(){return Cr||(Cr=1,function(t){var A=function(o){return String(Number(o))===o?Number(o):o},e=function(o,a,Q,n){if(n&&!Q)a[n]=A(o[1]);else for(var s=0;s<Q.length;s+=1)o[s+1]!=null&&(a[Q[s]]=A(o[s+1]))},g=function(o,a,Q){var n=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:n&&!a[o.name]&&(a[o.name]={});var s=o.push?{}:n?a[o.name]:a;e(Q.match(o.reg),s,o.names,o.name),o.push&&a[o.push].push(s)},i=BQ(),I=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(o){var a={},Q=[],n=a;return o.split(/(\r\n|\r|\n)/).filter(I).forEach(function(s){var B=s[0],E=s.slice(2);B==="m"&&(Q.push({rtp:[],fmtp:[]}),n=Q[Q.length-1]);for(var d=0;d<(i[B]||[]).length;d+=1){var c=i[B][d];if(c.reg.test(E))return g(c,n,E)}}),a.media=Q,a};var C=function(o,a){var Q=a.split(/=(.+)/,2);return Q.length===2?o[Q[0]]=A(Q[1]):Q.length===1&&a.length>1&&(o[Q[0]]=void 0),o};t.parseParams=function(o){return o.split(/;\s?/).reduce(C,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(o){return o.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(o){for(var a=[],Q=o.split(" ").map(A),n=0;n<Q.length;n+=3)a.push({component:Q[n],ip:Q[n+1],port:Q[n+2]});return a},t.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(C,{})})},t.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(Q){var n,s=!1;return Q[0]!=="~"?n=A(Q):(n=A(Q.substring(1,Q.length)),s=!0),{scid:n,paused:s}})})}}(nQ)),nQ}var EQ,or;function Tx(){if(or)return EQ;or=1;var t=BQ(),A=/%[sdv%]/g,e=function(C){var o=1,a=arguments,Q=a.length;return C.replace(A,function(n){if(o>=Q)return n;var s=a[o];switch(o+=1,n){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},g=function(C,o,a){var Q=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,n=[C+"="+Q];if(o.names)for(var s=0;s<o.names.length;s+=1){var B=o.names[s];o.name?n.push(a[o.name][B]):n.push(a[o.names[s]])}else n.push(a[o.name]);return e.apply(null,n)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],I=["i","c","b","a"];return EQ=function(C,o){o=o||{},C.version==null&&(C.version=0),C.name==null&&(C.name=" "),C.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var a=o.outerOrder||i,Q=o.innerOrder||I,n=[];return a.forEach(function(s){t[s].forEach(function(B){B.name in C&&C[B.name]!=null?n.push(g(s,B,C)):B.push in C&&C[B.push]!=null&&C[B.push].forEach(function(E){n.push(g(s,B,E))})})}),C.media.forEach(function(s){n.push(g("m",t.m[0],s)),Q.forEach(function(B){t[B].forEach(function(E){E.name in s&&s[E.name]!=null?n.push(g(B,E,s)):E.push in s&&s[E.push]!=null&&s[E.push].forEach(function(d){n.push(g(B,E,d))})})})}),n.join(`\r
|
|
82
|
+
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:I}):i.sdp=I}return e.apply(this,arguments)}}function zC(t,A){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const e=t.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(A.browser==="chrome"&&A.version<78||A.browser==="firefox"&&A.version<68||A.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function $C(t,A){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const e=t.RTCPeerConnection.prototype.setLocalDescription;!e||e.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return e.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?e.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(C=>e.apply(this,[C]))})}var Hd=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ja,shimAddIceCandidateNullOrEmpty:zC,shimConnectionState:va,shimMaxMessageSize:XC,shimParameterlessSetLocalDescription:$C,shimRTCIceCandidate:WC,shimRTCIceCandidateRelayProtocol:Ka,shimSendThrowTypeError:ZC});function Pd(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const e=$B,g=Jd(t),i={browserDetails:g,commonShim:Hd,extractVersion:jI,disableLog:Kd,disableWarnings:vd,sdp:qd};switch(g.browser){case"chrome":if(!BE||!Fa||!A.shimChrome)return e("Chrome shim is not included in this adapter release."),i;if(g.version===null)return e("Chrome shim can not determine version, not shimming."),i;e("adapter.js shimming chrome."),i.browserShim=BE,zC(t,g),$C(t),iE(t,g),IE(t),Fa(t,g),CE(t),nE(t,g),oE(t),aE(t),sE(t,g),WC(t),Ka(t),va(t),XC(t,g),ZC(t),Ja(t,g);break;case"firefox":if(!_E||!Ua||!A.shimFirefox)return e("Firefox shim is not included in this adapter release."),i;e("adapter.js shimming firefox."),i.browserShim=_E,zC(t,g),$C(t),EE(t,g),Ua(t,g),rE(t),dE(t),cE(t),hE(t),xE(t),lE(t),fE(t),uE(t),DE(t),WC(t),va(t),XC(t,g),ZC(t);break;case"safari":if(!GE||!A.shimSafari)return e("Safari shim is not included in this adapter release."),i;e("adapter.js shimming safari."),i.browserShim=GE,zC(t,g),$C(t),NE(t),kE(t),mE(t),wE(t),pE(t),SE(t),yE(t),RE(t),WC(t),Ka(t),XC(t,g),ZC(t),Ja(t,g);break;default:e("Unsupported browser!");break}return i}Pd({window:typeof window>"u"?void 0:window});const Od=10,WI="lk_e2ee",Vd={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Od,keyringSize:16};var Vt;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(Vt||(Vt={}));var UE;(function(t){t.KeyRatcheted="keyRatcheted"})(UE||(UE={}));var jt;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(jt||(jt={}));var LE;(function(t){t.Error="cryptorError"})(LE||(LE={}));function jd(){return Wd()||Ya()}function Ya(){return typeof window.RTCRtpScriptTransform<"u"}function Wd(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Ep extends At.EventEmitter{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(e,g,i)=>{Ae.debug("key ratcheted event received",{ratchetResult:e,participantId:g,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Vd),A),this.on(Vt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(A,e,g){const i={key:A,participantIdentity:e,keyIndex:g};if(!this.options.sharedKey&&!e)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(e??"shared","-").concat(g??0),i),this.emit(Vt.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(A,e){this.emit(Vt.RatchetRequest,A,e)}}class ut extends Error{constructor(A,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=A}}var ie;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(ie||(ie={}));class ue extends ut{constructor(A,e,g,i){super(1,A),this.name="ConnectionError",this.status=g,this.reason=e,this.context=i,this.reasonName=ie[e]}}class Ta extends ut{constructor(A){super(21,A??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Dt extends ut{constructor(A){super(20,A??"track is invalid"),this.name="TrackInvalidError"}}class Xd extends ut{constructor(A){super(10,A??"unsupported server"),this.name="UnsupportedServer"}}class Pe extends ut{constructor(A){super(12,A??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class qa extends ut{constructor(A){super(13,A??"unable to negotiate"),this.name="NegotiationError"}}class KE extends ut{constructor(A,e){super(15,A),this.name="PublishTrackError",this.status=e}}class vE extends ut{constructor(A,e){super(15,A),this.reason=e,this.reasonName=typeof e=="string"?e:ka[e]}}var Jg;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"})(Jg||(Jg={}));class Wt extends ut{constructor(A,e){super(16,A),this.name="DataStreamError",this.reason=e,this.reasonName=Jg[e]}}var Ao;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Ao||(Ao={})),function(t){function A(e){if(e&&"name"in e)return e.name==="NotFoundError"||e.name==="DevicesNotFoundError"?t.NotFound:e.name==="NotAllowedError"||e.name==="PermissionDeniedError"?t.PermissionDenied:e.name==="NotReadableError"||e.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=A}(Ao||(Ao={}));var JE;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(JE||(JE={}));var tA;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(tA||(tA={}));var QA;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(QA||(QA={}));var nA;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(nA||(nA={}));var oA;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(oA||(oA={}));function Zd(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const zd=/version\/(\d+(\.?_?\d+)+)/i;let Ha;function fg(t){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const e=navigator.userAgent.toLowerCase();if(Ha===void 0||A){const g=$d.find(i=>{let{test:I}=i;return I.test(e)});Ha=g==null?void 0:g.describe(e)}return Ha}const $d=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:eo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Pa(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:eo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Pa(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:eo(zd,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Pa(t)}}}];function eo(t,A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const g=A.match(t);return g&&g.length>=e&&g[e]||""}function Pa(t){return t.includes("mac os")?eo(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var Ax="2.15.6";const ex=Ax,gx=16;class ze{}ze.setTimeout=function(){return setTimeout(...arguments)},ze.setInterval=function(){return setInterval(...arguments)},ze.clearTimeout=function(){return clearTimeout(...arguments)},ze.clearInterval=function(){return clearInterval(...arguments)};const tx=5e3,XI=[];var ug;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(ug||(ug={}));class AA extends At.EventEmitter{get streamState(){return this._streamState}setStreamState(A){this._streamState=A}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=AA.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ae,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),tx):this.handleAppVisibilityChanged()},this.log=lt((i=g.loggerName)!==null&&i!==void 0?i:vg.Track),this.loggerContextCb=g.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=A,this._mediaStreamID=A.id,this.source=AA.Source.Unknown}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),WA(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(A){let e="audio";this.kind===AA.Kind.Video&&(e="video"),this.attachedElements.length===0&&this.kind===AA.Kind.Video&&this.addAppVisibilityListener(),A||(e==="audio"&&(XI.forEach(I=>{I.parentElement===null&&!A&&(A=I)}),A&&XI.splice(XI.indexOf(A),1)),A||(A=document.createElement(e))),this.attachedElements.includes(A)||this.attachedElements.push(A),AI(this.mediaStreamTrack,A);const g=A.srcObject.getTracks(),i=g.some(I=>I.kind==="audio");return A.play().then(()=>{this.emit(i?oA.AudioPlaybackStarted:oA.VideoPlaybackStarted)}).catch(I=>{I.name==="NotAllowedError"?this.emit(i?oA.AudioPlaybackFailed:oA.VideoPlaybackFailed,I):I.name==="AbortError"?Ae.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):Ae.warn("could not playback ".concat(i?"audio":"video"),I),i&&A&&g.some(C=>C.kind==="video")&&I.name==="NotAllowedError"&&(A.muted=!0,A.play().catch(()=>{}))}),this.emit(oA.ElementAttached,A),A}detach(A){try{if(A){eI(this.mediaStreamTrack,A);const g=this.attachedElements.indexOf(A);return g>=0&&(this.attachedElements.splice(g,1),this.recycleElement(A),this.emit(oA.ElementDetached,A)),A}const e=[];return this.attachedElements.forEach(g=>{eI(this.mediaStreamTrack,g),e.push(g),this.recycleElement(g),this.emit(oA.ElementDetached,g)}),this.attachedElements=[],e}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(A){A.loggerName&&(this.log=lt(A.loggerName)),A.loggerContextCb&&(this.loggerContextCb=A.loggerContextCb)}recycleElement(A){if(A instanceof HTMLAudioElement){let e=!0;A.pause(),XI.forEach(g=>{g.parentElement||(e=!1)}),e&&XI.push(A)}}handleAppVisibilityChanged(){return S(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===AA.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(A=>A.play().catch(()=>{})),0)})}addAppVisibilityListener(){cg()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){cg()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function AI(t,A){let e;A.srcObject instanceof MediaStream?e=A.srcObject:e=new MediaStream;let g;t.kind==="audio"?g=e.getAudioTracks():g=e.getVideoTracks(),g.includes(t)||(g.forEach(i=>{e.removeTrack(i)}),e.addTrack(t)),(!Di()||!(A instanceof HTMLVideoElement))&&(A.autoplay=!0),A.muted=e.getAudioTracks().length===0,A instanceof HTMLVideoElement&&(A.playsInline=!0),A.srcObject!==e&&(A.srcObject=e,(Di()||ui())&&A instanceof HTMLVideoElement&&setTimeout(()=>{A.srcObject=e,A.play().catch(()=>{})},0))}function eI(t,A){if(A.srcObject instanceof MediaStream){const e=A.srcObject;e.removeTrack(t),e.getTracks().length>0?A.srcObject=e:A.srcObject=null}}(function(t){let A;(function(Q){Q.Audio="audio",Q.Video="video",Q.Unknown="unknown"})(A=t.Kind||(t.Kind={}));let e;(function(Q){Q.Camera="camera",Q.Microphone="microphone",Q.ScreenShare="screen_share",Q.ScreenShareAudio="screen_share_audio",Q.Unknown="unknown"})(e=t.Source||(t.Source={}));let g;(function(Q){Q.Active="active",Q.Paused="paused",Q.Unknown="unknown"})(g=t.StreamState||(t.StreamState={}));function i(Q){switch(Q){case A.Audio:return Ug.AUDIO;case A.Video:return Ug.VIDEO;default:return Ug.DATA}}t.kindToProto=i;function I(Q){switch(Q){case Ug.AUDIO:return A.Audio;case Ug.VIDEO:return A.Video;default:return A.Unknown}}t.kindFromProto=I;function C(Q){switch(Q){case e.Camera:return ve.CAMERA;case e.Microphone:return ve.MICROPHONE;case e.ScreenShare:return ve.SCREEN_SHARE;case e.ScreenShareAudio:return ve.SCREEN_SHARE_AUDIO;default:return ve.UNKNOWN}}t.sourceToProto=C;function o(Q){switch(Q){case ve.CAMERA:return e.Camera;case ve.MICROPHONE:return e.Microphone;case ve.SCREEN_SHARE:return e.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return e.ScreenShareAudio;default:return e.Unknown}}t.sourceFromProto=o;function a(Q){switch(Q){case wa.ACTIVE:return g.Active;case wa.PAUSED:return g.Paused;default:return g.Unknown}}t.streamStateFromProto=a})(AA||(AA={}));class xe{constructor(A,e,g,i,I){if(typeof A=="object")this.width=A.width,this.height=A.height,this.aspectRatio=A.aspectRatio,this.encoding={maxBitrate:A.maxBitrate,maxFramerate:A.maxFramerate,priority:A.priority};else if(e!==void 0&&g!==void 0)this.width=A,this.height=e,this.aspectRatio=A/e,this.encoding={maxBitrate:g,maxFramerate:i,priority:I};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 ix=["vp8","h264"],Ix=["vp8","h264","vp9","av1","h265"];function Cx(t){return!!ix.find(A=>A===t)}var YE;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(YE||(YE={}));var Oa;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(Oa||(Oa={}));const ZI={h90:new xe(160,90,9e4,20),h180:new xe(320,180,16e4,20),h216:new xe(384,216,18e4,20),h360:new xe(640,360,45e4,20),h540:new xe(960,540,8e5,25),h720:new xe(1280,720,17e5,30),h1080:new xe(1920,1080,3e6,30),h1440:new xe(2560,1440,5e6,30),h2160:new xe(3840,2160,8e6,30)},Va={h120:new xe(160,120,7e4,20),h180:new xe(240,180,125e3,20),h240:new xe(320,240,14e4,20),h360:new xe(480,360,33e4,20),h480:new xe(640,480,5e5,20),h540:new xe(720,540,6e5,25),h720:new xe(960,720,13e5,30),h1080:new xe(1440,1080,23e5,30),h1440:new xe(1920,1440,38e5,30)},ja={h360fps3:new xe(640,360,2e5,3,"medium"),h360fps15:new xe(640,360,4e5,15,"medium"),h720fps5:new xe(1280,720,8e5,5,"medium"),h720fps15:new xe(1280,720,15e5,15,"medium"),h720fps30:new xe(1280,720,2e6,30,"medium"),h1080fps15:new xe(1920,1080,25e5,15,"medium"),h1080fps30:new xe(1920,1080,5e6,30,"medium"),original:new xe(0,0,7e6,30,"medium")},ox="|",TE="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ax(t){const A=t.split(ox);return A.length>1?[A[0],t.substr(A[0].length+1)]:[t,""]}function rg(t){return S(this,void 0,void 0,function*(){return new Promise(A=>ze.setTimeout(A,t))})}function Wa(){return"addTransceiver"in RTCPeerConnection.prototype}function Xa(){return"addTrack"in RTCPeerConnection.prototype}function Qx(){if(!("getCapabilities"in RTCRtpSender)||Di()||ui())return!1;const t=RTCRtpSender.getCapabilities("video");let A=!1;if(t){for(const e of t.codecs)if(e.mimeType==="video/AV1"){A=!0;break}}return A}function nx(){if(!("getCapabilities"in RTCRtpSender)||ui())return!1;if(Di()){const e=fg();if(e!=null&&e.version&&tt(e.version,"16")<0||(e==null?void 0:e.os)==="iOS"&&(e!=null&&e.osVersion)&&tt(e.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let A=!1;if(t){for(const e of t.codecs)if(e.mimeType==="video/VP9"){A=!0;break}}return A}function et(t){return t==="av1"||t==="vp9"}function Za(t){return!document||zI()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function sx(){return typeof RTCPeerConnection>"u"?!1:Wa()||Xa()}function ui(){var t;return((t=fg())===null||t===void 0?void 0:t.name)==="Firefox"}function Di(){var t;return((t=fg())===null||t===void 0?void 0:t.name)==="Safari"}function zI(){const t=fg();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function Bx(){const t=fg();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&tt(t.osVersion,"17")>=0}function Ex(t){return t||(t=fg()),(t==null?void 0:t.name)==="Safari"&&tt(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&tt(t.osVersion,"18.3")>0}function qE(){var t,A;return cg()?(A=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&A!==void 0?A:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function rx(){const t=fg(),A="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&tt(t.osVersion,A)>=0?!0:t.name==="Safari"&&tt(t.version,A)>=0}function cg(){return typeof document<"u"}function gt(){return navigator.product=="ReactNative"}function za(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function HE(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function PE(){if(!gt())return;let t=HE();if(t)return t.platform}function OE(){if(cg())return window.devicePixelRatio;if(gt()){let t=HE();if(t)return t.devicePixelRatio}return 1}function tt(t,A){const e=t.split("."),g=A.split("."),i=Math.min(e.length,g.length);for(let I=0;I<i;++I){const C=parseInt(e[I],10),o=parseInt(g[I],10);if(C>o)return 1;if(C<o)return-1;if(I===i-1&&C===o)return 0}return t===""&&A!==""?-1:A===""?1:e.length==g.length?0:e.length<g.length?-1:1}function cx(t){for(const A of t)A.target.handleResize(A)}function hx(t){for(const A of t)A.target.handleVisibilityChanged(A)}let $a=null;const VE=()=>($a||($a=new ResizeObserver(cx)),$a);let AQ=null;const jE=()=>(AQ||(AQ=new IntersectionObserver(hx,{root:null,rootMargin:"0px"})),AQ);function dx(){var t;const A=new Id({sdk:SB.JS,protocol:gx,version:ex});return gt()&&(A.os=(t=PE())!==null&&t!==void 0?t:""),A}function WE(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=t,i.height=A;const I=i.getContext("2d");I==null||I.fillRect(0,0,i.width,i.height),g&&I&&(I.beginPath(),I.arc(t/2,A/2,50,0,Math.PI*2,!0),I.closePath(),I.fillStyle="grey",I.fill());const C=i.captureStream(),[o]=C.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=e,o}let $I;function eQ(){if(!$I){const t=new AudioContext,A=t.createOscillator(),e=t.createGain();e.gain.setValueAtTime(0,0);const g=t.createMediaStreamDestination();if(A.connect(e),e.connect(g),A.start(),[$I]=g.stream.getAudioTracks(),!$I)throw Error("Could not get empty media stream audio track");$I.enabled=!1}return $I.clone()}class it{get isResolved(){return this._isResolved}constructor(A,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise((g,i)=>S(this,void 0,void 0,function*(){this.resolve=g,this.reject=i,A&&(yield A(g,i))})).finally(()=>{var g;this._isResolved=!0,(g=this.onFinally)===null||g===void 0||g.call(this)})}}function xx(t){return Ix.includes(t)}function Xt(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function lx(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function gQ(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function fx(t,A){return t.segments.map(e=>{let{id:g,text:i,language:I,startTime:C,endTime:o,final:a}=e;var Q;const n=(Q=A.get(g))!==null&&Q!==void 0?Q:Date.now(),s=Date.now();return a?A.delete(g):A.set(g,n),{id:g,text:i,startTime:Number.parseInt(C.toString()),endTime:Number.parseInt(o.toString()),final:a,language:I,firstReceivedTime:n,lastReceivedTime:s}})}function ux(t){const{id:A,timestamp:e,message:g,editTimestamp:i}=t;return{id:A,timestamp:Number.parseInt(e.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:g}}function XE(t){switch(t.reason){case ie.LeaveRequest:return t.context;case ie.Cancelled:return Lg.CLIENT_INITIATED;case ie.NotAllowed:return Lg.USER_REJECTED;case ie.ServerUnreachable:return Lg.JOIN_FAILURE;default:return Lg.UNKNOWN_REASON}}function go(t){return t!==void 0?Number(t):void 0}function _i(t){return t!==void 0?BigInt(t):void 0}function gI(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function It(t){return!!t&&t.kind==AA.Kind.Audio}function Zt(t){return!!t&&t.kind==AA.Kind.Video}function zt(t){return gI(t)&&Zt(t)}function _t(t){return gI(t)&&It(t)}function tQ(t){return!!t&&!t.isLocal}function Dx(t){return!!t&&!t.isLocal}function iQ(t){return tQ(t)&&Zt(t)}function _x(t){return t.isLocal}function wx(t,A){const e=[];let g=new TextEncoder().encode(t);for(;g.length>A;){let i=A;for(;i>0;){const I=g[i];if(I!==void 0&&(I&192)!==128)break;i--}e.push(g.slice(0,i)),g=g.slice(i)}return g.length>0&&e.push(g),e}function ZE(t,A,e){var g,i,I,C;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:Q}=Ar(t??{}),n=A==null?void 0:A.processor,s=e==null?void 0:e.processor,B=o??{};return B.audio===!0&&(B.audio={}),B.video===!0&&(B.video={}),B.audio&&(IQ(B.audio,A),(g=(I=B.audio).deviceId)!==null&&g!==void 0||(I.deviceId={ideal:"default"}),(a||n)&&(B.audio.processor=a??n)),B.video&&(IQ(B.video,e),(i=(C=B.video).deviceId)!==null&&i!==void 0||(C.deviceId={ideal:"default"}),(Q||s)&&(B.video.processor=Q??s)),B}function IQ(t,A){return Object.keys(A).forEach(e=>{t[e]===void 0&&(t[e]=A[e])}),t}function CQ(t){var A,e,g,i;const I={};if(t.video)if(typeof t.video=="object"){const C={},o=C,a=t.video;Object.keys(a).forEach(Q=>{switch(Q){case"resolution":IQ(o,a.resolution);break;default:o[Q]=a[Q]}}),I.video=C,(A=(g=I.video).deviceId)!==null&&A!==void 0||(g.deviceId={ideal:"default"})}else I.video=t.video?{deviceId:{ideal:"default"}}:!1;else I.video=!1;return t.audio?typeof t.audio=="object"?(I.audio=t.audio,(e=(i=I.audio).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})):I.audio={deviceId:{ideal:"default"}}:I.audio=!1,I}function zE(t){return S(this,arguments,void 0,function(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const g=$E();if(g){const i=g.createAnalyser();i.fftSize=2048;const I=i.frequencyBinCount,C=new Uint8Array(I);g.createMediaStreamSource(new MediaStream([A.mediaStreamTrack])).connect(i),yield rg(e),i.getByteTimeDomainData(C);const a=C.some(Q=>Q!==128&&Q!==0);return g.close(),!a}return!1}()})}function $E(){var t;const A=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(A){const e=new A({latencyHint:"interactive"});if(e.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const g=()=>S(this,void 0,void 0,function*(){var i;try{e.state==="suspended"&&(yield e.resume())}catch(I){console.warn("Error trying to auto-resume audio context",I)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",g)});window.document.body.addEventListener("click",g)}return e}}function px(t){return t==="audioinput"?AA.Source.Microphone:t==="videoinput"?AA.Source.Camera:AA.Source.Unknown}function oQ(t){return t===AA.Source.Microphone?"audioinput":t===AA.Source.Camera?"videoinput":void 0}function mx(t){var A,e;let g=(A=t.video)!==null&&A!==void 0?A:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(g=typeof g=="boolean"?{}:g,Di()?g=Object.assign(Object.assign({},g),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):g=Object.assign(Object.assign({},g),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(e=t.audio)!==null&&e!==void 0?e:!1,video:g,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function AC(t){return t.split("/")[1].toLowerCase()}function yx(t){const A=[];return t.forEach(e=>{e.track!==void 0&&A.push(new Na({cid:e.track.mediaStreamID,track:e.trackInfo}))}),A}function WA(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?WA(t.track):{})}}function bx(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Nx(t,A){var e;t===void 0&&(t={}),A===void 0&&(A={});const g=[...Object.keys(A),...Object.keys(t)],i={};for(const I of g)t[I]!==A[I]&&(i[I]=(e=A[I])!==null&&e!==void 0?e:"");return i}function Ar(t){const A=Object.assign({},t);let e,g;return typeof A.audio=="object"&&A.audio.processor&&(e=A.audio.processor,A.audio=Object.assign(Object.assign({},A.audio),{processor:void 0})),typeof A.video=="object"&&A.video.processor&&(g=A.video.processor,A.video=Object.assign(Object.assign({},A.video),{processor:void 0})),{audioProcessor:e,videoProcessor:g,optionsWithoutProcessor:Zd(A)}}function Sx(t){switch(t){case ve.CAMERA:return AA.Source.Camera;case ve.MICROPHONE:return AA.Source.Microphone;case ve.SCREEN_SHARE:return AA.Source.ScreenShare;case ve.SCREEN_SHARE_AUDIO:return AA.Source.ScreenShareAudio;default:return AA.Source.Unknown}}function er(t,A){return t.width*t.height<A.width*A.height}function kx(t,A){var e;return(e=t.layers)===null||e===void 0?void 0:e.find(g=>g.quality===A)}class Rx extends At.EventEmitter{constructor(A){super(),this.onWorkerMessage=e=>{var g,i;const{kind:I,data:C}=e.data;switch(I){case"error":Ae.error(C.error.message),this.emit(jt.EncryptionError,C.error);break;case"initAck":C.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(C.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==C.enabled&&C.participantIdentity===((g=this.room)===null||g===void 0?void 0:g.localParticipant.identity))this.emit(jt.ParticipantEncryptionStatusChanged,C.enabled,this.room.localParticipant),this.encryptionEnabled=C.enabled;else if(C.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(C.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(C.participantIdentity));this.emit(jt.ParticipantEncryptionStatusChanged,C.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Vt.KeyRatcheted,C.ratchetResult,C.participantIdentity,C.keyIndex);break}},this.onWorkerError=e=>{Ae.error("e2ee worker encountered an error:",{error:e.error}),this.emit(jt.EncryptionError,e.error)},this.keyProvider=A.keyProvider,this.worker=A.worker,this.encryptionEnabled=!1}setup(A){if(!jd())throw new Ta("tried to setup end-to-end encryption on an unsupported browser");if(Ae.info("setting up e2ee"),A!==this.room){this.room=A,this.setupEventListeners(A,this.keyProvider);const e={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Gd.getLevel()}};this.worker&&(Ae.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(A,e){Ae.debug("set e2ee to ".concat(A," for participant ").concat(e)),this.postEnable(A,e)}setSifTrailer(A){!A||A.length===0?Ae.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(A)}setupEngine(A){A.on(nA.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(A,e){A.on(tA.TrackPublished,(g,i)=>this.setParticipantCryptorEnabled(g.trackInfo.encryption!==lg.NONE,i.identity)),A.on(tA.ConnectionStateChanged,g=>{g===se.Connected&&A.remoteParticipants.forEach(i=>{i.trackPublications.forEach(I=>{this.setParticipantCryptorEnabled(I.trackInfo.encryption!==lg.NONE,i.identity)})})}).on(tA.TrackUnsubscribed,(g,i,I)=>{var C;const o={kind:"removeTransform",data:{participantIdentity:I.identity,trackId:g.mediaStreamID}};(C=this.worker)===null||C===void 0||C.postMessage(o)}).on(tA.TrackSubscribed,(g,i,I)=>{this.setupE2EEReceiver(g,I.identity,i.trackInfo)}).on(tA.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");e.getKeys().forEach(g=>{this.postKey(g)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),A.localParticipant.on(QA.LocalSenderCreated,(g,i)=>S(this,void 0,void 0,function*(){this.setupE2EESender(i,g)})),A.localParticipant.on(QA.LocalTrackPublished,g=>{if(!Zt(g.track)||!zI())return;const i={kind:"updateCodec",data:{trackId:g.track.mediaStreamID,codec:AC(g.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}),e.on(Vt.SetKey,g=>this.postKey(g)).on(Vt.RatchetRequest,(g,i)=>this.postRatchetRequest(g,i))}postRatchetRequest(A,e){if(!this.worker)throw Error("could not ratchet key, worker is missing");const g={kind:"ratchetRequest",data:{participantIdentity:A,keyIndex:e}};this.worker.postMessage(g)}postKey(A){let{key:e,participantIdentity:g,keyIndex:i}=A;var I;if(!this.worker)throw Error("could not set key, worker is missing");const C={kind:"setKey",data:{participantIdentity:g,isPublisher:g===((I=this.room)===null||I===void 0?void 0:I.localParticipant.identity),key:e,keyIndex:i}};this.worker.postMessage(C)}postEnable(A,e){if(this.worker){const g={kind:"enable",data:{enabled:A,participantIdentity:e}};this.worker.postMessage(g)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(A){var e;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((e=this.room)===null||e===void 0)&&e.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const g={kind:"setRTPMap",data:{map:A,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(g)}postSifTrailer(A){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const e={kind:"setSifTrailer",data:{trailer:A}};this.worker.postMessage(e)}setupE2EEReceiver(A,e,g){if(A.receiver){if(!(g!=null&&g.mimeType)||g.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(A.receiver,A.mediaStreamID,e,A.kind==="video"?AC(g.mimeType):void 0)}}setupE2EESender(A,e){if(!gI(A)||!e){e||Ae.warn("early return because sender is not ready");return}this.handleSender(e,A.mediaStreamID,void 0)}handleReceiver(A,e,g,i){return S(this,void 0,void 0,function*(){if(this.worker){if(Ya()){const I={kind:"decode",participantIdentity:g,trackId:e,codec:i};A.transform=new RTCRtpScriptTransform(this.worker,I)}else{if(WI in A&&i){const a={kind:"updateCodec",data:{trackId:e,codec:i,participantIdentity:g}};this.worker.postMessage(a);return}let I=A.writableStream,C=A.readableStream;if(!I||!C){const a=A.createEncodedStreams();A.writableStream=a.writable,I=a.writable,A.readableStream=a.readable,C=a.readable}const o={kind:"decode",data:{readableStream:C,writableStream:I,trackId:e,codec:i,participantIdentity:g,isReuse:WI in A}};this.worker.postMessage(o,[C,I])}A[WI]=!0}})}handleSender(A,e,g){var i;if(!(WI in A||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ya()){Ae.info("initialize script transform");const I={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:g};A.transform=new RTCRtpScriptTransform(this.worker,I)}else{Ae.info("initialize encoded streams");const I=A.createEncodedStreams(),C={kind:"encode",data:{readableStream:I.readable,writableStream:I.writable,codec:g,trackId:e,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(C,[I.readable,I.writable])}A[WI]=!0}}}const aQ="default";class We{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new We),this.instance}get previousDevices(){return this._previousDevices}getDevices(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var I;if(((I=We.userMediaPromiseMap)===null||I===void 0?void 0:I.size)>0){Ae.debug("awaiting getUserMedia promise");try{e?yield We.userMediaPromiseMap.get(e):yield Promise.all(We.userMediaPromiseMap.values())}catch{Ae.warn("error waiting for media permissons")}}let C=yield navigator.mediaDevices.enumerateDevices();if(i&&!(Di()&&g.hasDeviceInUse(e))&&(C.filter(a=>a.kind===e).length===0||C.some(a=>{const Q=a.label==="",n=e?a.kind===e:!0;return Q&&n}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"&&{deviceId:{ideal:"default"}}},Q=yield navigator.mediaDevices.getUserMedia(a);C=yield navigator.mediaDevices.enumerateDevices(),Q.getTracks().forEach(n=>{n.stop()})}return g._previousDevices=C,e&&(C=C.filter(o=>o.kind===e)),C}()})}normalizeDeviceId(A,e,g){return S(this,void 0,void 0,function*(){if(e!==aQ)return e;const i=yield this.getDevices(A),I=i.find(o=>o.deviceId===aQ);if(!I){Ae.warn("could not reliably determine default device");return}const C=i.find(o=>o.deviceId!==aQ&&o.groupId===(g??I.groupId));if(!C){Ae.warn("could not reliably determine default device");return}return C==null?void 0:C.deviceId})}hasDeviceInUse(A){return A?We.userMediaPromiseMap.has(A):We.userMediaPromiseMap.size>0}}We.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],We.userMediaPromiseMap=new Map;var eC;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(eC||(eC={}));class Gx{constructor(){this.pendingTasks=new Map,this.taskMutex=new sg,this.nextTaskIndex=0}run(A){return S(this,void 0,void 0,function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eC.WAITING};this.pendingTasks.set(e.id,e);const g=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=eC.RUNNING,yield A()}finally{e.status=eC.COMPLETED,this.pendingTasks.delete(e.id),g()}})}flush(){return S(this,void 0,void 0,function*(){return this.run(()=>S(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function Mx(t,A){const e=new URL(lx(t));return A.forEach((g,i)=>{e.searchParams.set(i,g)}),gr(e,"rtc")}function Fx(t){const A=new URL(gQ(t));return gr(A,"validate")}function Ux(t){return t.endsWith("/")?t:"".concat(t,"/")}function gr(t,A){return t.pathname="".concat(Ux(t.pathname)).concat(A),t.toString()}const Lx=["syncState","trickle","offer","answer","simulate","leave"];function Kx(t){const A=Lx.indexOf(t.case)>=0;return Ae.trace("request allowed to bypass queue:",{canPass:A,req:t}),A}var ye;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(ye||(ye={}));class QQ{get currentState(){return this.state}get isDisconnected(){return this.state===ye.DISCONNECTING||this.state===ye.DISCONNECTED}get isEstablishingConnection(){return this.state===ye.CONNECTING||this.state===ye.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var g;this.rtt=0,this.state=ye.DISCONNECTED,this.log=Ae,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=lt((g=e.loggerName)!==null&&g!==void 0?g:vg.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=A,this.requestQueue=new Gx,this.queuedRequests=[],this.closingLock=new sg,this.connectionLock=new sg,this.state=ye.DISCONNECTED}get logContext(){var A,e;return(e=(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this))!==null&&e!==void 0?e:{}}join(A,e,g,i){return S(this,void 0,void 0,function*(){return this.state=ye.CONNECTING,this.options=g,yield this.connect(A,e,g,i)})}reconnect(A,e,g,i){return S(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=ye.RECONNECTING,this.clearPingInterval(),yield this.connect(A,e,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:g,reconnectReason:i}))})}connect(A,e,g,i){this.connectOptions=g;const I=dx(),C=vx(e,I,g),o=Mx(A,C),a=Fx(o);return new Promise((Q,n)=>S(this,void 0,void 0,function*(){const s=yield this.connectionLock.lock();try{const B=()=>S(this,void 0,void 0,function*(){this.close(),clearTimeout(E),n(new ue("room connection has been cancelled (signal)",ie.Cancelled))}),E=setTimeout(()=>{this.close(),n(new ue("room connection has timed out (signal)",ie.ServerUnreachable))},g.websocketTimeout);i!=null&&i.aborted&&B(),i==null||i.addEventListener("abort",B);const d=new URL(o);d.searchParams.has("access_token")&&d.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(d),Object.assign({reconnect:g.reconnect,reconnectReason:g.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(E)},this.ws.onerror=c=>S(this,void 0,void 0,function*(){if(this.state!==ye.CONNECTED){this.state=ye.DISCONNECTED,clearTimeout(E);try{const h=yield fetch(a);if(h.status.toFixed(0).startsWith("4")){const r=yield h.text();n(new ue(r,ie.NotAllowed,h.status))}else n(new ue("Encountered unknown websocket error during connection: ".concat(c.toString()),ie.InternalError,h.status))}catch(h){n(new ue(h instanceof Error?h.message:"server was not reachable",ie.ServerUnreachable))}return}this.handleWSError(c)}),this.ws.onmessage=c=>S(this,void 0,void 0,function*(){var h,r,f;let _;if(typeof c.data=="string"){const l=JSON.parse(c.data);_=UB.fromJson(l,{ignoreUnknownFields:!0})}else if(c.data instanceof ArrayBuffer)_=UB.fromBinary(new Uint8Array(c.data));else{this.log.error("could not decode websocket message: ".concat(typeof c.data),this.logContext);return}if(this.state!==ye.CONNECTED){let l=!1;if(((h=_.message)===null||h===void 0?void 0:h.case)==="join"?(this.state=ye.CONNECTED,i==null||i.removeEventListener("abort",B),this.pingTimeoutDuration=_.message.value.pingTimeout,this.pingIntervalDuration=_.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),Q(_.message.value)):this.state===ye.RECONNECTING&&_.message.case!=="leave"?(this.state=ye.CONNECTED,i==null||i.removeEventListener("abort",B),this.startPingInterval(),((r=_.message)===null||r===void 0?void 0:r.case)==="reconnect"?Q(_.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),Q(void 0),l=!0)):this.isEstablishingConnection&&_.message.case==="leave"?n(new ue("Received leave request while trying to (re)connect",ie.LeaveRequest,void 0,_.message.value.reason)):g.reconnect||n(new ue("did not receive join response, got ".concat((f=_.message)===null||f===void 0?void 0:f.case," instead"),ie.InternalError)),!l)return}this.signalLatency&&(yield rg(this.signalLatency)),this.handleSignalResponse(_)}),this.ws.onclose=c=>{this.isEstablishingConnection&&n(new ue("Websocket got closed during a (re)connection attempt",ie.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:c.reason,code:c.code,wasClean:c.wasClean,state:this.state})),this.handleOnClose(c.reason)}}finally{s()}}))}close(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const g=yield A.closingLock.lock();try{if(A.clearPingInterval(),e&&(A.state=ye.DISCONNECTING),A.ws){A.ws.onmessage=null,A.ws.onopen=null,A.ws.onclose=null;const i=new Promise(I=>{A.ws?A.ws.onclose=()=>{I()}:I()});A.ws.readyState<A.ws.CLOSING&&(A.ws.close(),yield Promise.race([i,rg(250)])),A.ws=void 0}}finally{e&&(A.state=ye.DISCONNECTED),g()}}()})}sendOffer(A,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:A.sdp})),this.sendRequest({case:"offer",value:to(A,e)})}sendAnswer(A,e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:A.sdp})),this.sendRequest({case:"answer",value:to(A,e)})}sendIceCandidate(A,e){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:A})),this.sendRequest({case:"trickle",value:new ya({candidateInit:JSON.stringify(A),target:e})})}sendMuteTrack(A,e){return this.sendRequest({case:"mute",value:new ba({sid:A,muted:e})})}sendAddTrack(A){return this.sendRequest({case:"addTrack",value:A})}sendUpdateLocalMetadata(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=I.getNextRequestId();return yield I.sendRequest({case:"updateMetadata",value:new JB({requestId:o,metadata:g,name:i,attributes:C})}),o}()})}sendUpdateTrackSettings(A){this.sendRequest({case:"trackSetting",value:A})}sendUpdateSubscription(A){return this.sendRequest({case:"subscription",value:A})}sendSyncState(A){return this.sendRequest({case:"syncState",value:A})}sendUpdateVideoLayers(A,e){return this.sendRequest({case:"updateLayers",value:new vB({trackSid:A,layers:e})})}sendUpdateSubscriptionPermissions(A,e){return this.sendRequest({case:"subscriptionPermission",value:new qB({allParticipants:A,trackPermissions:e})})}sendSimulateScenario(A){return this.sendRequest({case:"simulate",value:A})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ne.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new VB({timestamp:Ne.parse(Date.now()),rtt:Ne.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(A,e){return this.sendRequest({case:"updateAudioTrack",value:new KB({trackSid:A,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new PC({reason:Lg.CLIENT_INITIATED,action:zi.DISCONNECT})})}sendRequest(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!Kx(e)&&g.state===ye.RECONNECTING){g.queuedRequests.push(()=>S(g,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(i||(yield g.requestQueue.flush()),g.signalLatency&&(yield rg(g.signalLatency)),g.isDisconnected){g.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));return}if(!g.ws||g.ws.readyState!==g.ws.OPEN){g.log.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case),g.logContext);return}const C=new ad({message:e});try{g.useJSON?g.ws.send(C.toJsonString()):g.ws.send(C.toBinary())}catch(o){g.log.error("error sending signal message",Object.assign(Object.assign({},g.logContext),{error:o}))}}()})}handleSignalResponse(A){var e,g;const i=A.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let I=!1;if(i.case==="answer"){const C=tr(i.value);this.onAnswer&&this.onAnswer(C,i.value.id)}else if(i.case==="offer"){const C=tr(i.value);this.onOffer&&this.onOffer(C,i.value.id)}else if(i.case==="trickle"){const C=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(C,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((e=i.value.participants)!==null&&e!==void 0?e:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((g=i.value.speakers)!==null&&g!==void 0?g:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),I=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));I||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const A=this.queuedRequests.shift();A&&this.requestQueue.run(A)}}handleOnClose(A){return S(this,void 0,void 0,function*(){if(this.state===ye.DISCONNECTED)return;const e=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(A),Object.assign(Object.assign({},this.logContext),{reason:A})),e&&e(A)})}handleWSError(A){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:A}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=ze.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&&ze.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=ze.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ze.clearInterval(this.pingInterval)}}function tr(t){const A={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":A.type=t.type;break}return A}function to(t,A){return new li({sdp:t.sdp,type:t.type,id:A})}function vx(t,A,e){var g;const i=new URLSearchParams;return i.set("access_token",t),e.reconnect&&(i.set("reconnect","1"),e.sid&&i.set("sid",e.sid)),i.set("auto_subscribe",e.autoSubscribe?"1":"0"),i.set("sdk",gt()?"reactnative":"js"),i.set("version",A.version),i.set("protocol",A.protocol.toString()),A.deviceModel&&i.set("device_model",A.deviceModel),A.os&&i.set("os",A.os),A.osVersion&&i.set("os_version",A.osVersion),A.browser&&i.set("browser",A.browser),A.browserVersion&&i.set("browser_version",A.browserVersion),e.adaptiveStream&&i.set("adaptive_stream","1"),e.reconnectReason&&i.set("reconnect_reason",e.reconnectReason.toString()),!((g=navigator.connection)===null||g===void 0)&&g.type&&i.set("network",navigator.connection.type),i}class ir{constructor(){this.buffer=[],this._totalSize=0}push(A){this.buffer.push(A),this._totalSize+=A.data.byteLength}pop(){const A=this.buffer.shift();return A&&(this._totalSize-=A.data.byteLength),A}getAll(){return this.buffer.slice()}popToSequence(A){for(;this.buffer.length>0&&this.buffer[0].sequence<=A;)this.pop()}alignBufferedAmount(A){for(;this.buffer.length>0;){const e=this.buffer[0];if(this._totalSize-e.data.byteLength<=A)break;this.pop()}}get length(){return this.buffer.length}}class Jx{constructor(A){this._map=new Map,this._lastCleanup=0,this.ttl=A}set(A,e){const g=Date.now();g-this._lastCleanup>this.ttl/2&&this.cleanup();const i=g+this.ttl;return this._map.set(A,{value:e,expiresAt:i}),this}get(A){const e=this._map.get(A);if(e){if(e.expiresAt<Date.now()){this._map.delete(A);return}return e.value}}has(A){const e=this._map.get(A);return e?e.expiresAt<Date.now()?(this._map.delete(A),!1):!0:!1}delete(A){return this._map.delete(A)}clear(){this._map.clear()}cleanup(){const A=Date.now();for(const[e,g]of this._map.entries())g.expiresAt<A&&this._map.delete(e);this._lastCleanup=A}get size(){return this.cleanup(),this._map.size}forEach(A){this.cleanup();for(const[e,g]of this._map.entries())g.expiresAt>=Date.now()&&A(g.value,e,this.asValueMap())}map(A){this.cleanup();const e=[],g=this.asValueMap();for(const[i,I]of g.entries())e.push(A(I,i,g));return e}asValueMap(){const A=new Map;for(const[e,g]of this._map.entries())g.expiresAt>=Date.now()&&A.set(e,g.value);return A}}var Yg={},nQ={},sQ={exports:{}},Ir;function BQ(){if(Ir)return sQ.exports;Ir=1;var t=sQ.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(A){return A.encoding?"rtpmap:%d %s/%s/%s":A.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(A){return A.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(A){return A.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(A){return"extmap:%d"+(A.direction?"/%s":"%v")+(A["encrypt-uri"]?" %s":"%v")+" %s"+(A.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(A){return A.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(A){var e="candidate:%s %d %s %d %s %d typ %s";return e+=A.raddr!=null?" raddr %s rport %d":"%v%v",e+=A.tcptype!=null?" tcptype %s":"%v",A.generation!=null&&(e+=" generation %d"),e+=A["network-id"]!=null?" network-id %d":"%v",e+=A["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(A){var e="ssrc:%d";return A.attribute!=null&&(e+=" %s",A.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(A){return A.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(A){return A.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(A){return"imageattr:%s %s %s"+(A.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(A){return"simulcast:%s %s"+(A.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(A){return"ts-refclk:%s"+(A.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(A){var e="mediaclk:";return e+=A.id!=null?"id=%s %s":"%v%s",e+=A.mediaClockValue!=null?"=%s":"",e+=A.rateNumerator!=null?" rate=%s":"",e+=A.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(A){var e=t[A];e.forEach(function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")})}),sQ.exports}var Cr;function Yx(){return Cr||(Cr=1,function(t){var A=function(o){return String(Number(o))===o?Number(o):o},e=function(o,a,Q,n){if(n&&!Q)a[n]=A(o[1]);else for(var s=0;s<Q.length;s+=1)o[s+1]!=null&&(a[Q[s]]=A(o[s+1]))},g=function(o,a,Q){var n=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:n&&!a[o.name]&&(a[o.name]={});var s=o.push?{}:n?a[o.name]:a;e(Q.match(o.reg),s,o.names,o.name),o.push&&a[o.push].push(s)},i=BQ(),I=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(o){var a={},Q=[],n=a;return o.split(/(\r\n|\r|\n)/).filter(I).forEach(function(s){var B=s[0],E=s.slice(2);B==="m"&&(Q.push({rtp:[],fmtp:[]}),n=Q[Q.length-1]);for(var d=0;d<(i[B]||[]).length;d+=1){var c=i[B][d];if(c.reg.test(E))return g(c,n,E)}}),a.media=Q,a};var C=function(o,a){var Q=a.split(/=(.+)/,2);return Q.length===2?o[Q[0]]=A(Q[1]):Q.length===1&&a.length>1&&(o[Q[0]]=void 0),o};t.parseParams=function(o){return o.split(/;\s?/).reduce(C,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(o){return o.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(o){for(var a=[],Q=o.split(" ").map(A),n=0;n<Q.length;n+=3)a.push({component:Q[n],ip:Q[n+1],port:Q[n+2]});return a},t.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(C,{})})},t.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(Q){var n,s=!1;return Q[0]!=="~"?n=A(Q):(n=A(Q.substring(1,Q.length)),s=!0),{scid:n,paused:s}})})}}(nQ)),nQ}var EQ,or;function Tx(){if(or)return EQ;or=1;var t=BQ(),A=/%[sdv%]/g,e=function(C){var o=1,a=arguments,Q=a.length;return C.replace(A,function(n){if(o>=Q)return n;var s=a[o];switch(o+=1,n){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},g=function(C,o,a){var Q=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,n=[C+"="+Q];if(o.names)for(var s=0;s<o.names.length;s+=1){var B=o.names[s];o.name?n.push(a[o.name][B]):n.push(a[o.names[s]])}else n.push(a[o.name]);return e.apply(null,n)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],I=["i","c","b","a"];return EQ=function(C,o){o=o||{},C.version==null&&(C.version=0),C.name==null&&(C.name=" "),C.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var a=o.outerOrder||i,Q=o.innerOrder||I,n=[];return a.forEach(function(s){t[s].forEach(function(B){B.name in C&&C[B.name]!=null?n.push(g(s,B,C)):B.push in C&&C[B.push]!=null&&C[B.push].forEach(function(E){n.push(g(s,B,E))})})}),C.media.forEach(function(s){n.push(g("m",t.m[0],s)),Q.forEach(function(B){t[B].forEach(function(E){E.name in s&&s[E.name]!=null?n.push(g(B,E,s)):E.push in s&&s[E.push]!=null&&s[E.push].forEach(function(d){n.push(g(B,E,d))})})})}),n.join(`\r
|
|
83
83
|
`)+`\r
|
|
84
|
-
`},EQ}var ar;function qx(){if(ar)return Yg;ar=1;var t=Yx(),A=Tx(),e=BQ();return Yg.grammar=e,Yg.write=A,Yg.parse=t.parse,Yg.parseParams=t.parseParams,Yg.parseFmtpConfig=t.parseFmtpConfig,Yg.parsePayloads=t.parsePayloads,Yg.parseRemoteCandidates=t.parseRemoteCandidates,Yg.parseImageAttributes=t.parseImageAttributes,Yg.parseSimulcastStreamList=t.parseSimulcastStreamList,Yg}var $t=qx();function rQ(t,A,e){var g,i,I;A===void 0&&(A=50),e===void 0&&(e={});var C=(g=e.isImmediate)!=null&&g,o=(i=e.callback)!=null&&i,a=e.maxWait,Q=Date.now(),n=[];function s(){if(a!==void 0){var E=Date.now()-Q;if(E+A>=a)return a-E}return A}var B=function(){var E=[].slice.call(arguments),d=this;return new Promise(function(c,h){var r=C&&I===void 0;if(I!==void 0&&clearTimeout(I),I=setTimeout(function(){if(I=void 0,Q=Date.now(),!C){var _=t.apply(d,E);o&&o(_),n.forEach(function(l){return(0,l.resolve)(_)}),n=[]}},s()),r){var f=t.apply(d,E);return o&&o(f),c(f)}n.push({resolve:c,reject:h})})};return B.cancel=function(E){I!==void 0&&clearTimeout(I),n.forEach(function(d){return(0,d.reject)(E)}),n=[]},B}const Hx=.7,Px=20,gI={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Qr extends At.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var g;super(),this.log=$A,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=rQ(i=>S(this,void 0,void 0,function*(){this.emit(gI.NegotiationStarted);try{yield this.createAndSendOffer()}catch(I){if(i)i(I);else throw I}}),Px),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=lt((g=e.loggerName)!==null&&g!==void 0?g:vg.PCTransport),this.loggerOptions=e,this.config=A,this._pc=this.createPC(),this.offerLock=new sg}createPC(){const A=new RTCPeerConnection(this.config);return A.onicecandidate=e=>{var g;e.candidate&&((g=this.onIceCandidate)===null||g===void 0||g.call(this,e.candidate))},A.onicecandidateerror=e=>{var g;(g=this.onIceCandidateError)===null||g===void 0||g.call(this,e)},A.oniceconnectionstatechange=()=>{var e;(e=this.onIceConnectionStateChange)===null||e===void 0||e.call(this,A.iceConnectionState)},A.onsignalingstatechange=()=>{var e;(e=this.onSignalingStatechange)===null||e===void 0||e.call(this,A.signalingState)},A.onconnectionstatechange=()=>{var e;(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,A.connectionState)},A.ondatachannel=e=>{var g;(g=this.onDataChannel)===null||g===void 0||g.call(this,e)},A.ontrack=e=>{var g;(g=this.onTrack)===null||g===void 0||g.call(this,e)},A}get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions).loggerContextCb)===null||e===void 0?void 0:e.call(A))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(A){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(A);this.pendingCandidates.push(A)})}setRemoteDescription(A,e){return S(this,void 0,void 0,function*(){var g;if(A.type==="answer"&&this.latestOfferId>0&&e>0&&e!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:e,latestOfferId:this.latestOfferId})),!1;let i;if(A.type==="offer"){let{stereoMids:I,nackMids:C}=Ox(A);this.remoteStereoMids=I,this.remoteNackMids=C}else if(A.type==="answer"){const I=$t.parse((g=A.sdp)!==null&&g!==void 0?g:"");I.media.forEach(C=>{C.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||C.mid!=o.transceiver.mid)return!1;let a=0;if(C.rtp.some(n=>n.codec.toUpperCase()===o.codec.toUpperCase()?(a=n.payload,!0):!1),a===0)return!0;let Q=!1;for(const n of C.fmtp)if(n.payload===a){n.config=n.config.split(";").filter(s=>!s.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(n.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),Q=!0;break}return Q||o.maxbr>0&&C.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),i=$t.write(I)}return yield this.setMungedSDP(A,i,!0),this.pendingCandidates.forEach(I=>{this.pc.addIceCandidate(I)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):A.type==="answer"&&(this.emit(gI.NegotiationComplete),A.sdp&&$t.parse(A.sdp).media.forEach(C=>{C.type==="video"&&this.emit(gI.RTPVideoPayloadTypes,C.rtp)})),!0})}createAndSendOffer(A){return S(this,void 0,void 0,function*(){var e;const g=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(A!=null&&A.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(A!=null&&A.iceRestart&&o)yield this._pc.setRemoteDescription(o);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 i=this.latestOfferId+1;this.latestOfferId=i;const I=yield this.pc.createOffer(A);this.log.debug("original offer",Object.assign({sdp:I.sdp},this.logContext));const C=$t.parse((e=I.sdp)!==null&&e!==void 0?e:"");if(C.media.forEach(o=>{sr(o),o.type==="audio"?nr(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let Q=0;if(o.rtp.some(s=>s.codec.toUpperCase()===a.codec.toUpperCase()?(Q=s.payload,!0):!1),Q===0||(et(a.codec)&&!Di()&&this.ensureVideoDDExtensionForSVC(o,C),a.codec!=="av1"))return!0;const n=Math.round(a.maxbr*Hx);for(const s of o.fmtp)if(s.payload===Q){s.config.includes("x-google-start-bitrate")||(s.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(I,$t.write(C)),this.onOffer(I,this.latestOfferId)}finally{g()}})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pc.createAnswer(),g=$t.parse((A=e.sdp)!==null&&A!==void 0?A:"");return g.media.forEach(i=>{sr(i),i.type==="audio"&&nr(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,$t.write(g)),e})}createDataChannel(A,e){return this.pc.createDataChannel(A,e)}addTransceiver(A,e){return this.pc.addTransceiver(A,e)}addTrack(A){if(!this._pc)throw new Pe("PC closed, cannot add track");return this._pc.addTrack(A)}setTrackCodecBitrate(A){this.trackBitrates.push(A)}setConfiguration(A){var e;if(!this._pc)throw new Pe("PC closed, cannot configure");return(e=this._pc)===null||e===void 0?void 0:e.setConfiguration(A)}canRemoveTrack(){var A;return!!(!((A=this._pc)===null||A===void 0)&&A.removeTrack)}removeTrack(A){var e;return(e=this._pc)===null||e===void 0?void 0:e.removeTrack(A)}getConnectionState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.connectionState)!==null&&e!==void 0?e:"closed"}getICEConnectionState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.iceConnectionState)!==null&&e!==void 0?e:"closed"}getSignallingState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.signalingState)!==null&&e!==void 0?e:"closed"}getTransceivers(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.getTransceivers())!==null&&e!==void 0?e:[]}getSenders(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.getSenders())!==null&&e!==void 0?e:[]}getLocalDescription(){var A;return(A=this._pc)===null||A===void 0?void 0:A.localDescription}getRemoteDescription(){var A;return(A=this.pc)===null||A===void 0?void 0:A.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return S(this,void 0,void 0,function*(){var A;if(!this._pc)return;let e="";const g=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":e=o.selectedCandidatePairId;break;case"candidate-pair":e===""&&o.selected&&(e=o.id),g.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),e==="")return;const C=(A=g.get(e))===null||A===void 0?void 0:A.remoteCandidateId;if(C!==void 0)return i.get(C)})}setMungedSDP(A,e,g){return S(this,void 0,void 0,function*(){if(e){const i=A.sdp;A.sdp=e;try{this.log.debug("setting munged ".concat(g?"remote":"local"," description"),this.logContext),g?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A);return}catch(I){this.log.warn("not able to set ".concat(A.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:I,sdp:e})),A.sdp=i}}try{g?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A)}catch(i){let I="unknown error";i instanceof Error?I=i.message:typeof i=="string"&&(I=i);const C={error:I,sdp:A.sdp};throw!g&&this.pc.remoteDescription&&(C.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(A.type),Object.assign(Object.assign({},this.logContext),{fields:C})),new qa(I)}})}ensureVideoDDExtensionForSVC(A,e){var g,i;if(!((g=A.ext)===null||g===void 0?void 0:g.some(C=>C.uri===TE))){if(this.ddExtID===0){let C=0;e.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(Q=>{Q.value>C&&(C=Q.value)}))}),this.ddExtID=C+1}(i=A.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:TE})}}}function nr(t,A,e){let g=0;t.rtp.some(i=>i.codec==="opus"?(g=i.payload,!0):!1),g>0&&(t.rtcpFb||(t.rtcpFb=[]),e.includes(t.mid)&&!t.rtcpFb.some(i=>i.payload===g&&i.type==="nack")&&t.rtcpFb.push({payload:g,type:"nack"}),A.includes(t.mid)&&t.fmtp.some(i=>i.payload===g?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function Ox(t){var A;const e=[],g=[],i=$t.parse((A=t.sdp)!==null&&A!==void 0?A:"");let I=0;return i.media.forEach(C=>{var o;C.type==="audio"&&(C.rtp.some(a=>a.codec==="opus"?(I=a.payload,!0):!1),!((o=C.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===I&&a.type==="nack")&&g.push(C.mid),C.fmtp.some(a=>a.payload===I?(a.config.includes("sprop-stereo=1")&&e.push(C.mid),!0):!1))}),{stereoMids:e,nackMids:g}}function sr(t){if(t.connection){const A=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&A||t.connection.version===6&&!A)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const cQ="vp8",Vx={audioPreset:Oa.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ja.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cQ,backupCodec:!0,preConnectBuffer:!1},Br={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Er={deviceId:{ideal:"default"},resolution:ZI.h720.resolution},jx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Fd,disconnectOnPageLeave:!0,webAudioMix:!1},hQ={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ge;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Ge||(Ge={}));class Wx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(A,e,g){var i;this.peerConnectionTimeout=hQ.peerConnectionTimeout,this.log=$A,this.updateState=()=>{var I;const C=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ge.CONNECTED:o.some(a=>a==="failed")?this.state=Ge.FAILED:o.some(a=>a==="connecting")?this.state=Ge.CONNECTING:o.every(a=>a==="closed")?this.state=Ge.CLOSED:o.some(a=>a==="closed")?this.state=Ge.CLOSING:o.every(a=>a==="new")&&(this.state=Ge.NEW),C!==this.state&&(this.log.debug("pc state change: from ".concat(Ge[C]," to ").concat(Ge[this.state]),this.logContext),(I=this.onStateChange)===null||I===void 0||I.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=lt((i=g.loggerName)!==null&&i!==void 0?i:vg.PCManager),this.loggerOptions=g,this.isPublisherConnectionRequired=!e,this.isSubscriberConnectionRequired=e,this.publisher=new Qr(A,g),this.subscriber=new Qr(A,g),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=I=>{var C;(C=this.onIceCandidate)===null||C===void 0||C.call(this,I,Kg.PUBLISHER)},this.subscriber.onIceCandidate=I=>{var C;(C=this.onIceCandidate)===null||C===void 0||C.call(this,I,Kg.SUBSCRIBER)},this.subscriber.onDataChannel=I=>{var C;(C=this.onDataChannel)===null||C===void 0||C.call(this,I)},this.subscriber.onTrack=I=>{var C;(C=this.onTrack)===null||C===void 0||C.call(this,I)},this.publisher.onOffer=(I,C)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,I,C)},this.state=Ge.NEW,this.connectionLock=new sg,this.remoteOfferLock=new sg}get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions).loggerContextCb)===null||e===void 0?void 0:e.call(A))}requirePublisher(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=A,this.updateState()}requireSubscriber(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=A,this.updateState()}createAndSendPublisherOffer(A){return this.publisher.createAndSendOffer(A)}setPublisherAnswer(A,e){return this.publisher.setRemoteDescription(A,e)}removeTrack(A){return this.publisher.removeTrack(A)}close(){return S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const A=this.publisher;for(const e of A.getSenders())try{A.canRemoveTrack()&&A.removeTrack(e)}catch(g){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:g}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(A,e){return S(this,void 0,void 0,function*(){e===Kg.PUBLISHER?yield this.publisher.addIceCandidate(A):yield this.subscriber.addIceCandidate(A)})}createSubscriberAnswerFromOffer(A,e){return S(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type,sdp:A.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const g=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(A,e))?yield this.subscriber.createAndSetAnswer():void 0}finally{g()}})}updateConfiguration(A,e){this.publisher.setConfiguration(A),this.subscriber.setConfiguration(A),e&&this.triggerIceRestart()}ensurePCTransportConnection(A,e){return S(this,void 0,void 0,function*(){var g;const i=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((g=this.requiredTransports)===null||g===void 0?void 0:g.map(I=>this.ensureTransportConnected(I,A,e)))}finally{i()}})}negotiate(A){return S(this,void 0,void 0,function*(){return new Promise((e,g)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{g("negotiation timed out")},this.peerConnectionTimeout),I=()=>{clearTimeout(i),g("negotiation aborted")};A.signal.addEventListener("abort",I),this.publisher.once(gI.NegotiationStarted,()=>{A.signal.aborted||this.publisher.once(gI.NegotiationComplete,()=>{clearTimeout(i),e()})}),yield this.publisher.negotiate(C=>{clearTimeout(i),g(C)})}))})}addPublisherTransceiver(A,e){return this.publisher.addTransceiver(A,e)}addPublisherTrack(A){return this.publisher.addTrack(A)}createPublisherDataChannel(A,e){return this.publisher.createDataChannel(A,e)}getConnectedAddress(A){return A===Kg.PUBLISHER?this.publisher.getConnectedAddress():A===Kg.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const A=[];return this.isPublisherConnectionRequired&&A.push(this.publisher),this.isSubscriberConnectionRequired&&A.push(this.subscriber),A}ensureTransportConnected(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(g.getConnectionState()!=="connected")return new Promise((a,Q)=>S(I,void 0,void 0,function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),ze.clearTimeout(s),Q(new ue("room connection has been cancelled",ie.Cancelled))};i!=null&&i.signal.aborted&&n(),i==null||i.signal.addEventListener("abort",n);const s=ze.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",n),Q(new ue("could not establish pc connection",ie.InternalError))},C);for(;this.state!==Ge.CONNECTED;)if(yield rg(50),i!=null&&i.signal.aborted){Q(new ue("room connection has been cancelled",ie.Cancelled));return}ze.clearTimeout(s),i==null||i.signal.removeEventListener("abort",n),a()}))}()})}}class Me extends Error{constructor(A,e,g){super(e),this.code=A,this.message=cr(e,Me.MAX_MESSAGE_BYTES),this.data=g?cr(g,Me.MAX_DATA_BYTES):void 0}static fromProto(A){return new Me(A.code,A.message,A.data)}toProto(){return new mB({code:this.code,message:this.message,data:this.data})}static builtIn(A,e){return new Me(Me.ErrorCode[A],Me.ErrorMessage[A],e)}}Me.MAX_MESSAGE_BYTES=256,Me.MAX_DATA_BYTES=15360,Me.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},Me.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 rr=15360;function dQ(t){return new TextEncoder().encode(t).length}function cr(t,A){if(dQ(t)<=A)return t;let e=0,g=t.length;const i=new TextEncoder;for(;e<g;){const I=Math.floor((e+g+1)/2);i.encode(t.slice(0,I)).length<=A?e=I:g=I-1}return t.slice(0,e)}const xQ=2e3;function io(t,A){if(!A)return 0;let e,g;return"bytesReceived"in t?(e=t.bytesReceived,g=A.bytesReceived):"bytesSent"in t&&(e=t.bytesSent,g=A.bytesSent),e===void 0||g===void 0||t.timestamp===void 0||A.timestamp===void 0?0:(e-g)*8*1e3/(t.timestamp-A.timestamp)}const lQ=typeof MediaRecorder<"u";class Xx{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Zx=lQ?MediaRecorder:Xx;class zx extends Zx{constructor(A,e){if(!lQ)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([A.mediaStreamTrack]),e);let g,i;const I=()=>i===void 0,C=()=>{this.removeEventListener("dataavailable",g),this.removeEventListener("stop",C),this.removeEventListener("error",o),i==null||i.close(),i=void 0},o=a=>{i==null||i.error(a),this.removeEventListener("dataavailable",g),this.removeEventListener("stop",C),this.removeEventListener("error",o),i=void 0};this.byteStream=new ReadableStream({start:a=>{i=a,g=Q=>S(this,void 0,void 0,function*(){let n;if(Q.data.arrayBuffer){const s=yield Q.data.arrayBuffer();n=new Uint8Array(s)}else if(Q.data.byteArray)n=Q.data.byteArray;else throw new Error("no data available!");I()||a.enqueue(n)}),this.addEventListener("dataavailable",g)},cancel:()=>{C()}}),this.addEventListener("stop",C),this.addEventListener("error",o)}}function $x(){return lQ}const Al=1e3,el=1e4;class hr extends AA{get sender(){return this._sender}set sender(A){this._sender=A}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(A,e,g){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,I=arguments.length>4?arguments[4]:void 0;super(A,e,I),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=rQ(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(oA.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new sg,this.pauseUpstreamLock=new sg,this.trackChangeLock=new sg,this.trackChangeLock.lock().then(C=>S(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(A,!0)}finally{C()}})),this._constraints=A.getConstraints(),g&&(this._constraints=g)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==AA.Kind.Video)return;const{width:A,height:e}=this._mediaStreamTrack.getSettings();if(A&&e)return{width:A,height:e}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var A,e;return(e=(A=this.processor)===null||A===void 0?void 0:A.processedTrack)!==null&&e!==void 0?e:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(A,e){return S(this,void 0,void 0,function*(){var g;if(A===this._mediaStreamTrack&&!e)return;this._mediaStreamTrack&&(this.attachedElements.forEach(I=>{AI(this._mediaStreamTrack,I)}),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([A]),A&&(A.addEventListener("ended",this.handleEnded),A.addEventListener("mute",this.handleTrackMuteEvent),A.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=A.getConstraints());let i;if(this.processor&&A){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&($i(A,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:A,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&((g=this.sender.transport)===null||g===void 0?void 0:g.state)!=="closed"&&(yield this.sender.replaceTrack(i??A)),!this.providedByUser&&this._mediaStreamTrack!==A&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=A,A&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(I=>{$i(i??A,I)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Al;return function*(){var g;if(A.kind===AA.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((g=fg())===null||g===void 0?void 0:g.os)==="iOS"&&(yield rg(10));const i=Date.now();for(;Date.now()-i<e;){const I=A.dimensions;if(I)return I;yield rg(50)}throw new Dt("unable to get track dimensions after timeout")}()})}setDeviceId(A){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===A&&this._mediaStreamTrack.getSettings().deviceId===Xt(A)||(this._constraints.deviceId=A,this.isMuted)?!0:(yield this.restartTrack(),Xt(A)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(A.source===AA.Source.ScreenShare)return;const{deviceId:g,groupId:i}=A._mediaStreamTrack.getSettings(),I=A.kind===AA.Kind.Audio?"audioinput":"videoinput";return e?We.getInstance().normalizeDeviceId(I,g,i):g}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(A,e){return S(this,void 0,void 0,function*(){const g=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Dt("unable to replace an unpublished track");let i,I;return typeof e=="boolean"?i=e:e!==void 0&&(i=e.userProvidedTrack,I=e.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(A),I&&this.processor&&(yield this.internalStopProcessor()),this}finally{g()}})}restart(A){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const e=yield this.trackChangeLock.lock();try{A||(A=this._constraints);const{deviceId:g,facingMode:i}=A,I=Ud(A,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:A}));const C={audio:!1,video:!1};this.kind===AA.Kind.Video?C.video=g||i?{deviceId:g,facingMode:i}:!0:C.audio=g?Object.assign({deviceId:g},I):!0,this.attachedElements.forEach(Q=>{AI(this.mediaStreamTrack,Q)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(C)).getTracks()[0];return this.kind===AA.Kind.Video&&(yield a.applyConstraints(I)),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=A,this.emit(oA.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{e()}})}setTrackMuted(A){this.log.debug("setting ".concat(this.kind," track ").concat(A?"muted":"unmuted"),this.logContext),!(this.isMuted===A&&this._mediaStreamTrack.enabled!==A)&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?oA.Muted:oA.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),qE()&&(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 A;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(A=this.processor)===null||A===void 0||A.destroy(),this.processor=void 0}pauseUpstream(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(oA.UpstreamPaused,this);const g=fg();if((g==null?void 0:g.name)==="Safari"&&tt(g.version,"12.0")<0)throw new Ta("pauseUpstream is not supported on Safari < 12.");((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(oA.UpstreamResumed,this),((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var A;return!((A=this.sender)===null||A===void 0)&&A.getStats?yield this.sender.getStats():void 0})}setProcessor(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var I;const C=yield g.trackChangeLock.lock();try{g.log.debug("setting up processor",g.logContext);const o=document.createElement(g.kind),a={kind:g.kind,track:g._mediaStreamTrack,element:o,audioContext:g.audioContext};if(yield e.init(a),g.log.debug("processor initialized",g.logContext),g.processor&&(yield g.internalStopProcessor()),g.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if($i(g._mediaStreamTrack,o),o.muted=!0,o.play().catch(Q=>{Q instanceof DOMException&&Q.name==="AbortError"?(g.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},g.logContext),{error:Q})),setTimeout(()=>{o.play().catch(n=>{g.log.error("failed to play processor element",Object.assign(Object.assign({},g.logContext),{err:n}))})},100)):g.log.error("failed to play processor element",Object.assign(Object.assign({},g.logContext),{error:Q}))}),g.processor=e,g.processorElement=o,g.processor.processedTrack){for(const Q of g.attachedElements)Q!==g.processorElement&&i&&(AI(g._mediaStreamTrack,Q),$i(g.processor.processedTrack,Q));yield(I=g.sender)===null||I===void 0?void 0:I.replaceTrack(g.processor.processedTrack)}g.emit(oA.TrackProcessorUpdate,g.processor)}finally{C()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const g=yield A.trackChangeLock.lock();try{yield A.internalStopProcessor(e)}finally{g()}}()})}internalStopProcessor(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var g,i;A.processor&&(A.log.debug("stopping processor",A.logContext),(g=A.processor.processedTrack)===null||g===void 0||g.stop(),yield A.processor.destroy(),A.processor=void 0,e||((i=A.processorElement)===null||i===void 0||i.remove(),A.processorElement=void 0),yield A._mediaStreamTrack.applyConstraints(A._constraints),yield A.setMediaStreamTrack(A._mediaStreamTrack,!0),A.emit(oA.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!$x()){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 e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new zx(this,{mimeType:e})}this.localTrackRecorder.start(A),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},el)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.byteStream}getPreConnectBufferMimeType(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.mimeType}}class Io extends hr{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0;super(A,AA.Kind.Audio,e,g,I),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let C;try{C=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}C&&this.prevStats&&(this._currentBitrate=io(C,this.prevStats)),this.prevStats=C}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oA.AudioTrackFeatureUpdate,this,je.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oA.AudioTrackFeatureUpdate,this,je.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===AA.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{e()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const g=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Xt(this._constraints.deviceId);return this.source===AA.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||g)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this}finally{e()}})}restartTrack(A){return S(this,void 0,void 0,function*(){let e;if(A){const g=CQ({audio:A});typeof g.audio!="boolean"&&(e=g.audio)}yield this.restart(e)})}restart(A){const e=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const g=yield e.restart.call(this,A);return this.checkForSilence(),g})}startMonitor(){cg()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},xQ)))}setProcessor(A){return S(this,void 0,void 0,function*(){var e;const g=yield this.trackChangeLock.lock();try{if(!gt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(A.name),this.logContext),yield A.init(i),this.processor=A,this.processor.processedTrack&&(yield(e=this.sender)===null||e===void 0?void 0:e.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(oA.TrackProcessorUpdate,this.processor)}finally{g()}})}setAudioContext(A){this.audioContext=A}getSenderStats(){return S(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return;const e=yield this.sender.getStats();let g;return e.forEach(i=>{i.type==="outbound-rtp"&&(g={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),g})}checkForSilence(){return S(this,void 0,void 0,function*(){const A=yield zE(this);return A&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oA.AudioSilenceDetected)),A})}}function gl(t,A,e){switch(t.kind){case"audio":return new Io(t,A,!1,void 0,e);case"video":return new Co(t,A,!1,e);default:throw new Dt("unsupported track type: ".concat(t.kind))}}const tl=Object.values(ZI),il=Object.values(Va),Il=Object.values(ja),Cl=[ZI.h180,ZI.h360],ol=[Va.h180,Va.h360],al=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var g,i;return new xe(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*(((g=t.encoding.maxFramerate)!==null&&g!==void 0?g:30)/((i=e.fps)!==null&&i!==void 0?i:30))))),e.fps,t.encoding.priority)}),fQ=["q","h","f"];function uQ(t,A,e,g){var i,I;let C=g==null?void 0:g.videoEncoding;t&&(C=g==null?void 0:g.screenShareEncoding);const o=g==null?void 0:g.simulcast,a=g==null?void 0:g.scalabilityMode,Q=g==null?void 0:g.videoCodec;if(!C&&!o&&!a||!A||!e)return[{}];C||(C=nl(t,A,e,Q),$A.debug("using video encoding",C));const n=C.maxFramerate,s=new xe(A,e,C.maxBitrate,C.maxFramerate,C.priority);if(a&&et(Q)){const d=new lr(a),c=[];if(d.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const h=fg();if(zI()||gt()||(h==null?void 0:h.name)==="Chrome"&&tt(h==null?void 0:h.version,"113")<0){const r=d.suffix=="h"?2:3,f=Ex(h);for(let _=0;_<d.spatial;_+=1)c.push({rid:fQ[2-_],maxBitrate:C.maxBitrate/Math.pow(r,_),maxFramerate:s.encoding.maxFramerate,scaleResolutionDownBy:f?Math.pow(2,_):void 0});c[0].scalabilityMode=a}else c.push({maxBitrate:C.maxBitrate,maxFramerate:s.encoding.maxFramerate,scalabilityMode:a});return s.encoding.priority&&(c[0].priority=s.encoding.priority,c[0].networkPriority=s.encoding.priority),$A.debug("using svc encoding",{encodings:c}),c}if(!o)return[C];let B=[];t?B=(i=xr(g==null?void 0:g.screenShareSimulcastLayers))!==null&&i!==void 0?i:dr(t,s):B=(I=xr(g==null?void 0:g.videoSimulcastLayers))!==null&&I!==void 0?I:dr(t,s);let E;if(B.length>0){const d=B[0];B.length>1&&([,E]=B);const c=Math.max(A,e);if(c>=960&&E)return DQ(A,e,[d,E,s],n);if(c>=480)return DQ(A,e,[d,s],n)}return DQ(A,e,[s])}function Ql(t,A,e){var g,i,I,C;if(!e.backupCodec||e.backupCodec===!0||e.backupCodec.codec===e.videoCodec)return;A!==e.backupCodec.codec&&$A.warn("requested a different codec than specified as backup",{serverRequested:A,backup:e.backupCodec.codec}),e.videoCodec=A,e.videoEncoding=e.backupCodec.encoding;const o=t.mediaStreamTrack.getSettings(),a=(g=o.width)!==null&&g!==void 0?g:(i=t.dimensions)===null||i===void 0?void 0:i.width,Q=(I=o.height)!==null&&I!==void 0?I:(C=t.dimensions)===null||C===void 0?void 0:C.height;return t.source===AA.Source.ScreenShare&&e.simulcast&&(e.simulcast=!1),uQ(t.source===AA.Source.ScreenShare,a,Q,e)}function nl(t,A,e,g){const i=sl(t,A,e);let{encoding:I}=i[0];const C=Math.max(A,e);for(let o=0;o<i.length;o+=1){const a=i[o];if(I=a.encoding,a.width>=C)break}if(g)switch(g){case"av1":case"h265":I=Object.assign({},I),I.maxBitrate=I.maxBitrate*.7;break;case"vp9":I=Object.assign({},I),I.maxBitrate=I.maxBitrate*.85;break}return I}function sl(t,A,e){if(t)return Il;const g=A>e?A/e:e/A;return Math.abs(g-16/9)<Math.abs(g-4/3)?tl:il}function dr(t,A){if(t)return al(A);const{width:e,height:g}=A,i=e>g?e/g:g/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cl:ol}function DQ(t,A,e,g){const i=[];if(e.forEach((I,C)=>{if(C>=fQ.length)return;const o=Math.min(t,A),Q={rid:fQ[C],scaleResolutionDownBy:Math.max(1,o/Math.min(I.width,I.height)),maxBitrate:I.encoding.maxBitrate},n=g&&I.encoding.maxFramerate?Math.min(g,I.encoding.maxFramerate):I.encoding.maxFramerate;n&&(Q.maxFramerate=n);const s=ui()||C===0;I.encoding.priority&&s&&(Q.priority=I.encoding.priority,Q.networkPriority=I.encoding.priority),i.push(Q)}),gt()&&PE()==="ios"){let I;i.forEach(o=>{I?o.maxFramerate&&o.maxFramerate>I&&(I=o.maxFramerate):I=o.maxFramerate});let C=!0;i.forEach(o=>{var a;o.maxFramerate!=I&&(C&&(C=!1,$A.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),$A.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(I)),o.maxFramerate=I)})}return i}function xr(t){if(t)return t.sort((A,e)=>{const{encoding:g}=A,{encoding:i}=e;return g.maxBitrate>i.maxBitrate?1:g.maxBitrate<i.maxBitrate?-1:g.maxBitrate===i.maxBitrate&&g.maxFramerate&&i.maxFramerate?g.maxFramerate>i.maxFramerate?1:-1:0})}class lr{constructor(A){const e=A.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw new Error("invalid scalability mode");if(this.spatial=parseInt(e[1]),this.temporal=parseInt(e[2]),e.length>3)switch(e[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=e[3]}}toString(){var A;return"L".concat(this.spatial,"T").concat(this.temporal).concat((A=this.suffix)!==null&&A!==void 0?A:"")}}function Bl(t){return t.source===AA.Source.ScreenShare||t.constraints.height&&Xt(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const El=5e3;class Co extends hr{get sender(){return this._sender}set sender(A){this._sender=A,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(A,AA.Kind.Video,e,g,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let I;try{I=yield this.getSenderStats()}catch(a){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const C=new Map(I.map(a=>[a.rid,a])),o=I.some(a=>a.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(oA.CpuConstrained)),this.prevStats){let a=0;C.forEach((Q,n)=>{var s;const B=(s=this.prevStats)===null||s===void 0?void 0:s.get(n);a+=io(Q,B)}),this._currentBitrate=a}this.prevStats=C}),this.senderLock=new sg}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(A){var e;if(this.signalClient=A,!cg())return;const g=(e=this.sender)===null||e===void 0?void 0:e.getParameters();g&&(this.encodings=g.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},xQ))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(A=>{A.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const A=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var e,g,i,I,C;yield A.pauseUpstream.call(this);try{for(var o=!0,a=ft(this.simulcastCodecs.values()),Q;Q=yield a.next(),e=Q.done,!e;o=!0)I=Q.value,o=!1,yield(C=I.sender)===null||C===void 0?void 0:C.replaceTrack(null)}catch(n){g={error:n}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(g)throw g.error}}})}resumeUpstream(){const A=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var e,g,i,I,C;yield A.resumeUpstream.call(this);try{for(var o=!0,a=ft(this.simulcastCodecs.values()),Q;Q=yield a.next(),e=Q.done,!e;o=!0){I=Q.value,o=!1;const n=I;yield(C=n.sender)===null||C===void 0?void 0:C.replaceTrack(n.mediaStreamTrack)}}catch(n){g={error:n}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(g)throw g.error}}})}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===AA.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{e()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source===AA.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{e()}})}setTrackMuted(A){super.setTrackMuted(A);for(const e of this.simulcastCodecs.values())e.mediaStreamTrack.enabled=!A}getSenderStats(){return S(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return[];const e=[],g=yield this.sender.getStats();return g.forEach(i=>{var I;if(i.type==="outbound-rtp"){const C={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(I=i.rid)!==null&&I!==void 0?I:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=g.get(i.remoteId);o&&(C.jitter=o.jitter,C.packetsLost=o.packetsLost,C.roundTripTime=o.roundTripTime),e.push(C)}}),e.sort((i,I)=>{var C,o;return((C=I.frameWidth)!==null&&C!==void 0?C:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),e})}setPublishingQuality(A){const e=[];for(let g=ug.LOW;g<=ug.HIGH;g+=1)e.push(new Sa({quality:g,enabled:g<=A}));this.log.debug("setting publishing quality. max quality ".concat(A),this.logContext),this.setPublishingLayers(et(this.codec),e)}restartTrack(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C;let o;if(A){const s=CQ({video:A});typeof s.video!="boolean"&&(o=s.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var a=!0,Q=ft(this.simulcastCodecs.values()),n;n=yield Q.next(),e=n.done,!e;a=!0){I=n.value,a=!1;const s=I;s.sender&&((C=s.sender.transport)===null||C===void 0?void 0:C.state)!=="closed"&&(s.mediaStreamTrack=this.mediaStreamTrack.clone(),yield s.sender.replaceTrack(s.mediaStreamTrack))}}catch(s){g={error:s}}finally{try{!a&&!e&&(i=Q.return)&&(yield i.call(Q))}finally{if(g)throw g.error}}})}setProcessor(A){const e=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(g){var i=this;let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var C,o,a,Q,n,s;if(yield e.setProcessor.call(i,g,I),!((n=i.processor)===null||n===void 0)&&n.processedTrack)try{for(var B=!0,E=ft(i.simulcastCodecs.values()),d;d=yield E.next(),C=d.done,!C;B=!0)Q=d.value,B=!1,yield(s=Q.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}catch(c){o={error:c}}finally{try{!B&&!C&&(a=E.return)&&(yield a.call(E))}finally{if(o)throw o.error}}}()})}setDegradationPreference(A){return S(this,void 0,void 0,function*(){if(this.degradationPreference=A,this.sender)try{this.log.debug("setting degradationPreference to ".concat(A),this.logContext);const e=this.sender.getParameters();e.degradationPreference=A,this.sender.setParameters(e)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(A,e){if(this.simulcastCodecs.has(A)){this.log.error("".concat(A," already added, skipping adding simulcast codec"),this.logContext);return}const g={codec:A,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:e};return this.simulcastCodecs.set(A,g),g}setSimulcastTrackSender(A,e){const g=this.simulcastCodecs.get(A);g&&(g.sender=e,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},El))}setPublishingCodecs(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:A,currentCodec:this.codec})),!this.codec&&A.length>0)return yield this.setPublishingLayers(et(A[0].codec),A[0].qualities),[];this.subscribedCodecs=A;const Q=[];try{for(e=!0,g=ft(A);i=yield g.next(),I=i.done,!I;e=!0){a=i.value,e=!1;const n=a;if(!this.codec||this.codec===n.codec)yield this.setPublishingLayers(et(n.codec),n.qualities);else{const s=this.simulcastCodecs.get(n.codec);if(this.log.debug("try setPublishingCodec for ".concat(n.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:s})),!s||!s.sender){for(const B of n.qualities)if(B.enabled){Q.push(n.codec);break}}else s.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(n.codec),this.logContext),yield fr(s.sender,s.encodings,n.qualities,this.senderLock,et(n.codec),this.log,this.logContext))}}}catch(n){C={error:n}}finally{try{!e&&!I&&(o=g.return)&&(yield o.call(g))}finally{if(C)throw C.error}}return Q})}setPublishingLayers(A,e){return S(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:e}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield fr(this.sender,this.encodings,e,this.senderLock,A,this.log,this.logContext))})}prioritizePerformance(){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const A=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((g,i)=>{var I;return Object.assign(Object.assign({},g),{active:i===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((I=this.mediaStreamTrack.getSettings().height)!==null&&I!==void 0?I:360)/360)),scalabilityMode:i===0&&et(this.codec)?"L1T3":void 0,maxFramerate:i===0?15:0,maxBitrate:i===0?g.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{A()}})}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),qE()&&this.isInBackground&&this.source===AA.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function fr(t,A,e,g,i,I,C){return S(this,void 0,void 0,function*(){const o=yield g.lock();I.debug("setPublishingLayersForSender",Object.assign(Object.assign({},C),{sender:t,qualities:e,senderEncodings:A}));try{const a=t.getParameters(),{encodings:Q}=a;if(!Q)return;if(Q.length!==A.length){I.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},C),{encodings:Q,senderEncodings:A}));return}let n=!1;!1&&Q[0].scalabilityMode||(i&&e.some(E=>E.enabled)&&e.forEach(E=>E.enabled=!0),Q.forEach((B,E)=>{var d;let c=(d=B.rid)!==null&&d!==void 0?d:"";c===""&&(c="q");const h=ur(c),r=e.find(f=>f.quality===h);r&&B.active!==r.enabled&&(n=!0,B.active=r.enabled,I.debug("setting layer ".concat(r.quality," to ").concat(B.active?"enabled":"disabled"),C),ui()&&(r.enabled?(B.scaleResolutionDownBy=A[E].scaleResolutionDownBy,B.maxBitrate=A[E].maxBitrate,B.maxFrameRate=A[E].maxFrameRate):(B.scaleResolutionDownBy=4,B.maxBitrate=10,B.maxFrameRate=2)))})),n&&(a.encodings=Q,I.debug("setting encodings",Object.assign(Object.assign({},C),{encodings:a.encodings})),yield t.setParameters(a))}finally{o()}})}function ur(t){switch(t){case"f":return ug.HIGH;case"h":return ug.MEDIUM;case"q":return ug.LOW;default:return ug.HIGH}}function Dr(t,A,e,g){if(!e)return[new xi({quality:ug.HIGH,width:t,height:A,bitrate:0,ssrc:0})];if(g){const i=e[0].scalabilityMode,I=new lr(i),C=[],o=I.suffix=="h"?1.5:2,a=I.suffix=="h"?2:3;for(let Q=0;Q<I.spatial;Q+=1)C.push(new xi({quality:Math.min(ug.HIGH,I.spatial-1)-Q,width:Math.ceil(t/Math.pow(o,Q)),height:Math.ceil(A/Math.pow(o,Q)),bitrate:e[0].maxBitrate?Math.ceil(e[0].maxBitrate/Math.pow(a,Q)):0,ssrc:0}));return C}return e.map(i=>{var I,C,o;const a=(I=i.scaleResolutionDownBy)!==null&&I!==void 0?I:1;let Q=ur((C=i.rid)!==null&&C!==void 0?C:"");return new xi({quality:Q,width:Math.ceil(t/a),height:Math.ceil(A/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const _r="_lossy",wr="_reliable",rl=2*1e3,_Q="leave-reconnect",cl=3e4;var Tg;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(Tg||(Tg={}));class hl extends At.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(A){var e;super(),this.options=A,this.rtcConfig={},this.peerConnectionTimeout=hQ.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Tg.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=$A,this.reliableDataSequence=1,this.reliableMessageBuffer=new ir,this.reliableReceivedState=new Jx(cl),this.handleDataChannel=g=>S(this,[g],void 0,function(i){var I=this;let{channel:C}=i;return function*(){if(C){if(C.label===wr)I.reliableDCSub=C;else if(C.label===_r)I.lossyDCSub=C;else return;I.log.debug("on data channel ".concat(C.id,", ").concat(C.label),I.logContext),C.onmessage=I.handleDataMessage}}()}),this.handleDataMessage=g=>S(this,void 0,void 0,function*(){var i,I;const C=yield this.dataProcessLock.lock();try{let o;if(g.data instanceof ArrayBuffer)o=g.data;else if(g.data instanceof Blob)o=yield g.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:g.data}));return}const a=Eg.fromBinary(new Uint8Array(o));if(a.sequence>0&&a.participantSid!==""){const Q=this.reliableReceivedState.get(a.participantSid);if(Q&&a.sequence<=Q)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(nA.ActiveSpeakersUpdate,a.value.value.speakers):(((I=a.value)===null||I===void 0?void 0:I.case)==="user"&&xl(a,a.value.value),this.emit(nA.DataPacketReceived,a))}finally{C()}}),this.handleDataError=g=>{const I=g.currentTarget.maxRetransmits===0?"lossy":"reliable";if(g instanceof ErrorEvent&&g.error){const{error:C}=g.error;this.log.error("DataChannel error on ".concat(I,": ").concat(g.message),Object.assign(Object.assign({},this.logContext),{error:C}))}else this.log.error("Unknown DataChannel error on ".concat(I),Object.assign(Object.assign({},this.logContext),{event:g}))},this.handleBufferedAmountLow=g=>{const I=g.currentTarget.maxRetransmits===0?HA.LOSSY:HA.RELIABLE;this.updateAndEmitDCBufferStatus(I)},this.handleDisconnect=(g,i)=>{if(this._isClosed)return;this.log.warn("".concat(g," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const I=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(nA.Disconnected),this.close()},C=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:C,retryCount:this.reconnectAttempts});if(o===null){I(C);return}g===_Q&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ze.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((g,i)=>{this.pcState===Tg.Connected&&g();const I=()=>{this.off(nA.Disconnected,C),g()},C=()=>{this.off(nA.Restarted,I),i()};this.once(nA.Restarted,I),this.once(nA.Disconnected,C)}),this.updateAndEmitDCBufferStatus=g=>{const i=this.isBufferStatusLow(g);typeof i<"u"&&i!==this.dcBufferStatus.get(g)&&(this.dcBufferStatus.set(g,i),this.emit(nA.DCBufferStatusChanged,i,g))},this.isBufferStatusLow=g=>{const i=this.dataChannelForKind(g);if(i)return g===HA.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(i.bufferedAmount),i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ye.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ji.RR_SIGNAL_DISCONNECTED))},this.log=lt((e=A.loggerName)!==null&&e!==void 0?e:vg.Engine),this.loggerOptions={loggerName:A.loggerName,loggerContextCb:()=>this.logContext},this.client=new QQ(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new sg,this.dataProcessLock=new sg,this.dcBufferStatus=new Map([[HA.LOSSY,!0],[HA.RELIABLE,!0]]),this.client.onParticipantUpdate=g=>this.emit(nA.ParticipantUpdate,g),this.client.onConnectionQuality=g=>this.emit(nA.ConnectionQualityUpdate,g),this.client.onRoomUpdate=g=>this.emit(nA.RoomUpdate,g),this.client.onSubscriptionError=g=>this.emit(nA.SubscriptionError,g),this.client.onSubscriptionPermissionUpdate=g=>this.emit(nA.SubscriptionPermissionUpdate,g),this.client.onSpeakersChanged=g=>this.emit(nA.SpeakersChanged,g),this.client.onStreamStateUpdate=g=>this.emit(nA.StreamStateChanged,g),this.client.onRequestResponse=g=>this.emit(nA.SignalRequestResponse,g)}get logContext(){var A,e,g,i,I,C;return{room:(e=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.room)===null||e===void 0?void 0:e.name,roomID:(i=(g=this.latestJoinResponse)===null||g===void 0?void 0:g.room)===null||i===void 0?void 0:i.sid,participant:(C=(I=this.latestJoinResponse)===null||I===void 0?void 0:I.participant)===null||C===void 0?void 0:C.identity,pID:this.participantSid}}join(A,e,g,i){return S(this,void 0,void 0,function*(){this.url=A,this.token=e,this.signalOpts=g,this.maxJoinAttempts=g.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const I=yield this.client.join(A,e,g,i);return this._isClosed=!1,this.latestJoinResponse=I,this.subscriberPrimary=I.subscriberPrimary,this.pcManager||(yield this.configure(I)),(!this.subscriberPrimary||I.fastPublish)&&this.negotiate(),this.clientConfiguration=I.clientConfiguration,this.emit(nA.SignalConnected,I),I}catch(I){if(I instanceof ue&&I.reason===ie.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(A,e,g,i);throw I}})}close(){return S(this,void 0,void 0,function*(){const A=yield this.closingLock.lock();if(this.isClosed){A();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(nA.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{A()}})}cleanupPeerConnections(){return S(this,void 0,void 0,function*(){var A;yield(A=this.pcManager)===null||A===void 0?void 0:A.close(),this.pcManager=void 0;const e=g=>{g&&(g.close(),g.onbufferedamountlow=null,g.onclose=null,g.onclosing=null,g.onerror=null,g.onmessage=null,g.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ir,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(A){if(this.pendingTrackResolvers[A.cid])throw new Dt("a track with the same ID has already been published");return new Promise((e,g)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[A.cid],g(new ue("publication of local track timed out, no response from server",ie.Timeout))},1e4);this.pendingTrackResolvers[A.cid]={resolve:I=>{clearTimeout(i),e(I)},reject:()=>{clearTimeout(i),g(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(A)})}removeTrack(A){if(A.track&&this.pendingTrackResolvers[A.track.id]){const{reject:e}=this.pendingTrackResolvers[A.track.id];e&&e(),delete this.pendingTrackResolvers[A.track.id]}try{return this.pcManager.removeTrack(A),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(A,e){this.client.sendMuteTrack(A,e)}get dataSubscriberReadyState(){var A;return(A=this.reliableDCSub)===null||A===void 0?void 0:A.readyState}getConnectedServerAddress(){return S(this,void 0,void 0,function*(){var A;return(A=this.pcManager)===null||A===void 0?void 0:A.getConnectedAddress()})}setRegionUrlProvider(A){this.regionUrlProvider=A}configure(A){return S(this,void 0,void 0,function*(){var e,g;if(this.pcManager&&this.pcManager.currentState!==Ge.NEW)return;this.participantSid=(e=A.participant)===null||e===void 0?void 0:e.sid;const i=this.makeRTCConfiguration(A);this.pcManager=new Wx(i,A.subscriberPrimary,this.loggerOptions),this.emit(nA.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(I,C)=>{this.client.sendIceCandidate(I,C)},this.pcManager.onPublisherOffer=(I,C)=>{this.client.sendOffer(I,C)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(I,C,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(I),this.logContext),["closed","disconnected","failed"].includes(C)&&(this.publisherConnectionPromise=void 0),I===Ge.CONNECTED){const n=this.pcState===Tg.New;this.pcState=Tg.Connected,n&&this.emit(nA.Connected,A)}else I===Ge.FAILED&&this.pcState===Tg.Connected&&(this.pcState=Tg.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ji.RR_SUBSCRIBER_FAILED:ji.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===ye.RECONNECTING,Q=[Ge.FAILED,Ge.CLOSING,Ge.CLOSED].includes(I);a&&Q&&!this._isClosed&&this.emit(nA.Offline)}),this.pcManager.onTrack=I=>{this.emit(nA.MediaTrackAdded,I.track,I.streams[0],I.receiver)},dl((g=A.serverInfo)===null||g===void 0?void 0:g.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(A,e)=>S(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type})),yield this.pcManager.setPublisherAnswer(A,e))}),this.client.onTrickle=(A,e)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:A,target:e})),this.pcManager.addIceCandidate(A,e))},this.client.onOffer=(A,e)=>S(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=e,!this.pcManager)return;const g=yield this.pcManager.createSubscriberAnswerFromOffer(A,e);g&&this.client.sendAnswer(g,e)}),this.client.onLocalTrackPublished=A=>{var e;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:A.cid,track:(e=A.track)===null||e===void 0?void 0:e.sid})),!this.pendingTrackResolvers[A.cid]){this.log.error("missing track resolver for ".concat(A.cid),Object.assign(Object.assign({},this.logContext),{cid:A.cid}));return}const{resolve:g}=this.pendingTrackResolvers[A.cid];delete this.pendingTrackResolvers[A.cid],g(A.track)},this.client.onLocalTrackUnpublished=A=>{this.emit(nA.LocalTrackUnpublished,A)},this.client.onLocalTrackSubscribed=A=>{this.emit(nA.LocalTrackSubscribed,A)},this.client.onTokenRefresh=A=>{this.token=A},this.client.onRemoteMuteChanged=(A,e)=>{this.emit(nA.RemoteMute,A,e)},this.client.onSubscribedQualityUpdate=A=>{this.emit(nA.SubscribedQualityUpdate,A)},this.client.onRoomMoved=A=>{var e;this.participantSid=(e=A.participant)===null||e===void 0?void 0:e.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=A.room),this.emit(nA.RoomMoved,A)},this.client.onClose=()=>{this.handleDisconnect("signal",ji.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=A=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:A==null?void 0:A.reason})),A.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(A.regions)),A.action){case Zi.DISCONNECT:this.emit(nA.Disconnected,A==null?void 0:A.reason),this.close();break;case Zi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(_Q);break;case Zi.RESUME:this.handleDisconnect(_Q)}}}makeRTCConfiguration(A){var e;const g=Object.assign({},this.rtcConfig);if(!((e=this.signalOpts)===null||e===void 0)&&e.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),g.encodedInsertableStreams=!0),A.iceServers&&!g.iceServers){const i=[];A.iceServers.forEach(I=>{const C={urls:I.urls};I.username&&(C.username=I.username),I.credential&&(C.credential=I.credential),i.push(C)}),g.iceServers=i}return A.clientConfiguration&&A.clientConfiguration.forceRelay===PI.ENABLED&&(g.iceTransportPolicy="relay"),g.sdpSemantics="unified-plan",g.continualGatheringPolicy="gather_continually",g}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(_r,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wr,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(A,e,g){return S(this,void 0,void 0,function*(){if(Wa())return yield this.createTransceiverRTCRtpSender(A,e,g);if(Xa())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(A.mediaStreamTrack);throw new Pe("Required webRTC APIs not supported on this device")})}createSimulcastSender(A,e,g,i){return S(this,void 0,void 0,function*(){if(Wa())return this.createSimulcastTransceiverSender(A,e,g,i);if(Xa())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(A.mediaStreamTrack);throw new Pe("Cannot stream on this device")})}createTransceiverRTCRtpSender(A,e,g){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const i=[];A.mediaStream&&i.push(A.mediaStream),Zt(A)&&(A.codec=e.videoCodec);const I={direction:"sendonly",streams:i};return g&&(I.sendEncodings=g),(yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,I)).sender})}createSimulcastTransceiverSender(A,e,g,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const I={direction:"sendonly"};i&&(I.sendEncodings=i);const C=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,I);if(g.videoCodec)return A.setSimulcastTrackSender(g.videoCodec,C.sender),C.sender})}createRTCRtpSender(A){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");return this.pcManager.addPublisherTrack(A)})}attemptReconnect(A){return S(this,void 0,void 0,function*(){var e,g,i;if(!this._isClosed){if(this.attemptingReconnect){$A.warn("already attempting reconnect, returning early",this.logContext);return}(((e=this.clientConfiguration)===null||e===void 0?void 0:e.resumeConnection)===PI.DISABLED||((i=(g=this.pcManager)===null||g===void 0?void 0:g.currentState)!==null&&i!==void 0?i:Ge.NEW)===Ge.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(A),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(I){this.reconnectAttempts+=1;let C=!0;I instanceof Pe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:I})),C=!1):I instanceof tI||(this.fullReconnectOnNext=!0),C?this.handleDisconnect("reconnect",ji.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(nA.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(A){try{return this.reconnectPolicy.nextRetryDelayInMs(A)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(A){return S(this,void 0,void 0,function*(){var e,g,i;try{if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(nA.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let I;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new tI;I=yield this.join(A??this.url,this.token,this.signalOpts)}catch(C){throw C instanceof ue&&C.reason===ie.NotAllowed?new Pe("could not reconnect, token might be expired"):new tI}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(nA.SignalRestarted,I),yield this.waitForPCReconnected(),this.client.currentState!==ye.CONNECTED)throw new tI("Signal connection got severed during reconnect");(e=this.regionUrlProvider)===null||e===void 0||e.resetAttempts(),this.emit(nA.Restarted)}catch(I){const C=yield(g=this.regionUrlProvider)===null||g===void 0?void 0:g.getNextBestRegionUrl();if(C){yield this.restartConnection(C);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),I}})}resumeConnection(A){return S(this,void 0,void 0,function*(){var e;if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");if(!this.pcManager)throw new Pe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(nA.Resuming);let g;try{this.setupSignalClientCallbacks(),g=yield this.client.reconnect(this.url,this.token,this.participantSid,A)}catch(i){let I="";throw i instanceof Error&&(I=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof ue&&i.reason===ie.NotAllowed?new Pe("could not reconnect, token might be expired"):i instanceof ue&&i.reason===ie.LeaveRequest?i:new tI(I)}if(this.emit(nA.SignalResumed),g){const i=this.makeRTCConfiguration(g);this.pcManager.updateConfiguration(i),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=g.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!==ye.CONNECTED)throw new tI("Signal connection got severed during reconnect");this.client.setReconnected(),((e=this.reliableDC)===null||e===void 0?void 0:e.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),g!=null&&g.lastMessageSeq&&this.resendReliableMessagesForResume(g.lastMessageSeq),this.emit(nA.Resumed)})}waitForPCInitialConnection(A,e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,A)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=Tg.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield rg(rl),!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Tg.Connected}catch(A){throw this.pcState=Tg.Disconnected,new ue("could not establish PC connection, ".concat(A.message),ie.InternalError)}})}publishRpcResponse(A,e,g,i){return S(this,void 0,void 0,function*(){const I=new Eg({destinationIdentities:[A],kind:HA.RELIABLE,value:{case:"rpcResponse",value:new pB({requestId:e,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:g??""}})}});yield this.sendDataPacket(I,HA.RELIABLE)})}publishRpcAck(A,e){return S(this,void 0,void 0,function*(){const g=new Eg({destinationIdentities:[A],kind:HA.RELIABLE,value:{case:"rpcAck",value:new wB({requestId:e})}});yield this.sendDataPacket(g,HA.RELIABLE)})}sendDataPacket(A,e){return S(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(e),e===HA.RELIABLE&&(A.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const g=A.toBinary(),i=this.dataChannelForKind(e);if(i){if(e===HA.RELIABLE&&this.reliableMessageBuffer.push({data:g,sequence:A.sequence}),this.attemptingReconnect)return;i.send(g)}this.updateAndEmitDCBufferStatus(e)})}resendReliableMessagesForResume(A){return S(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(HA.RELIABLE);const e=this.dataChannelForKind(HA.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(A),this.reliableMessageBuffer.getAll().forEach(g=>{e.send(g.data)})),this.updateAndEmitDCBufferStatus(HA.RELIABLE)})}waitForBufferStatusLow(A){return new Promise((e,g)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(A))e();else{const i=()=>g("Engine closed");for(this.once(nA.Closing,i);!this.dcBufferStatus.get(A);)yield rg(10);this.off(nA.Closing,i),e()}}))}ensureDataTransportConnected(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var I;if(!g.pcManager)throw new Pe("PC manager is closed");const C=i?g.pcManager.subscriber:g.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!C)throw new ue("".concat(o," connection not set"),ie.InternalError);let a=!1;!i&&!g.dataChannelForKind(e,i)&&(g.createDataChannels(),a=!0),!a&&!i&&!g.pcManager.publisher.isICEConnected&&g.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&g.negotiate();const Q=g.dataChannelForKind(e,i);if((Q==null?void 0:Q.readyState)==="open")return;const n=new Date().getTime()+g.peerConnectionTimeout;for(;new Date().getTime()<n;){if(C.isICEConnected&&((I=g.dataChannelForKind(e,i))===null||I===void 0?void 0:I.readyState)==="open")return;yield rg(50)}throw new ue("could not establish ".concat(o," connection, state: ").concat(C.getICEConnectionState()),ie.InternalError)}()})}ensurePublisherConnected(A){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(A,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ge.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((A,e)=>S(this,void 0,void 0,function*(){if(!this.pcManager){e(new qa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const g=new AbortController,i=()=>{g.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),A()};this.isClosed&&e("cannot negotiate on closed engine"),this.on(nA.Closing,i),this.pcManager.publisher.once(gI.RTPVideoPayloadTypes,I=>{const C=new Map;I.forEach(o=>{const a=o.codec.toLowerCase();xx(a)&&C.set(o.payload,a)}),this.emit(nA.RTPVideoMapUpdate,C)});try{yield this.pcManager.negotiate(g),A()}catch(I){I instanceof qa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ji.RR_UNKNOWN),e(I)}finally{this.off(nA.Closing,i)}}))})}dataChannelForKind(A,e){if(e){if(A===HA.LOSSY)return this.lossyDCSub;if(A===HA.RELIABLE)return this.reliableDCSub}else{if(A===HA.LOSSY)return this.lossyDC;if(A===HA.RELIABLE)return this.reliableDC}}sendSyncState(A,e){var g,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const I=this.pcManager.subscriber.getLocalDescription(),C=this.pcManager.subscriber.getRemoteDescription(),o=(i=(g=this.signalOpts)===null||g===void 0?void 0:g.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,Q=new Array;A.forEach(n=>{n.isDesired!==o&&a.push(n.trackSid),n.isEnabled||Q.push(n.trackSid)}),this.client.sendSyncState(new HB({answer:I?to({sdp:I.sdp,type:I.type}):void 0,offer:C?to({sdp:C.sdp,type:C.type}):void 0,subscription:new HC({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:yx(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:Q,datachannelReceiveStates:this.reliableReceivedState.map((n,s)=>new PB({publisherSid:s,lastSeq:n}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const A=[],e=(g,i)=>{(g==null?void 0:g.id)!==void 0&&g.id!==null&&A.push(new OB({label:g.label,id:g.id,target:i}))};return e(this.dataChannelForKind(HA.LOSSY),Kg.PUBLISHER),e(this.dataChannelForKind(HA.RELIABLE),Kg.PUBLISHER),e(this.dataChannelForKind(HA.LOSSY,!0),Kg.SUBSCRIBER),e(this.dataChannelForKind(HA.RELIABLE,!0),Kg.SUBSCRIBER),A}clearReconnectTimeout(){this.reconnectTimeout&&ze.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){cg()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){cg()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class tI extends Error{}function dl(t){return t!==void 0&&t>13}function xl(t,A){const e=t.participantIdentity?t.participantIdentity:A.participantIdentity;t.participantIdentity=e,A.participantIdentity=e;const g=t.destinationIdentities.length!==0?t.destinationIdentities:A.destinationIdentities;t.destinationIdentities=g,A.destinationIdentities=g}class wQ{constructor(A,e){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(A),this.token=e}updateToken(A){this.token=A}isCloud(){return za(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(A){return S(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(A));const e=this.regionSettings.regions.filter(g=>!this.attemptedRegions.find(i=>i.url===g.url));if(e.length>0){const g=e[0];return this.attemptedRegions.push(g),$A.debug("next region: ".concat(g.region)),g.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(A){return S(this,void 0,void 0,function*(){const e=yield fetch("".concat(ll(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:A});if(e.ok){const g=yield e.json();return this.lastUpdateAt=Date.now(),g}else throw new ue("Could not fetch region settings: ".concat(e.statusText),e.status===401?ie.NotAllowed:ie.InternalError,e.status)})}setServerReportedRegions(A){this.regionSettings=A,this.lastUpdateAt=Date.now()}}function ll(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class pr{get info(){return this._info}validateBytesReceived(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(A&&this.bytesReceived<this.totalByteSize)throw new Wt("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Jg.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Wt("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Jg.LengthExceeded)}}constructor(A,e,g,i){this.reader=e,this.totalByteSize=g,this._info=A,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class fl extends pr{handleChunkReceived(A){var e;this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const g=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(e=this.onProgress)===null||e===void 0||e.call(this,g)}[Symbol.asyncIterator](){const A=this.reader.getReader();let e=new it,g=null,i=null;if(this.signal){const C=this.signal;i=()=>{var o;(o=e.reject)===null||o===void 0||o.call(e,C.reason)},C.addEventListener("abort",i),g=C}const I=()=>{A.releaseLock(),g&&i&&g.removeEventListener("abort",i),this.signal=void 0};return{next:()=>S(this,void 0,void 0,function*(){var C,o;try{const{done:a,value:Q}=yield Promise.race([A.read(),e.promise,(o=(C=this.outOfBandFailureRejectingFuture)===null||C===void 0?void 0:C.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return a?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(Q),{done:!1,value:Q.content})}catch(a){throw I(),a}}),return(){return S(this,void 0,void 0,function*(){return I(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var g,i,I,C;let o=new Set;const a=e.signal?A.withAbortSignal(e.signal):A;try{for(var Q=!0,n=ft(a),s;s=yield n.next(),g=s.done,!g;Q=!0){C=s.value,Q=!1;const B=C;o.add(B)}}catch(B){i={error:B}}finally{try{!Q&&!g&&(I=n.return)&&(yield I.call(n))}finally{if(i)throw i.error}}return Array.from(o)}()})}}class ul extends pr{constructor(A,e,g,i){super(A,e,g,i),this.receivedChunks=new Map}handleChunkReceived(A){var e;const g=go(A.chunkIndex),i=this.receivedChunks.get(g);if(i&&i.version>A.version)return;this.receivedChunks.set(g,A),this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const I=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(e=this.onProgress)===null||e===void 0||e.call(this,I)}[Symbol.asyncIterator](){const A=this.reader.getReader(),e=new TextDecoder("utf-8",{fatal:!0});let g=new it,i=null,I=null;if(this.signal){const o=this.signal;I=()=>{var a;(a=g.reject)===null||a===void 0||a.call(g,o.reason)},o.addEventListener("abort",I),i=o}const C=()=>{A.releaseLock(),i&&I&&i.removeEventListener("abort",I),this.signal=void 0};return{next:()=>S(this,void 0,void 0,function*(){var o,a;try{const{done:Q,value:n}=yield Promise.race([A.read(),g.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);if(Q)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(n);let s;try{s=e.decode(n.content)}catch(B){throw new Wt("Cannot decode datastream chunk ".concat(n.chunkIndex," as text: ").concat(B),Jg.DecodeFailed)}return{done:!1,value:s}}}catch(Q){throw C(),Q}}),return(){return S(this,void 0,void 0,function*(){return C(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var g,i,I,C;let o="";const a=e.signal?A.withAbortSignal(e.signal):A;try{for(var Q=!0,n=ft(a),s;s=yield n.next(),g=s.done,!g;Q=!0)C=s.value,Q=!1,o+=C}catch(B){i={error:B}}finally{try{!Q&&!g&&(I=n.return)&&(yield I.call(n))}finally{if(i)throw i.error}}return o}()})}}class Dl{constructor(){this.log=$A,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(A,e){if(this.textStreamHandlers.has(A))throw new Wt('A text stream handler for topic "'.concat(A,'" has already been set.'),Jg.HandlerAlreadyRegistered);this.textStreamHandlers.set(A,e)}unregisterTextStreamHandler(A){this.textStreamHandlers.delete(A)}registerByteStreamHandler(A,e){if(this.byteStreamHandlers.has(A))throw new Wt('A byte stream handler for topic "'.concat(A,'" has already been set.'),Jg.HandlerAlreadyRegistered);this.byteStreamHandlers.set(A,e)}unregisterByteStreamHandler(A){this.byteStreamHandlers.delete(A)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(A){var e,g,i,I;const C=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A),o=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A);if(C.length>0||o.length>0){const a=new Wt("Participant ".concat(A," unexpectedly disconnected in the middle of sending data"),Jg.AbnormalEnd);for(const[Q,n]of o)(g=(e=n.outOfBandFailureRejectingFuture).reject)===null||g===void 0||g.call(e,a),this.byteStreamControllers.delete(Q);for(const[Q,n]of C)(I=(i=n.outOfBandFailureRejectingFuture).reject)===null||I===void 0||I.call(i,a),this.textStreamControllers.delete(Q)}}handleDataStreamPacket(A){return S(this,void 0,void 0,function*(){switch(A.value.case){case"streamHeader":return this.handleStreamHeader(A.value.value,A.participantIdentity);case"streamChunk":return this.handleStreamChunk(A.value.value);case"streamTrailer":return this.handleStreamTrailer(A.value.value);default:throw new Error('DataPacket of value "'.concat(A.value.case,'" is not data stream related!'))}})}handleStreamHeader(A,e){return S(this,void 0,void 0,function*(){var g;if(A.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(A.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",A.topic);return}let I;const C=new it,o={id:A.streamId,name:(g=A.contentHeader.value.name)!==null&&g!==void 0?g:"unknown",mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:go(A.timestamp),attributes:A.attributes},a=new ReadableStream({start:Q=>{if(I=Q,this.textStreamControllers.has(A.streamId))throw new Wt("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),Jg.AlreadyOpened);this.byteStreamControllers.set(A.streamId,{info:o,controller:I,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:C})}});i(new fl(o,a,go(A.totalLength),C),{identity:e})}else if(A.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(A.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",A.topic);return}let I;const C=new it,o={id:A.streamId,mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:Number(A.timestamp),attributes:A.attributes},a=new ReadableStream({start:Q=>{if(I=Q,this.textStreamControllers.has(A.streamId))throw new Wt("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),Jg.AlreadyOpened);this.textStreamControllers.set(A.streamId,{info:o,controller:I,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:C})}});i(new ul(o,a,go(A.totalLength),C),{identity:e})}})}handleStreamChunk(A){const e=this.byteStreamControllers.get(A.streamId);e&&A.content.length>0&&e.controller.enqueue(A);const g=this.textStreamControllers.get(A.streamId);g&&A.content.length>0&&g.controller.enqueue(A)}handleStreamTrailer(A){const e=this.textStreamControllers.get(A.streamId);e&&(e.info.attributes=Object.assign(Object.assign({},e.info.attributes),A.attributes),e.controller.close(),this.textStreamControllers.delete(A.streamId));const g=this.byteStreamControllers.get(A.streamId);g&&(g.info.attributes=Object.assign(Object.assign({},g.info.attributes),A.attributes),g.controller.close(),this.byteStreamControllers.delete(A.streamId))}}class mr{constructor(A,e,g){this.writableStream=A,this.defaultWriter=A.getWriter(),this.onClose=g,this.info=e}write(A){return this.defaultWriter.write(A)}close(){return S(this,void 0,void 0,function*(){var A;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(A=this.onClose)===null||A===void 0||A.call(this)})}}class _l extends mr{}class wl extends mr{}const yr=15e3;class pl{constructor(A,e){this.engine=A,this.log=e}setupEngine(A){this.engine=A}sendText(A,e){return S(this,void 0,void 0,function*(){var g;const i=crypto.randomUUID(),C=new TextEncoder().encode(A).byteLength,o=(g=e==null?void 0:e.attachments)===null||g===void 0?void 0:g.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),Q=(s,B)=>{var E;a[B]=s;const d=a.reduce((c,h)=>c+h,0);(E=e==null?void 0:e.onProgress)===null||E===void 0||E.call(e,d)},n=yield this.streamText({streamId:i,totalSize:C,destinationIdentities:e==null?void 0:e.destinationIdentities,topic:e==null?void 0:e.topic,attachedStreamIds:o,attributes:e==null?void 0:e.attributes});return yield n.write(A),Q(1,0),yield n.close(),e!=null&&e.attachments&&o&&(yield Promise.all(e.attachments.map((s,B)=>S(this,void 0,void 0,function*(){return this._sendFile(o[B],s,{topic:e.topic,mimeType:s.type,onProgress:E=>{Q(E,B+1)}})})))),n.info})}streamText(A){return S(this,void 0,void 0,function*(){var e,g;const i=(e=A==null?void 0:A.streamId)!==null&&e!==void 0?e:crypto.randomUUID(),I={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(g=A==null?void 0:A.topic)!==null&&g!==void 0?g:"",size:A==null?void 0:A.totalSize,attributes:A==null?void 0:A.attributes},C=new ua({streamId:i,mimeType:I.mimeType,topic:I.topic,timestamp:_i(I.timestamp),totalLength:_i(A==null?void 0:A.totalSize),attributes:I.attributes,contentHeader:{case:"textHeader",value:new MB({version:A==null?void 0:A.version,attachedStreamIds:A==null?void 0:A.attachedStreamIds,replyToStreamId:A==null?void 0:A.replyToStreamId,operationType:(A==null?void 0:A.type)==="update"?fa.UPDATE:fa.CREATE})}}),o=A==null?void 0:A.destinationIdentities,a=new Eg({destinationIdentities:o,value:{case:"streamHeader",value:C}});yield this.engine.sendDataPacket(a,HA.RELIABLE);let Q=0;const n=this.engine,s=new WritableStream({write(d){return S(this,void 0,void 0,function*(){for(const c of wx(d,yr)){yield n.waitForBufferStatusLow(HA.RELIABLE);const h=new Da({content:c,streamId:i,chunkIndex:_i(Q)}),r=new Eg({destinationIdentities:o,value:{case:"streamChunk",value:h}});yield n.sendDataPacket(r,HA.RELIABLE),Q+=1}})},close(){return S(this,void 0,void 0,function*(){const d=new _a({streamId:i}),c=new Eg({destinationIdentities:o,value:{case:"streamTrailer",value:d}});yield n.sendDataPacket(c,HA.RELIABLE)})},abort(d){console.log("Sink error:",d)}});let B=()=>S(this,void 0,void 0,function*(){yield E.close()});n.once(nA.Closing,B);const E=new _l(s,I,()=>this.engine.off(nA.Closing,B));return E})}sendFile(A,e){return S(this,void 0,void 0,function*(){const g=crypto.randomUUID();return yield this._sendFile(g,A,e),{id:g}})}_sendFile(A,e,g){return S(this,void 0,void 0,function*(){var i;const I=yield this.streamBytes({streamId:A,totalSize:e.size,name:e.name,mimeType:(i=g==null?void 0:g.mimeType)!==null&&i!==void 0?i:e.type,topic:g==null?void 0:g.topic,destinationIdentities:g==null?void 0:g.destinationIdentities}),C=e.stream().getReader();for(;;){const{done:o,value:a}=yield C.read();if(o)break;yield I.write(a)}return yield I.close(),I.info})}streamBytes(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C;const o=(e=A==null?void 0:A.streamId)!==null&&e!==void 0?e:crypto.randomUUID(),a=A==null?void 0:A.destinationIdentities,Q={id:o,mimeType:(g=A==null?void 0:A.mimeType)!==null&&g!==void 0?g:"application/octet-stream",topic:(i=A==null?void 0:A.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:A==null?void 0:A.attributes,size:A==null?void 0:A.totalSize,name:(I=A==null?void 0:A.name)!==null&&I!==void 0?I:"unknown"},n=new ua({totalLength:_i((C=Q.size)!==null&&C!==void 0?C:0),mimeType:Q.mimeType,streamId:o,topic:Q.topic,timestamp:_i(Date.now()),attributes:Q.attributes,contentHeader:{case:"byteHeader",value:new FB({name:Q.name})}}),s=new Eg({destinationIdentities:a,value:{case:"streamHeader",value:n}});yield this.engine.sendDataPacket(s,HA.RELIABLE);let B=0;const E=new sg,d=this.engine,c=this.log,h=new WritableStream({write(f){return S(this,void 0,void 0,function*(){const _=yield E.lock();let l=0;try{for(;l<f.byteLength;){const D=f.slice(l,l+yr);yield d.waitForBufferStatusLow(HA.RELIABLE);const p=new Eg({destinationIdentities:a,value:{case:"streamChunk",value:new Da({content:D,streamId:o,chunkIndex:_i(B)})}});yield d.sendDataPacket(p,HA.RELIABLE),B+=1,l+=D.byteLength}}finally{_()}})},close(){return S(this,void 0,void 0,function*(){const f=new _a({streamId:o}),_=new Eg({destinationIdentities:a,value:{case:"streamTrailer",value:f}});yield d.sendDataPacket(_,HA.RELIABLE)})},abort(f){c.error("Sink error:",f)}});return new wl(h,Q)})}}class br extends AA{constructor(A,e,g,i,I){super(A,g,I),this.sid=e,this.receiver=i}get isLocal(){return!1}setMuted(A){this.isMuted!==A&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?oA.Muted:oA.Unmuted,this))}setMediaStream(A){this.mediaStream=A;const e=g=>{g.track===this._mediaStreamTrack&&(A.removeEventListener("removetrack",e),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(oA.Ended,this))};A.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var A;return!((A=this.receiver)===null||A===void 0)&&A.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(A){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=A: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(),xQ)),bx()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const A=()=>{var e;this.timeSyncHandle=requestAnimationFrame(()=>A());const g=(e=this.receiver)===null||e===void 0?void 0:e.getSynchronizationSources()[0];if(g){const{timestamp:i,rtpTimestamp:I}=g;I&&this.rtpTimestamp!==I&&(this.emit(oA.TimeSyncUpdate,{timestamp:i,rtpTimestamp:I}),this.rtpTimestamp=I)}};A()}}class ml extends br{constructor(A,e,g,i,I,C){super(A,e,AA.Kind.Audio,g,C),this.monitorReceiver=()=>S(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=io(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],I&&(this.sinkId=I.deviceId)}setVolume(A){var e;for(const g of this.attachedElements)this.audioContext?(e=this.gainNode)===null||e===void 0||e.gain.setTargetAtTime(A,0,.1):g.volume=A;gt()&&this._mediaStreamTrack._setVolume(A),this.elementVolume=A}getVolume(){if(this.elementVolume)return this.elementVolume;if(gt())return 1;let A=0;return this.attachedElements.forEach(e=>{e.volume>A&&(A=e.volume)}),A}setSinkId(A){return S(this,void 0,void 0,function*(){this.sinkId=A,yield Promise.all(this.attachedElements.map(e=>{if(Za(e))return e.setSinkId(A)}))})}attach(A){const e=this.attachedElements.length===0;return A?super.attach(A):A=super.attach(),this.sinkId&&Za(A)&&A.setSinkId(this.sinkId).catch(g=>{this.log.error("Failed to set sink id on remote audio track",g,this.logContext)}),this.audioContext&&e&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,A),A.volume=0,A.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),A}detach(A){let e;return A?(e=super.detach(A),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(e=super.detach(),this.disconnectWebAudio()),e}setAudioContext(A){this.audioContext=A,A&&this.attachedElements.length>0?this.connectWebAudio(A,this.attachedElements[0]):A||this.disconnectWebAudio()}setWebAudioPlugins(A){this.webAudioPluginNodes=A,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(A,e){this.disconnectWebAudio(),this.sourceNode=A.createMediaStreamSource(e.srcObject);let g=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{g.connect(i),g=i}),this.gainNode=A.createGain(),g.connect(this.gainNode),this.gainNode.connect(A.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),A.state!=="running"&&A.resume().then(()=>{A.state!=="running"&&this.emit(oA.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(oA.AudioPlaybackFailed,i)})}disconnectWebAudio(){var A,e;(A=this.gainNode)===null||A===void 0||A.disconnect(),(e=this.sourceNode)===null||e===void 0||e.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let e;return A.forEach(g=>{g.type==="inbound-rtp"&&(e={type:"audio",streamId:g.id,timestamp:g.timestamp,jitter:g.jitter,bytesReceived:g.bytesReceived,concealedSamples:g.concealedSamples,concealmentEvents:g.concealmentEvents,silentConcealedSamples:g.silentConcealedSamples,silentConcealmentEvents:g.silentConcealmentEvents,totalAudioEnergy:g.totalAudioEnergy,totalSamplesDuration:g.totalSamplesDuration})}),e})}}const pQ=100;class yl extends br{constructor(A,e,g,i,I){super(A,e,AA.Kind.Video,g,I),this.elementInfos=[],this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const C=yield this.getReceiverStats();C&&this.prevStats&&this.receiver&&(this._currentBitrate=io(C,this.prevStats)),this.prevStats=C}),this.debouncedHandleResize=rQ(()=>{this.updateDimensions()},pQ),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(A){super.setStreamState(A),console.log("setStreamState",A),A===AA.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(A){super.setMuted(A),this.attachedElements.forEach(e=>{A?AI(this._mediaStreamTrack,e):$i(this._mediaStreamTrack,e)})}attach(A){if(A?super.attach(A):A=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(e=>e.element===A)===void 0){const e=new bl(A);this.observeElementInfo(e)}return A}observeElementInfo(A){this.adaptiveStreamSettings&&this.elementInfos.find(e=>e===A)===void 0?(A.handleResize=()=>{this.debouncedHandleResize()},A.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(A),A.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(A){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const e=this.elementInfos.filter(g=>g===A);for(const g of e)g.stopObserving();this.elementInfos=this.elementInfos.filter(g=>g!==A),this.updateVisibility(),this.debouncedHandleResize()}detach(A){let e=[];if(A)return this.stopObservingElement(A),super.detach(A);e=super.detach();for(const g of e)this.stopObservingElement(g);return e}getDecoderImplementation(){var A;return(A=this.prevStats)===null||A===void 0?void 0:A.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let e,g="",i=new Map;return A.forEach(I=>{I.type==="inbound-rtp"?(g=I.codecId,e={type:"video",streamId:I.id,framesDecoded:I.framesDecoded,framesDropped:I.framesDropped,framesReceived:I.framesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost,frameWidth:I.frameWidth,frameHeight:I.frameHeight,pliCount:I.pliCount,firCount:I.firCount,nackCount:I.nackCount,jitter:I.jitter,timestamp:I.timestamp,bytesReceived:I.bytesReceived,decoderImplementation:I.decoderImplementation}):I.type==="codec"&&i.set(I.id,I)}),e&&g!==""&&i.get(g)&&(e.mimeType=i.get(g).mimeType),e})}stopObservingElement(A){const e=this.elementInfos.filter(g=>g.element===A);for(const g of e)this.stopObservingElementInfo(g)}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(A){var e,g;const i=this.elementInfos.reduce((a,Q)=>Math.max(a,Q.visibilityChangedAt||0),0),I=!((g=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&g!==void 0)||g?this.isInBackground:!1,C=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!I||C;if(!(this.lastVisible===o&&!A)){if(!o&&Date.now()-i<pQ){ze.setTimeout(()=>{this.updateVisibility()},pQ);return}this.lastVisible=o,this.emit(oA.VisibilityChanged,o,this)}}updateDimensions(){var A,e;let g=0,i=0;const I=this.getPixelDensity();for(const C of this.elementInfos){const o=C.width()*I,a=C.height()*I;o+a>g+i&&(g=o,i=a)}((A=this.lastDimensions)===null||A===void 0?void 0:A.width)===g&&((e=this.lastDimensions)===null||e===void 0?void 0:e.height)===i||(this.lastDimensions={width:g,height:i},this.emit(oA.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var A;const e=(A=this.adaptiveStreamSettings)===null||A===void 0?void 0:A.pixelDensity;return e==="screen"?OE():e||(OE()>2?2:1)}}class bl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(A,e){this.onVisibilityChanged=g=>{var i;const{target:I,isIntersecting:C}=g;I===this.element&&(this.isIntersecting=C,this.isPiP=gC(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var g,i,I;(i=(g=window.documentPictureInPicture)===null||g===void 0?void 0:g.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=gC(this.element),(I=this.handleVisibilityChanged)===null||I===void 0||I.call(this)},this.onLeavePiP=()=>{var g;this.isPiP=gC(this.element),(g=this.handleVisibilityChanged)===null||g===void 0||g.call(this)},this.element=A,this.isIntersecting=e??mQ(A),this.isPiP=cg()&&gC(A),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var A,e,g;this.isIntersecting=mQ(this.element),this.isPiP=gC(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,jE().observe(this.element),VE().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(A=window.documentPictureInPicture)===null||A===void 0||A.addEventListener("enter",this.onEnterPiP),(g=(e=window.documentPictureInPicture)===null||e===void 0?void 0:e.window)===null||g===void 0||g.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var A,e,g,i,I;(A=jE())===null||A===void 0||A.unobserve(this.element),(e=VE())===null||e===void 0||e.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(g=window.documentPictureInPicture)===null||g===void 0||g.removeEventListener("enter",this.onEnterPiP),(I=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||I===void 0||I.removeEventListener("pagehide",this.onLeavePiP)}}function gC(t){var A,e;return document.pictureInPictureElement===t?!0:!((A=window.documentPictureInPicture)===null||A===void 0)&&A.window?mQ(t,(e=window.documentPictureInPicture)===null||e===void 0?void 0:e.window):!1}function mQ(t,A){const e=A||window;let g=t.offsetTop,i=t.offsetLeft;const I=t.offsetWidth,C=t.offsetHeight,{hidden:o}=t,{display:a}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,g+=t.offsetTop,i+=t.offsetLeft;return g<e.pageYOffset+e.innerHeight&&i<e.pageXOffset+e.innerWidth&&g+C>e.pageYOffset&&i+I>e.pageXOffset&&!o&&a!=="none"}class wt extends At.EventEmitter{constructor(A,e,g,i){var I;super(),this.metadataMuted=!1,this.encryption=lg.NONE,this.log=$A,this.handleMuted=()=>{this.emit(oA.Muted)},this.handleUnmuted=()=>{this.emit(oA.Unmuted)},this.log=lt((I=i==null?void 0:i.loggerName)!==null&&I!==void 0?I:vg.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=A,this.trackSid=e,this.trackName=g,this.source=AA.Source.Unknown}setTrack(A){this.track&&(this.track.off(oA.Muted,this.handleMuted),this.track.off(oA.Unmuted,this.handleUnmuted)),this.track=A,A&&(A.on(oA.Muted,this.handleMuted),A.on(oA.Unmuted,this.handleUnmuted))}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),WA(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==lg.NONE}get audioTrack(){if(It(this.track))return this.track}get videoTrack(){if(Zt(this.track))return this.track}updateInfo(A){this.trackSid=A.sid,this.trackName=A.name,this.source=AA.sourceFromProto(A.source),this.mimeType=A.mimeType,this.kind===AA.Kind.Video&&A.width>0&&(this.dimensions={width:A.width,height:A.height},this.simulcasted=A.simulcast),this.encryption=A.encryption,this.trackInfo=A,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:A}))}}(function(t){(function(A){A.Desired="desired",A.Subscribed="subscribed",A.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(A){A.Allowed="allowed",A.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(wt||(wt={}));class yQ extends wt{get isUpstreamPaused(){var A;return(A=this.track)===null||A===void 0?void 0:A.isUpstreamPaused}constructor(A,e,g,i){super(A,e.sid,e.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(oA.Ended)},this.handleCpuConstrained=()=>{this.track&&Zt(this.track)&&this.emit(oA.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(g)}setTrack(A){this.track&&(this.track.off(oA.Ended,this.handleTrackEnded),this.track.off(oA.CpuConstrained,this.handleCpuConstrained)),super.setTrack(A),A&&(A.on(oA.Ended,this.handleTrackEnded),A.on(oA.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 S(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.mute()})}unmute(){return S(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.resumeUpstream()})}getTrackFeatures(){var A;if(It(this.track)){const e=this.track.getSourceTrackSettings(),g=new Set;return e.autoGainControl&&g.add(je.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&g.add(je.TF_ECHO_CANCELLATION),e.noiseSuppression&&g.add(je.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&g.add(je.TF_STEREO),!((A=this.options)===null||A===void 0)&&A.dtx||g.add(je.TF_NO_DTX),this.track.enhancedNoiseCancellation&&g.add(je.TF_ENHANCED_NOISE_CANCELLATION),Array.from(g.values())}else return[]}}function oo(t,A){return S(this,void 0,void 0,function*(){t??(t={});let e=!1;const{audioProcessor:g,videoProcessor:i,optionsWithoutProcessor:I}=Ar(t);let C=I.audio,o=I.video;if(g&&typeof I.audio=="object"&&(I.audio.processor=g),i&&typeof I.video=="object"&&(I.video.processor=i),t.audio&&typeof I.audio=="object"&&typeof I.audio.deviceId=="string"){const s=I.audio.deviceId;I.audio.deviceId={exact:s},e=!0,C=Object.assign(Object.assign({},I.audio),{deviceId:{ideal:s}})}if(I.video&&typeof I.video=="object"&&typeof I.video.deviceId=="string"){const s=I.video.deviceId;I.video.deviceId={exact:s},e=!0,o=Object.assign(Object.assign({},I.video),{deviceId:{ideal:s}})}(I.audio===!0||typeof I.audio=="object"&&!I.audio.deviceId)&&(I.audio={deviceId:"default"}),I.video===!0?I.video={deviceId:"default"}:typeof I.video=="object"&&!I.video.deviceId&&(I.video.deviceId="default");const a=ZE(I,Br,Er),Q=CQ(a),n=navigator.mediaDevices.getUserMedia(Q);I.audio&&(We.userMediaPromiseMap.set("audioinput",n),n.catch(()=>We.userMediaPromiseMap.delete("audioinput"))),I.video&&(We.userMediaPromiseMap.set("videoinput",n),n.catch(()=>We.userMediaPromiseMap.delete("videoinput")));try{const s=yield n;return yield Promise.all(s.getTracks().map(B=>S(this,void 0,void 0,function*(){const E=B.kind==="audio";let d=E?a.audio:a.video;(typeof d=="boolean"||!d)&&(d={});let c;const h=E?Q.audio:Q.video;typeof h!="boolean"&&(c=h);const r=B.getSettings().deviceId;c!=null&&c.deviceId&&Xt(c.deviceId)!==r?c.deviceId=r:c||(c={deviceId:r});const f=gl(B,c,A);return f.kind===AA.Kind.Video?f.source=AA.Source.Camera:f.kind===AA.Kind.Audio&&(f.source=AA.Source.Microphone),f.mediaStream=s,It(f)&&g?yield f.setProcessor(g):Zt(f)&&i&&(yield f.setProcessor(i)),f})))}catch(s){if(!e)throw s;return oo(Object.assign(Object.assign({},t),{audio:C,video:o}),A)}})}function Nl(t){return S(this,void 0,void 0,function*(){return(yield oo({audio:!1,video:!0}))[0]})}function Sl(t){return S(this,void 0,void 0,function*(){return(yield oo({audio:!0,video:!1}))[0]})}var Ai;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(Ai||(Ai={}));function kl(t){switch(t){case HI.EXCELLENT:return Ai.Excellent;case HI.GOOD:return Ai.Good;case HI.POOR:return Ai.Poor;case HI.LOST:return Ai.Lost;default:return Ai.Unknown}}class Nr extends At.EventEmitter{get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions)===null||A===void 0?void 0:A.loggerContextCb)===null||e===void 0?void 0:e.call(A))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(A=>A.isEncrypted)}get isAgent(){var A;return((A=this.permissions)===null||A===void 0?void 0:A.agent)||this.kind===OI.AGENT}get isActive(){var A;return((A=this.participantInfo)===null||A===void 0?void 0:A.state)===Wi.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(A,e,g,i,I,C){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:OI.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ai.Unknown,this.log=$A,this.log=lt((a=C==null?void 0:C.loggerName)!==null&&a!==void 0?a:vg.Participant),this.loggerOptions=C,this.setMaxListeners(100),this.sid=A,this.identity=e,this.name=g,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=I??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(A){for(const[,e]of this.trackPublications)if(e.source===A)return e}getTrackPublicationByName(A){for(const[,e]of this.trackPublications)if(e.trackName===A)return e}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new it,this.once(QA.Active,()=>{var A,e;(e=(A=this.activeFuture)===null||A===void 0?void 0:A.resolve)===null||e===void 0||e.call(A),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var A;const e=this.getTrackPublication(AA.Source.Camera);return!(!((A=e==null?void 0:e.isMuted)!==null&&A!==void 0)||A)}get isMicrophoneEnabled(){var A;const e=this.getTrackPublication(AA.Source.Microphone);return!(!((A=e==null?void 0:e.isMuted)!==null&&A!==void 0)||A)}get isScreenShareEnabled(){return!!this.getTrackPublication(AA.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(A){var e;return this.participantInfo&&this.participantInfo.sid===A.sid&&this.participantInfo.version>A.version?!1:(this.identity=A.identity,this.sid=A.sid,this._setName(A.name),this._setMetadata(A.metadata),this._setAttributes(A.attributes),A.state===Wi.ACTIVE&&((e=this.participantInfo)===null||e===void 0?void 0:e.state)!==Wi.ACTIVE&&this.emit(QA.Active),A.permission&&this.setPermissions(A.permission),this.participantInfo=A,!0)}_setMetadata(A){const e=this.metadata!==A,g=this.metadata;this.metadata=A,e&&this.emit(QA.ParticipantMetadataChanged,g)}_setName(A){const e=this.name!==A;this.name=A,e&&this.emit(QA.ParticipantNameChanged,A)}_setAttributes(A){const e=Nx(this.attributes,A);this._attributes=A,Object.keys(e).length>0&&this.emit(QA.AttributesChanged,e)}setPermissions(A){var e,g,i,I,C,o;const a=this.permissions,Q=A.canPublish!==((e=this.permissions)===null||e===void 0?void 0:e.canPublish)||A.canSubscribe!==((g=this.permissions)===null||g===void 0?void 0:g.canSubscribe)||A.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||A.hidden!==((I=this.permissions)===null||I===void 0?void 0:I.hidden)||A.recorder!==((C=this.permissions)===null||C===void 0?void 0:C.recorder)||A.canPublishSources.length!==this.permissions.canPublishSources.length||A.canPublishSources.some((n,s)=>{var B;return n!==((B=this.permissions)===null||B===void 0?void 0:B.canPublishSources[s])})||A.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=A,Q&&this.emit(QA.ParticipantPermissionsChanged,a),Q}setIsSpeaking(A){A!==this.isSpeaking&&(this.isSpeaking=A,A&&(this.lastSpokeAt=new Date),this.emit(QA.IsSpeakingChanged,A))}setConnectionQuality(A){const e=this._connectionQuality;this._connectionQuality=kl(A),e!==this._connectionQuality&&this.emit(QA.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var A,e;this.activeFuture&&((e=(A=this.activeFuture).reject)===null||e===void 0||e.call(A,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(A){this.audioContext=A,this.audioTrackPublications.forEach(e=>It(e.track)&&e.track.setAudioContext(A))}addTrackPublication(A){A.on(oA.Muted,()=>{this.emit(QA.TrackMuted,A)}),A.on(oA.Unmuted,()=>{this.emit(QA.TrackUnmuted,A)});const e=A;switch(e.track&&(e.track.sid=A.trackSid),this.trackPublications.set(A.trackSid,A),A.kind){case AA.Kind.Audio:this.audioTrackPublications.set(A.trackSid,A);break;case AA.Kind.Video:this.videoTrackPublications.set(A.trackSid,A);break}}}function Rl(t){var A,e,g;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new TB({participantIdentity:(A=t.participantIdentity)!==null&&A!==void 0?A:"",participantSid:(e=t.participantSid)!==null&&e!==void 0?e:"",allTracks:(g=t.allowAll)!==null&&g!==void 0?g:!1,trackSids:t.allowedTrackSids||[]})}class Gl extends Nr{constructor(A,e,g,i,I,C){super(A,e,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=lg.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new it)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,a,Q,n,s,B;this.reconnectFuture&&(this.reconnectFuture.promise.catch(E=>this.log.warn(E.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((n=(Q=this.signalConnectedFuture).reject)===null||n===void 0||n.call(Q,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(B=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||B===void 0||B.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,Q;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new it),(Q=(a=this.signalConnectedFuture).resolve)===null||Q===void 0||Q.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:Q,message:n}=o,s=this.pendingSignalRequests.get(a);s&&(Q!==ka.OK&&s.reject(new vE(n,Q)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,Q=null,n=null;a.value.case==="payload"?Q=a.value.value:a.value.case==="error"&&(n=Me.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,Q,n);break;case"rpcAck":let s=o.value.value;this.handleIncomingRpcAck(s.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(o=>Rl(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),WA(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),WA(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),WA(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.onTrackCpuConstrained=(o,a)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),WA(a))),this.emit(QA.LocalTrackCpuConstrained,o,a)},this.handleSubscribedQualityUpdate=o=>S(this,void 0,void 0,function*(){var a,Q,n,s,B;if(!(!((B=this.roomOptions)===null||B===void 0)&&B.dynacast))return;const E=this.videoTrackPublications.get(o.trackSid);if(!E){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!E.videoTrack)return;const d=yield E.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var c=!0,h=ft(d),r;r=yield h.next(),a=r.done,!a;c=!0){s=r.value,c=!1;const f=s;Cx(f)&&(this.log.debug("publish ".concat(f," for ").concat(E.videoTrack.sid),Object.assign(Object.assign({},this.logContext),WA(E))),yield this.publishAdditionalCodecForTrack(E.videoTrack,f,E.options))}}catch(f){Q={error:f}}finally{try{!c&&!a&&(n=h.return)&&(yield n.call(h))}finally{if(Q)throw Q.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>S(this,void 0,void 0,function*(){if(o.source===AA.Source.ScreenShare||o.source===AA.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),WA(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(_t(o)||zt(o))try{if(cg())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===AA.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),WA(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),WA(o))),_t(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),WA(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=g,this.roomOptions=i,this.setupEngine(g),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=I,this.roomOutgoingDataStreamManager=C}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==lg.NONE}getTrackPublication(A){const e=super.getTrackPublication(A);if(e)return e}getTrackPublicationByName(A){const e=super.getTrackPublicationByName(A);if(e)return e}setupEngine(A){var e;this.engine=A,this.engine.on(nA.RemoteMute,(g,i)=>{const I=this.trackPublications.get(g);!I||!I.track||(i?I.mute():I.unmute())}),!((e=this.signalConnectedFuture)===null||e===void 0)&&e.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(nA.Connected,this.handleReconnected).on(nA.SignalConnected,this.handleSignalConnected).on(nA.SignalRestarted,this.handleReconnected).on(nA.SignalResumed,this.handleReconnected).on(nA.Restarting,this.handleReconnecting).on(nA.Resuming,this.handleReconnecting).on(nA.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(nA.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(nA.Closing,this.handleClosing).on(nA.SignalRequestResponse,this.handleSignalRequestResponse).on(nA.DataPacketReceived,this.handleDataPacket)}setMetadata(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:A})})}setName(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:A})})}setAttributes(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:A})})}requestMetadataUpdate(A){return S(this,arguments,void 0,function(e){var g=this;let{metadata:i,name:I,attributes:C}=e;return function*(){return new Promise((o,a)=>S(g,void 0,void 0,function*(){var Q,n;try{let s=!1;const B=yield this.engine.client.sendUpdateLocalMetadata((Q=i??this.metadata)!==null&&Q!==void 0?Q:"",(n=I??this.name)!==null&&n!==void 0?n:"",C),E=performance.now();for(this.pendingSignalRequests.set(B,{resolve:o,reject:d=>{a(d),s=!0},values:{name:I,metadata:i,attributes:C}});performance.now()-E<5e3&&!s;){if((!I||this.name===I)&&(!i||this.metadata===i)&&(!C||Object.entries(C).every(d=>{let[c,h]=d;return this.attributes[c]===h||h===""&&!this.attributes[c]}))){this.pendingSignalRequests.delete(B),o();return}yield rg(50)}a(new vE("Request to update local metadata timed out","TimeoutError"))}catch(s){s instanceof Error&&a(s)}}))}()})}setCameraEnabled(A,e,g){return this.setTrackEnabled(AA.Source.Camera,A,e,g)}setMicrophoneEnabled(A,e,g){return this.setTrackEnabled(AA.Source.Microphone,A,e,g)}setScreenShareEnabled(A,e,g){return this.setTrackEnabled(AA.Source.ScreenShare,A,e,g)}setPermissions(A){const e=this.permissions,g=super.setPermissions(A);return g&&e&&this.emit(QA.ParticipantPermissionsChanged,e),g}setE2EEEnabled(A){return S(this,void 0,void 0,function*(){this.encryptionType=A?lg.GCM:lg.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(A,e,g,i){return S(this,void 0,void 0,function*(){var I,C;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:A,enabled:e})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(A);if(e)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(A)){const Q=yield this.waitForPendingPublicationOfSource(A);return Q||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A})),yield Q==null?void 0:Q.unmute(),Q}this.pendingPublishing.add(A);try{switch(A){case AA.Source.Camera:a=yield this.createTracks({video:(I=g)!==null&&I!==void 0?I:!0});break;case AA.Source.Microphone:a=yield this.createTracks({audio:(C=g)!==null&&C!==void 0?C:!0});break;case AA.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},g));break;default:throw new Dt(A)}}catch(Q){throw a==null||a.forEach(n=>{n.stop()}),Q instanceof Error&&this.emit(QA.MediaDevicesError,Q,oQ(A)),this.pendingPublishing.delete(A),Q}for(const Q of a){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),g);A===AA.Source.Microphone&&It(Q)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),Q.startPreConnectBuffer())}try{const Q=[];for(const s of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),WA(s))),Q.push(this.publishTrack(s,i));[o]=yield Promise.all(Q)}catch(Q){throw a==null||a.forEach(n=>{n.stop()}),Q}finally{this.pendingPublishing.delete(A)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(A)&&(o=yield this.waitForPendingPublicationOfSource(A),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A}))),o&&o.track)if(A===AA.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(AA.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(AA.Source.Camera)||this.pendingPublishing.has(AA.Source.Microphone))){this.pendingPublishing.add(AA.Source.Camera),this.pendingPublishing.add(AA.Source.Microphone);try{const A=yield this.createTracks({audio:!0,video:!0});yield Promise.all(A.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(AA.Source.Camera),this.pendingPublishing.delete(AA.Source.Microphone)}}})}createTracks(A){return S(this,void 0,void 0,function*(){var e,g;A??(A={});const i=ZE(A,(e=this.roomOptions)===null||e===void 0?void 0:e.audioCaptureDefaults,(g=this.roomOptions)===null||g===void 0?void 0:g.videoCaptureDefaults);try{return(yield oo(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(It(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=AA.Source.Microphone,this.emit(QA.AudioStreamAcquired)),Zt(o)&&(this.cameraError=void 0,o.source=AA.Source.Camera),o))}catch(I){throw I instanceof Error&&(A.audio&&(this.microphoneError=I),A.video&&(this.cameraError=I)),I}})}createScreenTracks(A){return S(this,void 0,void 0,function*(){if(A===void 0&&(A={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ta("getDisplayMedia not supported");A.resolution===void 0&&!Bx()&&(A.resolution=ja.h1080fps30.resolution);const e=mx(A),g=yield navigator.mediaDevices.getDisplayMedia(e),i=g.getVideoTracks();if(i.length===0)throw new Dt("no video track found");const I=new Co(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});I.source=AA.Source.ScreenShare,A.contentHint&&(I.mediaStreamTrack.contentHint=A.contentHint);const C=[I];if(g.getAudioTracks().length>0){this.emit(QA.AudioStreamAcquired);const o=new Io(g.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=AA.Source.ScreenShareAudio,C.push(o)}return C})}publishTrack(A,e){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(A,e)})}publishOrRepublishTrack(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,Q,n;_t(g)&&g.setAudioContext(I.audioContext),yield(o=I.reconnectFuture)===null||o===void 0?void 0:o.promise,I.republishPromise&&!C&&(yield I.republishPromise),eI(g)&&I.pendingPublishPromises.has(g)&&(yield I.pendingPublishPromises.get(g));let s;if(g instanceof MediaStreamTrack)s=g.getConstraints();else{s=g.constraints;let r;switch(g.source){case AA.Source.Microphone:r="audioinput";break;case AA.Source.Camera:r="videoinput"}r&&I.activeDeviceMap.has(r)&&(s=Object.assign(Object.assign({},s),{deviceId:I.activeDeviceMap.get(r)}))}if(g instanceof MediaStreamTrack)switch(g.kind){case"audio":g=new Io(g,s,!0,I.audioContext,{loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});break;case"video":g=new Co(g,s,!0,{loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});break;default:throw new Dt("unsupported MediaStreamTrack kind ".concat(g.kind))}else g.updateLoggerOptions({loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});let B;if(I.trackPublications.forEach(r=>{r.track&&r.track===g&&(B=r)}),B)return I.log.warn("track has already been published, skipping",Object.assign(Object.assign({},I.logContext),WA(B))),B;const E="channelCount"in g.mediaStreamTrack.getSettings()&&g.mediaStreamTrack.getSettings().channelCount===2||g.mediaStreamTrack.getConstraints().channelCount===2,d=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:E;d&&(i||(i={}),i.dtx===void 0&&I.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},I.logContext),WA(g))),i.red===void 0&&I.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(Q=i.dtx)!==null&&Q!==void 0||(i.dtx=!1),(n=i.red)!==null&&n!==void 0||(i.red=!1));const c=Object.assign(Object.assign({},I.roomOptions.publishDefaults),i);!rx()&&I.roomOptions.e2ee&&(I.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},I.logContext)),c.simulcast=!1),c.source&&(g.source=c.source);const h=new Promise((r,f)=>S(I,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ye.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:WA(g)}));const _=setTimeout(()=>{f(new KE("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(_);const l=yield this.publish(g,c,d);r(l)}else try{const _=yield this.publish(g,c,d);r(_)}catch(_){f(_)}}catch(_){f(_)}}));I.pendingPublishPromises.set(g,h);try{return yield h}catch(r){throw r}finally{I.pendingPublishPromises.delete(g)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new it),this.signalConnectedFuture.promise}hasPermissionsToPublish(A){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),WA(A))),!1;const{canPublish:e,canPublishSources:g}=this.permissions;return e&&(g.length===0||g.map(i=>Sx(i)).includes(A.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),WA(A))),!1)}publish(A,e,g){return S(this,void 0,void 0,function*(){var i,I,C,o,a,Q,n,s,B,E;if(!this.hasPermissionsToPublish(A))throw new KE("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(x=>eI(A)&&x.source===A.source)&&A.source!==AA.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(A.source),Object.assign(Object.assign({},this.logContext),WA(A))),e.stopMicTrackOnMute&&It(A)&&(A.stopOnMute=!0),A.source===AA.Source.ScreenShare&&ui()&&(e.simulcast=!1),e.videoCodec==="av1"&&!Qx()&&(e.videoCodec=void 0),e.videoCodec==="vp9"&&!nx()&&(e.videoCodec=void 0),e.videoCodec===void 0&&(e.videoCodec=cQ),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(x=>e.videoCodec===AC(x.mime))||(e.videoCodec=AC(this.enabledPublishVideoCodecs[0].mime)));const c=e.videoCodec;A.on(oA.Muted,this.onTrackMuted),A.on(oA.Unmuted,this.onTrackUnmuted),A.on(oA.Ended,this.handleTrackEnded),A.on(oA.UpstreamPaused,this.onTrackUpstreamPaused),A.on(oA.UpstreamResumed,this.onTrackUpstreamResumed),A.on(oA.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const h=[],r=!(!((i=e.dtx)!==null&&i!==void 0)||i),f=A.getSourceTrackSettings();f.autoGainControl&&h.push(je.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&h.push(je.TF_ECHO_CANCELLATION),f.noiseSuppression&&h.push(je.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&h.push(je.TF_STEREO),r&&h.push(je.TF_NO_DTX),_t(A)&&A.hasPreConnectBuffer&&h.push(je.TF_PRECONNECT_BUFFER);const _=new ma({cid:A.mediaStreamTrack.id,name:e.name,type:AA.kindToProto(A.kind),muted:A.isMuted,source:AA.sourceToProto(A.source),disableDtx:r,encryption:this.encryptionType,stereo:g,disableRed:this.isE2EEEnabled||!(!((I=e.red)!==null&&I!==void 0)||I),stream:e==null?void 0:e.stream,backupCodecPolicy:e==null?void 0:e.backupCodecPolicy,audioFeatures:h});let l;if(A.kind===AA.Kind.Video){let x={width:0,height:0};try{x=yield A.waitForDimensions()}catch{const N=(o=(C=this.roomOptions.videoCaptureDefaults)===null||C===void 0?void 0:C.resolution)!==null&&o!==void 0?o:ZI.h720.resolution;x={width:N.width,height:N.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{dims:x}))}_.width=x.width,_.height=x.height,zt(A)&&(et(c)&&(A.source===AA.Source.ScreenShare&&(e.scalabilityMode="L1T3","contentHint"in A.mediaStreamTrack&&(A.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),WA(A))))),e.scalabilityMode=(a=e.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),_.simulcastCodecs=[new pa({codec:c,cid:A.mediaStreamTrack.id})],e.backupCodec===!0&&(e.backupCodec={codec:cQ}),e.backupCodec&&c!==e.backupCodec.codec&&_.encryption===lg.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),_.simulcastCodecs.push(new pa({codec:e.backupCodec.codec,cid:""})))),l=uQ(A.source===AA.Source.ScreenShare,_.width,_.height,e),_.layers=Dr(_.width,_.height,l,et(e.videoCodec))}else A.kind===AA.Kind.Audio&&(l=[{maxBitrate:(Q=e.audioPreset)===null||Q===void 0?void 0:Q.maxBitrate,priority:(s=(n=e.audioPreset)===null||n===void 0?void 0:n.priority)!==null&&s!==void 0?s:"high",networkPriority:(E=(B=e.audioPreset)===null||B===void 0?void 0:B.priority)!==null&&E!==void 0?E:"high"}]);if(!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const D=()=>S(this,void 0,void 0,function*(){var x,w,N;if(!this.engine.pcManager)throw new Pe("pcManager is not ready");if(A.sender=yield this.engine.createSender(A,e,l),this.emit(QA.LocalSenderCreated,A.sender,A),zt(A)&&((x=e.degradationPreference)!==null&&x!==void 0||(e.degradationPreference=Bl(A)),A.setDegradationPreference(e.degradationPreference)),l)if(ui()&&A.kind===AA.Kind.Audio){let U;for(const K of this.engine.pcManager.publisher.getTransceivers())if(K.sender===A.sender){U=K;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((w=l[0])===null||w===void 0)&&w.maxBitrate?l[0].maxBitrate/1e3:0})}else A.codec&&et(A.codec)&&(!((N=l[0])===null||N===void 0)&&N.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:_.cid,codec:A.codec,maxbr:l[0].maxBitrate/1e3});yield this.engine.negotiate()});let p;const y=new Promise((x,w)=>S(this,void 0,void 0,function*(){var N;try{p=yield this.engine.addTrack(_),x(p)}catch(U){A.sender&&(!((N=this.engine.pcManager)===null||N===void 0)&&N.publisher)&&(this.engine.pcManager.publisher.removeTrack(A.sender),yield this.engine.negotiate().catch(K=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{error:K}))})),w(U)}}));if(this.enabledPublishVideoCodecs.length>0)p=(yield Promise.all([y,D()]))[0];else{p=yield y;let x;if(p.codecs.forEach(w=>{x===void 0&&(x=w.mimeType)}),x&&A.kind===AA.Kind.Video){const w=AC(x);w!==c&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{codec:w})),e.videoCodec=w,l=uQ(A.source===AA.Source.ScreenShare,_.width,_.height,e))}yield D()}const k=new yQ(A.kind,p,A,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(oA.CpuConstrained,x=>this.onTrackCpuConstrained(x,k)),k.options=e,A.sid=p.sid,this.log.debug("publishing ".concat(A.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:l,trackInfo:p})),zt(A)?A.startMonitor(this.engine.client):_t(A)&&A.startMonitor(),this.addTrackPublication(k),this.emit(QA.LocalTrackPublished,k),_t(A)&&p.audioFeatures.includes(je.TF_PRECONNECT_BUFFER)){const x=A.getPreConnectBuffer(),w=A.getPreConnectBufferMimeType();this.on(QA.LocalTrackSubscribed,N=>{if(N.trackSid===p.sid){if(!A.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),WA(A))),A.stopPreConnectBuffer()}}),x&&new Promise((U,K)=>S(this,void 0,void 0,function*(){var P,j,H,O,z,xA;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),WA(A)));const vA=setTimeout(()=>{K(new Error("agent not active within 10 seconds"))},1e4),be=yield this.waitUntilActiveAgentPresent();clearTimeout(vA),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),WA(A)));const le=yield this.streamBytes({name:"preconnect-buffer",mimeType:w,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[be.identity],attributes:{trackId:k.trackSid,sampleRate:String((z=f.sampleRate)!==null&&z!==void 0?z:"48000"),channels:String((xA=f.channelCount)!==null&&xA!==void 0?xA:"1")}});try{for(var sA=!0,fA=ft(x),JA;JA=yield fA.next(),P=JA.done,!P;sA=!0){O=JA.value,sA=!1;const Z=O;yield le.write(Z)}}catch(Z){j={error:Z}}finally{try{!sA&&!P&&(H=fA.return)&&(yield H.call(fA))}finally{if(j)throw j.error}}yield le.close(),U()}catch(vA){K(vA)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),WA(A)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{error:U}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(A,e,g){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==lg.NONE)return;let I;if(this.trackPublications.forEach(E=>{E.track&&E.track===A&&(I=E)}),!I)throw new Dt("track is not published");if(!zt(A))throw new Dt("track is not a video track");const C=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),g),o=Ql(A,e,C);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),WA(A)));return}const a=A.addSimulcastTrack(e,o);if(!a)return;const Q=new ma({cid:a.mediaStreamTrack.id,type:AA.kindToProto(A.kind),muted:A.isMuted,source:AA.sourceToProto(A.source),sid:A.sid,simulcastCodecs:[{codec:C.videoCodec,cid:a.mediaStreamTrack.id}]});if(Q.layers=Dr(Q.width,Q.height,o),!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const n=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(A,a,C,o),yield this.engine.negotiate()}),B=(yield Promise.all([this.engine.addTrack(Q),n()]))[0];this.log.debug("published ".concat(e," for track ").concat(A.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:B}))})}unpublishTrack(A,e){return S(this,void 0,void 0,function*(){var g,i;if(eI(A)){const Q=this.pendingPublishPromises.get(A);Q&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),WA(A))),yield Q)}const I=this.getPublicationForTrack(A),C=I?WA(I):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),C)),!I||!I.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),C));return}A=I.track,A.off(oA.Muted,this.onTrackMuted),A.off(oA.Unmuted,this.onTrackUnmuted),A.off(oA.Ended,this.handleTrackEnded),A.off(oA.UpstreamPaused,this.onTrackUpstreamPaused),A.off(oA.UpstreamResumed,this.onTrackUpstreamResumed),A.off(oA.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),e===void 0&&(e=(i=(g=this.roomOptions)===null||g===void 0?void 0:g.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),e?A.stop():A.stopMonitor();let o=!1;const a=A.sender;if(A.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ge.FAILED&&a)try{for(const Q of this.engine.pcManager.publisher.getTransceivers())Q.sender===a&&(Q.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),zt(A)){for(const[,Q]of A.simulcastCodecs)Q.sender&&(this.engine.removeTrack(Q.sender)&&(o=!0),Q.sender=void 0);A.simulcastCodecs.clear()}}catch(Q){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),C),{error:Q}))}switch(this.trackPublications.delete(I.trackSid),I.kind){case AA.Kind.Audio:this.audioTrackPublications.delete(I.trackSid);break;case AA.Kind.Video:this.videoTrackPublications.delete(I.trackSid);break}return this.emit(QA.LocalTrackUnpublished,I),I.setTrack(void 0),o&&(yield this.engine.negotiate()),I})}unpublishTracks(A){return S(this,void 0,void 0,function*(){return(yield Promise.all(A.map(g=>this.unpublishTrack(g)))).filter(g=>!!g)})}republishAllTracks(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){g.republishPromise&&(yield g.republishPromise),g.republishPromise=new Promise((I,C)=>S(g,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(e&&(a.options=Object.assign(Object.assign({},a.options),e)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const Q=a.track;yield this.unpublishTrack(Q,!1),i&&!Q.isMuted&&Q.source!==AA.Source.ScreenShare&&Q.source!==AA.Source.ScreenShareAudio&&(_t(Q)||zt(Q))&&!Q.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield Q.restartTrack()),yield this.publishOrRepublishTrack(Q,a.options,!0)}))),I()}catch(o){C(o)}finally{this.republishPromise=void 0}})),yield g.republishPromise}()})}publishData(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const I=i.reliable?HA.RELIABLE:HA.LOSSY,C=i.destinationIdentities,o=i.topic,a=new Eg({kind:I,value:{case:"user",value:new uB({participantIdentity:g.identity,payload:e,destinationIdentities:C,topic:o})}});yield g.engine.sendDataPacket(a,I)}()})}publishDtmf(A,e){return S(this,void 0,void 0,function*(){const g=new Eg({kind:HA.RELIABLE,value:{case:"sipDtmf",value:new DB({code:A,digit:e})}});yield this.engine.sendDataPacket(g,HA.RELIABLE)})}sendChatMessage(A,e){return S(this,void 0,void 0,function*(){const g={id:crypto.randomUUID(),message:A,timestamp:Date.now(),attachedFiles:e==null?void 0:e.attachments},i=new Eg({value:{case:"chatMessage",value:new la(Object.assign(Object.assign({},g),{timestamp:Ne.parse(g.timestamp)}))}});return yield this.engine.sendDataPacket(i,HA.RELIABLE),this.emit(QA.ChatMessage,g),g})}editChatMessage(A,e){return S(this,void 0,void 0,function*(){const g=Object.assign(Object.assign({},e),{message:A,editTimestamp:Date.now()}),i=new Eg({value:{case:"chatMessage",value:new la(Object.assign(Object.assign({},g),{timestamp:Ne.parse(g.timestamp),editTimestamp:Ne.parse(g.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,HA.RELIABLE),this.emit(QA.ChatMessage,g),g})}sendText(A,e){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(A,e)})}streamText(A){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(A)})}sendFile(A,e){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(A,e)})}streamBytes(A){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(A)})}performRpc(A){return S(this,arguments,void 0,function(e){var g=this;let{destinationIdentity:i,method:I,payload:C,responseTimeout:o=1e4}=e;return function*(){return new Promise((Q,n)=>S(g,void 0,void 0,function*(){var s,B,E,d;if(dQ(C)>rr){n(Me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((B=(s=this.engine.latestJoinResponse)===null||s===void 0?void 0:s.serverInfo)===null||B===void 0)&&B.version&&tt((d=(E=this.engine.latestJoinResponse)===null||E===void 0?void 0:E.serverInfo)===null||d===void 0?void 0:d.version,"1.8.0")<0){n(Me.builtIn("UNSUPPORTED_SERVER"));return}const c=crypto.randomUUID();yield this.publishRpcRequest(i,c,I,C,o-2e3);const h=setTimeout(()=>{this.pendingAcks.delete(c),n(Me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(c),clearTimeout(r)},2e3);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(h)},participantIdentity:i});const r=setTimeout(()=>{this.pendingResponses.delete(c),n(Me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(c,{resolve:(f,_)=>{clearTimeout(r),this.pendingAcks.has(c)&&(console.warn("RPC response received before ack",c),this.pendingAcks.delete(c),clearTimeout(h)),_?n(_):Q(f??"")},participantIdentity:i})}))}()})}registerRpcMethod(A,e){this.rpcHandlers.has(A)&&this.log.warn("you're overriding the RPC handler for method ".concat(A,", in the future this will throw an error")),this.rpcHandlers.set(A,e)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setTrackSubscriptionPermissions(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=e,this.allParticipantsAllowedToSubscribe=A,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(A){const e=this.pendingAcks.get(A);e?(e.resolve(),this.pendingAcks.delete(A)):console.error("Ack received for unexpected RPC request",A)}handleIncomingRpcResponse(A,e,g){const i=this.pendingResponses.get(A);i?(i.resolve(e,g),this.pendingResponses.delete(A)):console.error("Response received for unexpected RPC request",A)}publishRpcRequest(A,e,g,i,I){return S(this,void 0,void 0,function*(){const C=new Eg({destinationIdentities:[A],kind:HA.RELIABLE,value:{case:"rpcRequest",value:new _B({id:e,method:g,payload:i,responseTimeoutMs:I,version:1})}});yield this.engine.sendDataPacket(C,HA.RELIABLE)})}handleParticipantDisconnected(A){for(const[e,{participantIdentity:g}]of this.pendingAcks)g===A&&this.pendingAcks.delete(e);for(const[e,{participantIdentity:g,resolve:i}]of this.pendingResponses)g===A&&(i(null,Me.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(e))}setEnabledPublishCodecs(A){this.enabledPublishVideoCodecs=A.filter(e=>e.mime.split("/")[0].toLowerCase()==="video")}updateInfo(A){return super.updateInfo(A)?(A.tracks.forEach(e=>{var g,i;const I=this.trackPublications.get(e.sid);if(I){const C=I.isMuted||((i=(g=I.track)===null||g===void 0?void 0:g.isUpstreamPaused)!==null&&i!==void 0?i:!1);C!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),WA(I)),{mutedOnServer:C})),this.engine.client.sendMuteTrack(e.sid,C))}}),!0):!1}setActiveAgent(A){var e,g,i,I;this.firstActiveAgent=A,A&&!this.firstActiveAgent&&(this.firstActiveAgent=A),A?(g=(e=this.activeAgentFuture)===null||e===void 0?void 0:e.resolve)===null||g===void 0||g.call(e,A):(I=(i=this.activeAgentFuture)===null||i===void 0?void 0:i.reject)===null||I===void 0||I.call(i,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new it),this.activeAgentFuture.promise)}getPublicationForTrack(A){let e;return this.trackPublications.forEach(g=>{const i=g.track;i&&(A instanceof MediaStreamTrack?(_t(i)||zt(i))&&i.mediaStreamTrack===A&&(e=g):A===i&&(e=g))}),e}waitForPendingPublicationOfSource(A){return S(this,void 0,void 0,function*(){const g=Date.now();for(;Date.now()<g+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(I=>{let[C]=I;return C.source===A});if(i)return i[1];yield rg(20)}})}}class Ml extends wt{constructor(A,e,g,i){super(A,e.sid,e.name,i),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=I=>{this.setTrack(void 0),this.emit(oA.Ended,I)},this.handleVisibilityChange=I=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(I),this.logContext),this.visible=I,this.emitTrackUpdate()},this.handleVideoDimensionsChange=I=>{this.log.debug("adaptivestream video dimensions ".concat(I.width,"x").concat(I.height),this.logContext),this.videoDimensionsAdaptiveStream=I,this.emitTrackUpdate()},this.subscribed=g,this.updateInfo(e)}setSubscribed(A){const e=this.subscriptionStatus,g=this.permissionStatus;this.subscribed=A,A&&(this.allowed=!0);const i=new HC({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new yB({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oA.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(g)}get subscriptionStatus(){return this.subscribed===!1?wt.SubscriptionStatus.Unsubscribed:super.isSubscribed?wt.SubscriptionStatus.Subscribed:wt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?wt.PermissionStatus.Allowed:wt.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(A){!this.isManualOperationAllowed()||this.requestedDisabled===!A||(this.requestedDisabled=!A,this.emitTrackUpdate())}setVideoQuality(A){!this.isManualOperationAllowed()||this.requestedMaxQuality===A||(this.requestedMaxQuality=A,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(A){var e,g;this.isManualOperationAllowed()&&(((e=this.requestedVideoDimensions)===null||e===void 0?void 0:e.width)===A.width&&((g=this.requestedVideoDimensions)===null||g===void 0?void 0:g.height)===A.height||(iQ(this.track)&&(this.requestedVideoDimensions=A),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(A){this.isManualOperationAllowed()&&iQ(this.track)&&this.fps!==A&&(this.fps=A,this.emitTrackUpdate())}get videoQuality(){var A;return(A=this.requestedMaxQuality)!==null&&A!==void 0?A:ug.HIGH}setTrack(A){const e=this.subscriptionStatus,g=this.permissionStatus,i=this.track;i!==A&&(i&&(i.off(oA.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(oA.VisibilityChanged,this.handleVisibilityChange),i.off(oA.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(oA.Unsubscribed,i)),super.setTrack(A),A&&(A.sid=this.trackSid,A.on(oA.VideoDimensionsChanged,this.handleVideoDimensionsChange),A.on(oA.VisibilityChanged,this.handleVisibilityChange),A.on(oA.Ended,this.handleEnded),this.emit(oA.Subscribed,A)),this.emitPermissionUpdateIfChanged(g),this.emitSubscriptionUpdateIfChanged(e))}setAllowed(A){const e=this.subscriptionStatus,g=this.permissionStatus;this.allowed=A,this.emitPermissionUpdateIfChanged(g),this.emitSubscriptionUpdateIfChanged(e)}setSubscriptionError(A){this.emit(oA.SubscriptionFailed,A)}updateInfo(A){super.updateInfo(A);const e=this.metadataMuted;this.metadataMuted=A.muted,this.track?this.track.setMuted(A.muted):e!==A.muted&&this.emit(A.muted?oA.Muted:oA.Unmuted)}emitSubscriptionUpdateIfChanged(A){const e=this.subscriptionStatus;A!==e&&this.emit(oA.SubscriptionStatusChanged,e,A)}emitPermissionUpdateIfChanged(A){this.permissionStatus!==A&&this.emit(oA.SubscriptionPermissionChanged,this.permissionStatus,A)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return iQ(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const A=new LB({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===AA.Kind.Video){let e=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(e)er(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const g=kx(this.trackInfo,this.requestedMaxQuality);g&&er(this.videoDimensionsAdaptiveStream,g)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream;e?(A.width=Math.ceil(e.width),A.height=Math.ceil(e.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),A.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ug.HIGH})),A.quality=ug.HIGH)}this.emit(oA.UpdateSettings,A)}}class ao extends Nr{static fromParticipantInfo(A,e,g){return new ao(A,e.sid,e.identity,e.name,e.metadata,e.attributes,g,e.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(A,e,g,i,I,C,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:OI.STANDARD;super(e,g||"",i,I,C,o,a),this.signalClient=A,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(A){super.addTrackPublication(A),A.on(oA.UpdateSettings,e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)}),A.on(oA.UpdateSubscription,e=>{e.participantTracks.forEach(g=>{g.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),A.on(oA.SubscriptionPermissionChanged,e=>{this.emit(QA.TrackSubscriptionPermissionChanged,A,e)}),A.on(oA.SubscriptionStatusChanged,e=>{this.emit(QA.TrackSubscriptionStatusChanged,A,e)}),A.on(oA.Subscribed,e=>{this.emit(QA.TrackSubscribed,e,A)}),A.on(oA.Unsubscribed,e=>{this.emit(QA.TrackUnsubscribed,e,A)}),A.on(oA.SubscriptionFailed,e=>{this.emit(QA.TrackSubscriptionFailed,A.trackSid,e)})}getTrackPublication(A){const e=super.getTrackPublication(A);if(e)return e}getTrackPublicationByName(A){const e=super.getTrackPublicationByName(A);if(e)return e}setVolume(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:AA.Source.Microphone;this.volumeMap.set(e,A);const g=this.getTrackPublication(e);g&&g.track&&g.track.setVolume(A)}getVolume(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:AA.Source.Microphone;const e=this.getTrackPublication(A);return e&&e.track?e.track.getVolume():this.volumeMap.get(A)}addSubscribedMediaTrack(A,e,g,i,I,C){let o=this.getTrackPublicationBySid(e);if(o||e.startsWith("TR")||this.trackPublications.forEach(n=>{!o&&A.kind===n.kind.toString()&&(o=n)}),!o){if(C===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:e})),this.emit(QA.TrackSubscriptionFailed,e);return}C===void 0&&(C=20),setTimeout(()=>{this.addSubscribedMediaTrack(A,e,g,i,I,C-1)},150);return}if(A.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),WA(o))),this.emit(QA.TrackSubscriptionFailed,e);return}const a=A.kind==="video";let Q;return a?Q=new yl(A,e,i,I):Q=new ml(A,e,i,this.audioContext,this.audioOutput),Q.source=o.source,Q.isMuted=o.isMuted,Q.setMediaStream(g),Q.start(),o.setTrack(Q),this.volumeMap.has(o.source)&&tQ(Q)&&It(Q)&&Q.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(A){return this.trackPublications.get(A)}updateInfo(A){if(!super.updateInfo(A))return!1;const e=new Map,g=new Map;return A.tracks.forEach(i=>{var I,C;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=AA.kindFromProto(i.type);if(!a)return;o=new Ml(a,i,(I=this.signalClient.connectOptions)===null||I===void 0?void 0:I.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(C=this.loggerOptions)===null||C===void 0?void 0:C.loggerName}),o.updateInfo(i),g.set(i.sid,o);const Q=Array.from(this.trackPublications.values()).find(n=>n.source===(o==null?void 0:o.source));Q&&o.source!==AA.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:WA(Q),newTrack:WA(o)})),this.addTrackPublication(o)}e.set(i.sid,o)}),this.trackPublications.forEach(i=>{e.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),WA(i))),this.unpublishTrack(i.trackSid,!0))}),g.forEach(i=>{this.emit(QA.TrackPublished,i)}),!0}unpublishTrack(A,e){const g=this.trackPublications.get(A);if(!g)return;const{track:i}=g;switch(i&&(i.stop(),g.setTrack(void 0)),this.trackPublications.delete(A),g.kind){case AA.Kind.Audio:this.audioTrackPublications.delete(A);break;case AA.Kind.Video:this.videoTrackPublications.delete(A);break}e&&this.emit(QA.TrackUnpublished,g)}setAudioOutput(A){return S(this,void 0,void 0,function*(){this.audioOutput=A;const e=[];this.audioTrackPublications.forEach(g=>{var i;It(g.track)&&tQ(g.track)&&e.push(g.track.setSinkId((i=A.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(e)})}emit(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:A,args:g})),super.emit(A,...g)}}var se;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(se||(se={}));const Fl=4*1e3;class iI extends At.EventEmitter{constructor(A){var e,g,i,I;if(super(),e=this,this.state=se.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=$A,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(C,o,a)=>S(this,void 0,void 0,function*(){var Q;if(!sx())throw gt()?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 n=yield this.disconnectLock.lock();if(this.state===se.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),n(),Promise.resolve();if(this.connectFuture)return n(),this.connectFuture.promise;this.setAndEmitConnectionState(se.Connecting),((Q=this.regionUrlProvider)===null||Q===void 0?void 0:Q.getServerUrl().toString())!==C&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),za(new URL(C))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new wQ(C,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(E=>{var d;(d=this.regionUrlProvider)===null||d===void 0||d.setServerReportedRegions(E)}).catch(E=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:E}))}));const s=(E,d,c)=>S(this,void 0,void 0,function*(){var h,r;this.abortController&&this.abortController.abort();const f=new AbortController;this.abortController=f,n==null||n();try{yield this.attemptConnection(c??C,o,a,f),this.abortController=void 0,E()}catch(_){if(this.regionUrlProvider&&_ instanceof ue&&_.reason!==ie.Cancelled&&_.reason!==ie.NotAllowed){let l=null;try{l=yield this.regionUrlProvider.getNextBestRegionUrl((h=this.abortController)===null||h===void 0?void 0:h.signal)}catch(D){if(D instanceof ue&&(D.status===401||D.reason===ie.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),d(D);return}}l&&!(!((r=this.abortController)===null||r===void 0)&&r.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(l),this.logContext),this.recreateEngine(),yield s(E,d,l)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,XE(_)),d(_))}else{let l=Lg.UNKNOWN_REASON;_ instanceof ue&&(l=XE(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,l),d(_)}}}),B=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new it((E,d)=>{s(E,d,B)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(C,o,a,Q,n,s)=>S(this,void 0,void 0,function*(){var B,E,d;const c=yield a.join(C,o,{autoSubscribe:Q.autoSubscribe,adaptiveStream:typeof n.adaptiveStream=="object"?!0:n.adaptiveStream,maxRetries:Q.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:Q.websocketTimeout},s.signal);let h=c.serverInfo;if(h||(h={version:c.serverVersion,region:c.serverRegion}),this.serverInfo=h,this.log.debug("connected to Livekit Server ".concat(Object.entries(h).map(r=>{let[f,_]=r;return"".concat(f,": ").concat(_)}).join(", ")),{room:(B=c.room)===null||B===void 0?void 0:B.name,roomSid:(E=c.room)===null||E===void 0?void 0:E.sid,identity:(d=c.participant)===null||d===void 0?void 0:d.identity}),!h.version)throw new Xd("unknown server version");return h.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),n.dynacast=!1),c}),this.applyJoinResponse=C=>{const o=C.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(C.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(C.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...C.otherParticipants]),C.room&&this.handleRoomUpdate(C.room)},this.attemptConnection=(C,o,a,Q)=>S(this,void 0,void 0,function*(){var n,s;this.state===se.Reconnecting||this.isResuming||!((n=this.engine)===null||n===void 0)&&n.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((s=this.regionUrlProvider)===null||s===void 0)&&s.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},hQ),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const B=yield this.connectSignal(C,o,this.engine,this.connOptions,this.options,Q);this.applyJoinResponse(B),this.setupLocalParticipantEvents(),this.emit(tA.SignalConnected)}catch(B){yield this.engine.close(),this.recreateEngine();const E=new ue("could not establish signal connection",ie.ServerUnreachable);throw B instanceof Error&&(E.message="".concat(E.message,": ").concat(B.message)),B instanceof ue&&(E.reason=B.reason,E.status=B.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:B})),E}if(Q.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ue("Connection attempt aborted",ie.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,Q)}catch(B){throw yield this.engine.close(),this.recreateEngine(),B}cg()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),cg()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(se.Connected),this.emit(tA.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var C=arguments.length,o=new Array(C),a=0;a<C;a++)o[a]=arguments[a];return S(e,[...o],void 0,function(){var Q=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var s,B,E,d;const c=yield Q.disconnectLock.lock();try{if(Q.state===se.Disconnected){Q.log.debug("already disconnected",Q.logContext);return}Q.log.info("disconnect from room",Object.assign({},Q.logContext)),(Q.state===se.Connecting||Q.state===se.Reconnecting||Q.isResuming)&&(Q.log.warn("abort connection attempt",Q.logContext),(s=Q.abortController)===null||s===void 0||s.abort(),(E=(B=Q.connectFuture)===null||B===void 0?void 0:B.reject)===null||E===void 0||E.call(B,new ue("Client initiated disconnect",ie.Cancelled)),Q.connectFuture=void 0),!((d=Q.engine)===null||d===void 0)&&d.client.isDisconnected||(yield Q.engine.client.sendLeave()),Q.engine&&(yield Q.engine.close()),Q.handleDisconnect(n,Lg.CLIENT_INITIATED),Q.engine=void 0}finally{c()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const C=[],o=fg();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let Q=document.getElementById(a);if(!Q){Q=document.createElement("audio"),Q.id=a,Q.autoplay=!0,Q.hidden=!0;const n=eQ();n.enabled=!0;const s=new MediaStream([n]);Q.srcObject=s,document.addEventListener("visibilitychange",()=>{Q&&(Q.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(Q),this.once(tA.Disconnected,()=>{Q==null||Q.remove(),Q=null})}C.push(Q)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(Q=>{Q.track&&Q.track.attachedElements.forEach(n=>{C.push(n)})})});try{yield Promise.all([this.acquireAudioContext(),...C.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const C=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var Q;(Q=a.track)===null||Q===void 0||Q.attachedElements.forEach(n=>{C.includes(n)||C.push(n)})});yield Promise.all(C.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const C of this.remoteParticipants.values())this.handleParticipantDisconnected(C.identity,C);this.setAndEmitConnectionState(se.Reconnecting)&&this.emit(tA.Reconnecting)},this.handleSignalRestarted=C=>S(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(C.serverRegion),Object.assign(Object.assign({},this.logContext),{region:C.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(C);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:C.serverRegion}))}catch{return}this.setAndEmitConnectionState(se.Connected),this.emit(tA.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=C=>{C.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let Q=this.remoteParticipants.get(o.identity);o.state===Wi.DISCONNECTED?this.handleParticipantDisconnected(o.identity,Q):Q=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=C=>{const o=[],a={};C.forEach(Q=>{if(a[Q.sid]=!0,Q.sid===this.localParticipant.sid)this.localParticipant.audioLevel=Q.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const n=this.getRemoteParticipantBySid(Q.sid);n&&(n.audioLevel=Q.level,n.setIsSpeaking(!0),o.push(n))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(Q=>{a[Q.sid]||(Q.audioLevel=0,Q.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(tA.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=C=>{const o=new Map;this.activeSpeakers.forEach(Q=>{const n=this.remoteParticipants.get(Q.identity);n&&n.sid!==Q.sid||o.set(Q.sid,Q)}),C.forEach(Q=>{let n=this.getRemoteParticipantBySid(Q.sid);Q.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=Q.level,n.setIsSpeaking(Q.active),Q.active?o.set(Q.sid,n):o.delete(Q.sid))});const a=Array.from(o.values());a.sort((Q,n)=>n.audioLevel-Q.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(tA.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=C=>{C.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const Q=a.getTrackPublicationBySid(o.trackSid);if(!Q||!Q.track)return;const n=AA.streamStateFromProto(o.state);Q.track.setStreamState(n),n!==Q.track.streamState&&(a.emit(QA.TrackStreamStateChanged,Q,Q.track.streamState),this.emitWhenConnected(tA.TrackStreamStateChanged,Q,Q.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=C=>{const o=this.getRemoteParticipantBySid(C.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(C.trackSid);a&&a.setAllowed(C.allowed)},this.handleSubscriptionError=C=>{const o=Array.from(this.remoteParticipants.values()).find(Q=>Q.trackPublications.has(C.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(C.trackSid);a&&a.setSubscriptionError(C.err)},this.handleDataPacket=C=>{const o=this.remoteParticipants.get(C.participantIdentity);if(C.value.case==="user")this.handleUserPacket(o,C.value.value,C.kind);else if(C.value.case==="transcription")this.handleTranscription(o,C.value.value);else if(C.value.case==="sipDtmf")this.handleSipDtmf(o,C.value.value);else if(C.value.case==="chatMessage")this.handleChatMessage(o,C.value.value);else if(C.value.case==="metrics")this.handleMetrics(C.value.value,o);else if(C.value.case==="streamHeader"||C.value.case==="streamChunk"||C.value.case==="streamTrailer")this.handleDataStream(C);else if(C.value.case==="rpcRequest"){const a=C.value.value;this.handleIncomingRpcRequest(C.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(C,o,a)=>{this.emit(tA.DataReceived,o.payload,C,a,o.topic),C==null||C.emit(QA.DataReceived,o.payload,a)},this.handleSipDtmf=(C,o)=>{this.emit(tA.SipDTMFReceived,o,C),C==null||C.emit(QA.SipDTMFReceived,o)},this.handleTranscription=(C,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),Q=a==null?void 0:a.trackPublications.get(o.trackId),n=fx(o,this.transcriptionReceivedTimes);Q==null||Q.emit(oA.TranscriptionReceived,n),a==null||a.emit(QA.TranscriptionReceived,n,Q),this.emit(tA.TranscriptionReceived,n,a,Q)},this.handleChatMessage=(C,o)=>{const a=ux(o);this.emit(tA.ChatMessage,a,C)},this.handleMetrics=(C,o)=>{this.emit(tA.MetricsReceived,C,o)},this.handleDataStream=C=>{this.incomingDataStreamManager.handleDataStreamPacket(C)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(tA.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=C=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:C})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(tA.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(tA.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(tA.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var C;((C=fg())===null||C===void 0?void 0:C.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(tA.MediaDevicesChanged)}),this.handleRoomUpdate=C=>{const o=this.roomInfo;this.roomInfo=C,o&&o.metadata!==C.metadata&&this.emitWhenConnected(tA.RoomMetadataChanged,C.metadata),(o==null?void 0:o.activeRecording)!==C.activeRecording&&this.emitWhenConnected(tA.RecordingStatusChanged,C.activeRecording)},this.handleConnectionQualityUpdate=C=>{C.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=C=>{this.emit(tA.ParticipantMetadataChanged,C,this.localParticipant)},this.onLocalParticipantNameChanged=C=>{this.emit(tA.ParticipantNameChanged,C,this.localParticipant)},this.onLocalAttributesChanged=C=>{this.emit(tA.ParticipantAttributesChanged,C,this.localParticipant)},this.onLocalTrackMuted=C=>{this.emit(tA.TrackMuted,C,this.localParticipant)},this.onLocalTrackUnmuted=C=>{this.emit(tA.TrackUnmuted,C,this.localParticipant)},this.onTrackProcessorUpdate=C=>{var o;(o=C==null?void 0:C.onPublish)===null||o===void 0||o.call(C,this)},this.onLocalTrackPublished=C=>S(this,void 0,void 0,function*(){var o,a,Q,n,s,B;(o=C.track)===null||o===void 0||o.on(oA.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=C.track)===null||a===void 0||a.on(oA.Restarted,this.onLocalTrackRestarted),(s=(n=(Q=C.track)===null||Q===void 0?void 0:Q.getProcessor())===null||n===void 0?void 0:n.onPublish)===null||s===void 0||s.call(n,this),this.emit(tA.LocalTrackPublished,C,this.localParticipant),_t(C.track)&&(yield C.track.checkForSilence())&&this.emit(tA.LocalAudioSilenceDetected,C);const E=yield(B=C.track)===null||B===void 0?void 0:B.getDeviceId(!1),d=oQ(C.source);d&&E&&E!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,E),this.emit(tA.ActiveDeviceChanged,d,E))}),this.onLocalTrackUnpublished=C=>{var o,a;(o=C.track)===null||o===void 0||o.off(oA.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=C.track)===null||a===void 0||a.off(oA.Restarted,this.onLocalTrackRestarted),this.emit(tA.LocalTrackUnpublished,C,this.localParticipant)},this.onLocalTrackRestarted=C=>S(this,void 0,void 0,function*(){const o=yield C.getDeviceId(!1),a=oQ(C.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(tA.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=C=>{this.emit(tA.ConnectionQualityChanged,C,this.localParticipant)},this.onMediaDevicesError=(C,o)=>{this.emit(tA.MediaDevicesError,C,o)},this.onLocalParticipantPermissionsChanged=C=>{this.emit(tA.ParticipantPermissionsChanged,C,this.localParticipant)},this.onLocalChatMessageSent=C=>{this.emit(tA.ChatMessage,C,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},jx),A),this.log=lt((g=this.options.loggerName)!==null&&g!==void 0?g:vg.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Br),A==null?void 0:A.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Er),A==null?void 0:A.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Vx),A==null?void 0:A.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Dl,this.outgoingDataStreamManager=new pl(this.engine,this.log),this.disconnectLock=new sg,this.localParticipant=new Gl("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Xt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Xt(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",Xt(this.options.audioOutput.deviceId)).catch(C=>this.log.warn("Could not set audio output: ".concat(C.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),cg()){const C=new AbortController;(I=navigator.mediaDevices)===null||I===void 0||I.addEventListener("devicechange",this.handleDeviceChange,{signal:C.signal}),iI.cleanupRegistry&&iI.cleanupRegistry.register(this,()=>{C.abort()})}}registerTextStreamHandler(A,e){return this.incomingDataStreamManager.registerTextStreamHandler(A,e)}unregisterTextStreamHandler(A){return this.incomingDataStreamManager.unregisterTextStreamHandler(A)}registerByteStreamHandler(A,e){return this.incomingDataStreamManager.registerByteStreamHandler(A,e)}unregisterByteStreamHandler(A){return this.incomingDataStreamManager.unregisterByteStreamHandler(A)}registerRpcMethod(A,e){if(this.rpcHandlers.has(A))throw Error("RPC handler already registered for method ".concat(A,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(A,e)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setE2EEEnabled(A){return S(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(A)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(A,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var A;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Rx(this.options.e2ee),this.e2eeManager.on(jt.ParticipantEncryptionStatusChanged,(e,g)=>{_x(g)&&(this.isE2EEEnabled=e),this.emit(tA.ParticipantEncryptionStatusChanged,e,g)}),this.e2eeManager.on(jt.EncryptionError,e=>this.emit(tA.EncryptionError,e)),(A=this.e2eeManager)===null||A===void 0||A.setup(this))}get logContext(){var A;return{room:this.name,roomID:(A=this.roomInfo)===null||A===void 0?void 0:A.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.activeRecording)!==null&&e!==void 0?e:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===se.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((A,e)=>{const g=i=>{i.sid!==""&&(this.engine.off(nA.RoomUpdate,g),A(i.sid))};this.engine.on(nA.RoomUpdate,g),this.once(tA.Disconnected,()=>{this.engine.off(nA.RoomUpdate,g),e("Room disconnected before room server id was available")})})})}get name(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.name)!==null&&e!==void 0?e:""}get metadata(){var A;return(A=this.roomInfo)===null||A===void 0?void 0:A.metadata}get numParticipants(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.numParticipants)!==null&&e!==void 0?e:0}get numPublishers(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.numPublishers)!==null&&e!==void 0?e:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new hl(this.options),this.engine.on(nA.ParticipantUpdate,this.handleParticipantUpdates).on(nA.RoomUpdate,this.handleRoomUpdate).on(nA.SpeakersChanged,this.handleSpeakersChanged).on(nA.StreamStateChanged,this.handleStreamStateUpdate).on(nA.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(nA.SubscriptionError,this.handleSubscriptionError).on(nA.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(nA.MediaTrackAdded,(A,e,g)=>{this.onTrackAdded(A,e,g)}).on(nA.Disconnected,A=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,A)}).on(nA.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(nA.DataPacketReceived,this.handleDataPacket).on(nA.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(se.SignalReconnecting)&&this.emit(tA.SignalReconnecting)}).on(nA.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(se.Connected)&&this.emit(tA.Reconnected)}).on(nA.SignalResumed,()=>{this.bufferedEvents=[],(this.state===se.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(nA.Restarting,this.handleRestarting).on(nA.SignalRestarted,this.handleSignalRestarted).on(nA.Offline,()=>{this.setAndEmitConnectionState(se.Reconnecting)&&this.emit(tA.Reconnecting)}).on(nA.DCBufferStatusChanged,(A,e)=>{this.emit(tA.DCBufferStatusChanged,A,e)}).on(nA.LocalTrackSubscribed,A=>{const e=this.localParticipant.getTrackPublications().find(g=>{let{trackSid:i}=g;return i===A});if(!e){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(QA.LocalTrackSubscribed,e),this.emitWhenConnected(tA.LocalTrackSubscribed,e,this.localParticipant)}).on(nA.RoomMoved,A=>{this.log.debug("room moved",A),A.room&&this.handleRoomUpdate(A.room),this.remoteParticipants.forEach((e,g)=>{this.handleParticipantDisconnected(g,e)}),this.emit(tA.Moved,A.room.name),A.participant?this.handleParticipantUpdates([A.participant,...A.otherParticipants]):this.handleParticipantUpdates(A.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return We.getInstance().getDevices(A,e)}prepareConnection(A,e){return S(this,void 0,void 0,function*(){if(this.state===se.Disconnected){this.log.debug("prepareConnection to ".concat(A),this.logContext);try{if(za(new URL(A))&&e){this.regionUrlProvider=new wQ(A,e);const g=yield this.regionUrlProvider.getNextBestRegionUrl();g&&this.state===se.Disconnected&&(this.regionUrl=g,yield fetch(gQ(g),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(g),this.logContext))}else yield fetch(gQ(A),{method:"HEAD"})}catch(g){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:g}))}}})}getParticipantByIdentity(A){return this.localParticipant.identity===A?this.localParticipant:this.remoteParticipants.get(A)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(A,e){return S(this,void 0,void 0,function*(){let g=()=>{},i;switch(A){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new $g({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new $g({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new $g({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new $g({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":g=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new $g({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":g=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new $g({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new $g({scenario:{case:"switchCandidateProtocol",value:A==="force-tls"?2:1}}),g=()=>S(this,void 0,void 0,function*(){const I=this.engine.client.onLeave;I&&I(new PC({reason:Lg.CLIENT_INITIATED,action:Zi.RECONNECT}))});break;case"subscriber-bandwidth":if(e===void 0||typeof e!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new $g({scenario:{case:"subscriberBandwidth",value:_i(e)}});break;case"leave-full-reconnect":i=new $g({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield g())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(A){return this.localParticipant.activeDeviceMap.get(A)}switchActiveDevice(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,Q,n,s,B,E;let d=!0,c=!1;const h=C?{exact:i}:i;if(g==="audioinput"){c=I.localParticipant.audioTrackPublications.size===0;const r=(o=I.getActiveDevice(g))!==null&&o!==void 0?o:I.options.audioCaptureDefaults.deviceId;I.options.audioCaptureDefaults.deviceId=h;const f=Array.from(I.localParticipant.audioTrackPublications.values()).filter(l=>l.source===AA.Source.Microphone);try{d=(yield Promise.all(f.map(l=>{var D;return(D=l.audioTrack)===null||D===void 0?void 0:D.setDeviceId(h)}))).every(l=>l===!0)}catch(l){throw I.options.audioCaptureDefaults.deviceId=r,l}const _=f.some(l=>{var D,p;return(p=(D=l.track)===null||D===void 0?void 0:D.isMuted)!==null&&p!==void 0?p:!1});d&&_&&(c=!0)}else if(g==="videoinput"){c=I.localParticipant.videoTrackPublications.size===0;const r=(a=I.getActiveDevice(g))!==null&&a!==void 0?a:I.options.videoCaptureDefaults.deviceId;I.options.videoCaptureDefaults.deviceId=h;const f=Array.from(I.localParticipant.videoTrackPublications.values()).filter(l=>l.source===AA.Source.Camera);try{d=(yield Promise.all(f.map(l=>{var D;return(D=l.videoTrack)===null||D===void 0?void 0:D.setDeviceId(h)}))).every(l=>l===!0)}catch(l){throw I.options.videoCaptureDefaults.deviceId=r,l}const _=f.some(l=>{var D,p;return(p=(D=l.track)===null||D===void 0?void 0:D.isMuted)!==null&&p!==void 0?p:!1});d&&_&&(c=!0)}else if(g==="audiooutput"){if(c=!0,!Za()&&!I.options.webAudioMix||I.options.webAudioMix&&I.audioContext&&!("setSinkId"in I.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");I.options.webAudioMix&&(i=(Q=yield We.getInstance().normalizeDeviceId("audiooutput",i))!==null&&Q!==void 0?Q:""),(n=(E=I.options).audioOutput)!==null&&n!==void 0||(E.audioOutput={});const r=(s=I.getActiveDevice(g))!==null&&s!==void 0?s:I.options.audioOutput.deviceId;I.options.audioOutput.deviceId=i;try{I.options.webAudioMix&&((B=I.audioContext)===null||B===void 0||B.setSinkId(i)),yield Promise.all(Array.from(I.remoteParticipants.values()).map(f=>f.setAudioOutput({deviceId:i})))}catch(f){throw I.options.audioOutput.deviceId=r,f}}return c&&(I.localParticipant.activeDeviceMap.set(g,i),I.emit(tA.ActiveDeviceChanged,g,i)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(QA.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(QA.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(QA.AttributesChanged,this.onLocalAttributesChanged).on(QA.TrackMuted,this.onLocalTrackMuted).on(QA.TrackUnmuted,this.onLocalTrackUnmuted).on(QA.LocalTrackPublished,this.onLocalTrackPublished).on(QA.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(QA.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(QA.MediaDevicesError,this.onMediaDevicesError).on(QA.AudioStreamAcquired,this.startAudio).on(QA.ChatMessage,this.onLocalChatMessageSent).on(QA.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var A;(A=this.engine)===null||A===void 0||A.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(A,e,g){if(this.state===se.Connecting||this.state===se.Reconnecting){const s=()=>{this.onTrackAdded(A,e,g),B()},B=()=>{this.off(tA.Reconnected,s),this.off(tA.Connected,s),this.off(tA.Disconnected,B)};this.once(tA.Reconnected,s),this.once(tA.Connected,s),this.once(tA.Disconnected,B);return}if(this.state===se.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(A.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=ax(e.id),I=i[0];let C=i[1],o=A.id;if(C&&C.startsWith("TR")&&(o=C),I===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(s=>s.sid===I);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(I),this.logContext);return}let Q;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?Q=this.options.adaptiveStream:Q={});const n=a.addSubscribedMediaTrack(A,o,e,g,Q);n!=null&&n.isEncrypted&&!this.e2eeManager&&this.emit(tA.EncryptionError,new Error("Encrypted ".concat(n.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1?arguments[1]:void 0;var g;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==se.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(I=>{i.unpublishTrack(I.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var I,C,o;i.track&&this.localParticipant.unpublishTrack(i.track,A),A?((I=i.track)===null||I===void 0||I.detach(),(C=i.track)===null||C===void 0||C.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(QA.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(QA.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(QA.AttributesChanged,this.onLocalAttributesChanged).off(QA.TrackMuted,this.onLocalTrackMuted).off(QA.TrackUnmuted,this.onLocalTrackUnmuted).off(QA.LocalTrackPublished,this.onLocalTrackPublished).off(QA.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(QA.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(QA.MediaDevicesError,this.onMediaDevicesError).off(QA.AudioStreamAcquired,this.startAudio).off(QA.ChatMessage,this.onLocalChatMessageSent).off(QA.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),cg()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(g=navigator.mediaDevices)===null||g===void 0||g.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(se.Disconnected),this.emit(tA.Disconnected,e)}}}handleParticipantDisconnected(A,e){var g;this.remoteParticipants.delete(A),e&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(A),e.trackPublications.forEach(i=>{e.unpublishTrack(i.trackSid,!0)}),this.emit(tA.ParticipantDisconnected,e),e.setDisconnected(),(g=this.localParticipant)===null||g===void 0||g.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(A,e,g,i,I,C){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(A,e),C!==1){yield this.engine.publishRpcResponse(A,e,null,Me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(g);if(!o){yield this.engine.publishRpcResponse(A,e,null,Me.builtIn("UNSUPPORTED_METHOD"));return}let a=null,Q=null;try{const n=yield o({requestId:e,callerIdentity:A,payload:i,responseTimeout:I});dQ(n)>rr?(a=Me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(g))):Q=n}catch(n){n instanceof Me?a=n:(console.warn("Uncaught error returned by RPC handler for ".concat(g,". Returning APPLICATION_ERROR instead."),n),a=Me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(A,e,Q,a)})}selectDefaultDevices(){return S(this,void 0,void 0,function*(){var A,e,g;const i=We.getInstance().previousDevices,I=yield We.getInstance().getDevices(void 0,!1),C=fg();if((C==null?void 0:C.name)==="Chrome"&&C.os!=="iOS")for(let a of I){const Q=i.find(n=>n.deviceId===a.deviceId);Q&&Q.label!==""&&Q.kind===a.kind&&Q.label!==a.label&&this.getActiveDevice(a.kind)==="default"&&this.emit(tA.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const Q=px(a),n=this.localParticipant.getTrackPublication(Q);if(n&&(!((A=n.track)===null||A===void 0)&&A.isUserProvided))continue;const s=I.filter(E=>E.kind===a),B=this.getActiveDevice(a);if(B===((e=i.filter(E=>E.kind===a)[0])===null||e===void 0?void 0:e.deviceId)&&s.length>0&&((g=s[0])===null||g===void 0?void 0:g.deviceId)!==B){yield this.switchActiveDevice(a,s[0].deviceId);continue}a==="audioinput"&&!zI()||a==="videoinput"||s.length>0&&!s.find(E=>E.deviceId===this.getActiveDevice(a))&&(a!=="audiooutput"||!zI())&&(yield this.switchActiveDevice(a,s[0].deviceId))}})}acquireAudioContext(){return S(this,void 0,void 0,function*(){var A,e;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(A=$E())!==null&&A!==void 0?A:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),rg(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const g=((e=this.audioContext)===null||e===void 0?void 0:e.state)==="running";g!==this.canPlaybackAudio&&(this.audioEnabled=g,this.emit(tA.AudioPlaybackStatusChanged,g))})}createParticipant(A,e){var g;let i;return e?i=ao.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new ao(this.engine.client,"",A,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((g=this.options.audioOutput)===null||g===void 0)&&g.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(I=>this.log.warn("Could not set audio output: ".concat(I.message),this.logContext)),i}getOrCreateParticipant(A,e){if(this.remoteParticipants.has(A)){const i=this.remoteParticipants.get(A);return e&&i.updateInfo(e)&&this.sidToIdentity.set(e.sid,e.identity),i}const g=this.createParticipant(A,e);return this.remoteParticipants.set(A,g),this.sidToIdentity.set(e.sid,e.identity),this.emitWhenConnected(tA.ParticipantConnected,g),g.on(QA.TrackPublished,i=>{this.emitWhenConnected(tA.TrackPublished,i,g)}).on(QA.TrackSubscribed,(i,I)=>{i.kind===AA.Kind.Audio?(i.on(oA.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(oA.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===AA.Kind.Video&&(i.on(oA.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(oA.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(tA.TrackSubscribed,i,I,g)}).on(QA.TrackUnpublished,i=>{this.emit(tA.TrackUnpublished,i,g)}).on(QA.TrackUnsubscribed,(i,I)=>{this.emit(tA.TrackUnsubscribed,i,I,g)}).on(QA.TrackMuted,i=>{this.emitWhenConnected(tA.TrackMuted,i,g)}).on(QA.TrackUnmuted,i=>{this.emitWhenConnected(tA.TrackUnmuted,i,g)}).on(QA.ParticipantMetadataChanged,i=>{this.emitWhenConnected(tA.ParticipantMetadataChanged,i,g)}).on(QA.ParticipantNameChanged,i=>{this.emitWhenConnected(tA.ParticipantNameChanged,i,g)}).on(QA.AttributesChanged,i=>{this.emitWhenConnected(tA.ParticipantAttributesChanged,i,g)}).on(QA.ConnectionQualityChanged,i=>{this.emitWhenConnected(tA.ConnectionQualityChanged,i,g)}).on(QA.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(tA.ParticipantPermissionsChanged,i,g)}).on(QA.TrackSubscriptionStatusChanged,(i,I)=>{this.emitWhenConnected(tA.TrackSubscriptionStatusChanged,i,I,g)}).on(QA.TrackSubscriptionFailed,(i,I)=>{this.emit(tA.TrackSubscriptionFailed,i,g,I)}).on(QA.TrackSubscriptionPermissionChanged,(i,I)=>{this.emitWhenConnected(tA.TrackSubscriptionPermissionChanged,i,I,g)}).on(QA.Active,()=>{this.emitWhenConnected(tA.ParticipantActive,g),g.kind===OI.AGENT&&this.localParticipant.setActiveAgent(g)}),e&&g.updateInfo(e),g}sendSyncState(){const A=Array.from(this.remoteParticipants.values()).reduce((g,i)=>(g.push(...i.getTrackPublications()),g),[]),e=this.localParticipant.getTrackPublications();this.engine.sendSyncState(A,e)}updateSubscriptions(){for(const A of this.remoteParticipants.values())for(const e of A.videoTrackPublications.values())e.isSubscribed&&Dx(e)&&e.emitTrackUpdate()}getRemoteParticipantBySid(A){const e=this.sidToIdentity.get(A);if(e)return this.remoteParticipants.get(e)}registerConnectionReconcile(){this.clearConnectionReconcile();let A=0;this.connectionReconcileInterval=ze.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(A++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:A,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),A>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Lg.STATE_MISMATCH))):A=0},Fl)}clearConnectionReconcile(){this.connectionReconcileInterval&&ze.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(A){return A===this.state?!1:(this.state=A,this.emit(tA.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(A=>{let[e,g]=A;this.emit(e,...g)}),this.bufferedEvents=[]}emitWhenConnected(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];if(this.state===se.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([A,g]);else if(this.state===se.Connected)return this.emit(A,...g);return!1}simulateParticipants(A){return S(this,void 0,void 0,function*(){var e,g;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},A.publish),I=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},A.participants);if(this.handleDisconnect(),this.roomInfo=new TC({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ne.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new di({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(tA.SignalConnected),this.emit(tA.Connected),this.setAndEmitConnectionState(se.Connected),i.video){const C=new yQ(AA.Kind.Video,new Xi({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO,name:"video-dummy"}),new Co(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:WE(160*((e=I.aspectRatios[0])!==null&&e!==void 0?e: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(QA.LocalTrackPublished,C)}if(i.audio){const C=new yQ(AA.Kind.Audio,new Xi({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO}),new Io(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:eQ(),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(QA.LocalTrackPublished,C)}for(let C=0;C<I.count-1;C+=1){let o=new di({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(C),state:Wi.ACTIVE,tracks:[],joinedAt:Ne.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(I.video){const Q=WE(160*((g=I.aspectRatios[C%I.aspectRatios.length])!==null&&g!==void 0?g:1),160,!1,!0),n=new Xi({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO});a.addSubscribedMediaTrack(Q,n.sid,new MediaStream([Q]),new RTCRtpReceiver),o.tracks=[...o.tracks,n]}if(I.audio){const Q=eQ(),n=new Xi({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO});a.addSubscribedMediaTrack(Q,n.sid,new MediaStream([Q]),new RTCRtpReceiver),o.tracks=[...o.tracks,n]}a.updateInfo(o)}})}emit(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];if(A!==tA.ActiveSpeakersChanged&&A!==tA.TranscriptionReceived){const I=Sr(g).filter(C=>C!==void 0);this.log.debug("room event ".concat(A),Object.assign(Object.assign({},this.logContext),{event:A,args:I}))}return super.emit(A,...g)}}iI.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function Sr(t){return t.map(A=>{if(A)return Array.isArray(A)?Sr(A):typeof A=="object"?"logContext"in A?A.logContext:void 0:A})}var qg;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(qg||(qg={}));class ei extends At.EventEmitter{constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qg.IDLE,this.logs=[],this.options={},this.url=A,this.token=e,this.name=this.constructor.name,this.room=new iI(g.roomOptions),this.connectOptions=g.connectOptions,this.options=g}run(A){return S(this,void 0,void 0,function*(){if(this.status!==qg.IDLE)throw Error("check is running already");this.setStatus(qg.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==qg.SKIPPED&&this.setStatus(this.isSuccess()?qg.SUCCESS:qg.FAILED),A&&A(),this.getInfo()})}isSuccess(){return!this.logs.some(A=>A.level==="error")}connect(A){return S(this,void 0,void 0,function*(){return this.room.state===se.Connected?this.room:(A||(A=this.url),yield this.room.connect(A,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==se.Disconnected&&(yield this.room.disconnect(),yield new Promise(A=>setTimeout(A,500)))})}skip(){this.setStatus(qg.SKIPPED)}switchProtocol(A){return S(this,void 0,void 0,function*(){let e=!1,g=!1;if(this.room.on(tA.Reconnecting,()=>{e=!0}),this.room.once(tA.Reconnected,()=>{g=!0}),this.room.simulateScenario("force-".concat(A)),yield new Promise(I=>setTimeout(I,1e3)),!e)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(g)return;yield rg(100)}throw new Error("Could not reconnect using ".concat(A," protocol after 10 seconds"))})}appendMessage(A){this.logs.push({level:"info",message:A}),this.emit("update",this.getInfo())}appendWarning(A){this.logs.push({level:"warning",message:A}),this.emit("update",this.getInfo())}appendError(A){this.logs.push({level:"error",message:A}),this.emit("update",this.getInfo())}setStatus(A){this.status=A,this.emit("update",this.getInfo())}get engine(){var A;return(A=this.room)===null||A===void 0?void 0:A.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Ul extends ei{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const A=new wQ(this.url,this.token);if(!A.isCloud()){this.skip();return}const e=[],g=new Set;for(let I=0;I<3;I++){const C=yield A.getNextBestRegionUrl();if(!C)break;if(g.has(C))continue;g.add(C);const o=yield this.checkCloudRegion(C);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),e.push(o)}e.sort((I,C)=>(I.duration-C.duration)*.5+(I.rtt-C.rtt)*.5);const i=e[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkCloudRegion(A){return S(this,void 0,void 0,function*(){var e,g;yield this.connect(A),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(e=this.room.serverInfo)===null||e===void 0?void 0:e.region;if(!i)throw new Error("Region not found");const I=yield this.room.localParticipant.streamText({topic:"test"}),C=1e3,a=1e6/C,Q="A".repeat(C),n=Date.now();for(let d=0;d<a;d++)yield I.write(Q);yield I.close();const s=Date.now(),B=yield(g=this.room.engine.pcManager)===null||g===void 0?void 0:g.publisher.getStats(),E={region:i,rtt:1e4,duration:s-n};return B==null||B.forEach(d=>{d.type==="candidate-pair"&&d.nominated&&(E.rtt=d.currentRoundTripTime*1e3)}),yield this.disconnect(),E})}}const bQ=1e4;class Ll extends ei{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const A=yield this.checkConnectionProtocol("udp"),e=yield this.checkConnectionProtocol("tcp");this.bestStats=A,A.qualityLimitationDurations.bandwidth-e.qualityLimitationDurations.bandwidth>.5||(A.packetsLost-e.packetsLost)/A.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=e):this.appendMessage("best connection quality via udp");const g=this.bestStats;this.appendMessage("upstream bitrate: ".concat((g.bitrateTotal/g.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((g.rttTotal/g.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((g.jitterTotal/g.count*1e3).toFixed(2)," ms")),g.packetsLost>0&&this.appendWarning("packets lost: ".concat((g.packetsLost/g.packetsSent*100).toFixed(2),"%")),g.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((g.qualityLimitationDurations.bandwidth/(bQ/1e3)*100).toFixed(2),"%")),g.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((g.qualityLimitationDurations.cpu/(bQ/1e3)*100).toFixed(2),"%"))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkConnectionProtocol(A){return S(this,void 0,void 0,function*(){yield this.connect(),A==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const e=document.createElement("canvas");e.width=1280,e.height=720;const g=e.getContext("2d");if(!g)throw new Error("Could not get canvas context");let i=0;const I=()=>{i=(i+1)%360,g.fillStyle="hsl(".concat(i,", 100%, 50%)"),g.fillRect(0,0,e.width,e.height),requestAnimationFrame(I)};I();const o=e.captureStream(30).getVideoTracks()[0],Q=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,n={protocol:A,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},s=setInterval(()=>S(this,void 0,void 0,function*(){const B=yield Q.getRTCStatsReport();B==null||B.forEach(E=>{E.type==="outbound-rtp"?(n.packetsSent=E.packetsSent,n.qualityLimitationDurations=E.qualityLimitationDurations,n.bitrateTotal+=E.targetBitrate,n.count++):E.type==="remote-inbound-rtp"&&(n.packetsLost=E.packetsLost,n.rttTotal+=E.roundTripTime,n.jitterTotal+=E.jitter)})}),1e3);return yield new Promise(B=>setTimeout(B,bQ)),clearInterval(s),o.stop(),e.remove(),yield this.disconnect(),n})}}class Kl extends ei{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect(),g=yield Sl();if(yield zE(g,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),e.localParticipant.publishTrack(g),yield new Promise(o=>setTimeout(o,3e3));const I=yield(A=g.sender)===null||A===void 0?void 0:A.getStats();if(!I)throw new Error("Could not get RTCStats");let C=0;if(I.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(C=o.packetsSent)}),C===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(C," audio packets"))})}}class vl extends ei{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect(),g=yield Nl();yield this.checkForVideo(g.mediaStreamTrack),e.localParticipant.publishTrack(g),yield new Promise(C=>setTimeout(C,5e3));const i=yield(A=g.sender)===null||A===void 0?void 0:A.getStats();if(!i)throw new Error("Could not get RTCStats");let I=0;if(i.forEach(C=>{C.type==="outbound-rtp"&&(C.kind==="video"||!C.kind&&C.mediaType==="video")&&(I+=C.packetsSent)}),I===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(I," video packets"))})}checkForVideo(A){return S(this,void 0,void 0,function*(){const e=new MediaStream;e.addTrack(A.clone());const g=document.createElement("video");g.srcObject=e,g.muted=!0,yield new Promise(i=>{g.onplay=()=>{setTimeout(()=>{var I,C,o,a;const Q=document.createElement("canvas"),n=A.getSettings(),s=(C=(I=n.width)!==null&&I!==void 0?I:g.videoWidth)!==null&&C!==void 0?C:1280,B=(a=(o=n.height)!==null&&o!==void 0?o:g.videoHeight)!==null&&a!==void 0?a:720;Q.width=s,Q.height=B;const E=Q.getContext("2d");E.drawImage(g,0,0);const c=E.getImageData(0,0,Q.width,Q.height).data;let h=!0;for(let r=0;r<c.length;r+=4)if(c[r]!==0||c[r+1]!==0||c[r+2]!==0){h=!1;break}h?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},g.play()}),e.getTracks().forEach(i=>i.stop()),g.remove()})}}class Jl extends ei{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect();let g=!1,i=!1,I;const C=new Promise(Q=>{setTimeout(Q,5e3),I=Q}),o=()=>{g=!0};e.on(tA.SignalReconnecting,o).on(tA.Reconnecting,o).on(tA.Reconnected,()=>{i=!0,I(!0)}),(A=e.engine.client.ws)===null||A===void 0||A.close();const a=e.engine.client.onClose;if(a&&a(""),yield C,g){if(!i||e.state!==se.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 Yl extends ei{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var A,e;const g=new QQ,i=yield g.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let I=!1,C=!1,o=!1;for(let a of i.iceServers)for(let Q of a.urls)Q.startsWith("turn:")?(C=!0,o=!0):Q.startsWith("turns:")&&(C=!0,o=!0,I=!0),Q.startsWith("stun:")&&(o=!0);o?C&&!I&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield g.close(),!((e=(A=this.connectOptions)===null||A===void 0?void 0:A.rtcConfig)===null||e===void 0)&&e.iceServers||C?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class Tl extends ei{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let A=!1,e=!1;this.room.on(tA.SignalConnected,()=>{const g=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,I)=>{if(i.candidate){const C=new RTCIceCandidate(i);let o="".concat(C.protocol," ").concat(C.address,":").concat(C.port," ").concat(C.type);C.address&&(ql(C.address)?o+=" (private)":C.protocol==="tcp"&&C.tcpType==="passive"?(A=!0,o+=" (passive)"):C.protocol==="udp"&&(e=!0)),this.appendMessage(o)}g&&g(i,I)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),$A.info("now the room is connected")}catch(g){throw this.appendWarning("ports need to be open on firewall in order to connect."),g}A||this.appendWarning("Server is not configured for ICE/TCP"),e||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function ql(t){const A=t.split(".");if(A.length===4){if(A[0]==="10")return!0;if(A[0]==="192"&&A[1]==="168")return!0;if(A[0]==="172"){const e=parseInt(A[1],10);if(e>=16&&e<=31)return!0}}return!1}class Hl extends ei{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var A,e,g;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new QQ;const I=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(I.serverVersion,".")),((A=I.serverInfo)===null||A===void 0?void 0:A.edition)===NB.Cloud&&(!((e=I.serverInfo)===null||e===void 0)&&e.region)&&this.appendMessage("LiveKit Cloud: ".concat((g=I.serverInfo)===null||g===void 0?void 0:g.region)),yield i.close()})}}class rp extends At.EventEmitter{constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=A,this.token=e,this.options=g}getNextCheckId(){const A=this.checkResults.size;return this.checkResults.set(A,{logs:[],status:qg.IDLE,name:"",description:""}),A}updateCheck(A,e){this.checkResults.set(A,e),this.emit("checkUpdate",A,e)}isSuccess(){return Array.from(this.checkResults.values()).every(A=>A.status!==qg.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(A){return S(this,void 0,void 0,function*(){const e=this.getNextCheckId(),g=new A(this.url,this.token,this.options),i=C=>{this.updateCheck(e,C)};g.on("update",i);const I=yield g.run();return g.off("update",i),I})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Hl)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Tl)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Yl)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Jl)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Kl)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(vl)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const A=yield this.createAndRunCheck(Ll);if(A.data&&"protocol"in A.data){const e=A.data;this.options.protocol=e.protocol}return A})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Ul)})}}var Pl=Object.defineProperty,Ol=(t,A,e)=>A in t?Pl(t,A,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[A]=e,pt=(t,A,e)=>(Ol(t,typeof A!="symbol"?A+"":A,e),e),NQ=(t,A,e)=>{if(!A.has(t))throw TypeError("Cannot "+e)},XA=(t,A,e)=>(NQ(t,A,"read from private field"),e?e.call(t):A.get(t)),mt=(t,A,e)=>{if(A.has(t))throw TypeError("Cannot add the same private member more than once");A instanceof WeakSet?A.add(t):A.set(t,e)},Ng=(t,A,e,g)=>(NQ(t,A,"write to private field"),A.set(t,e),e),kr=(t,A,e)=>(NQ(t,A,"access private method"),e);function Qo(){const t=[`
|
|
84
|
+
`},EQ}var ar;function qx(){if(ar)return Yg;ar=1;var t=Yx(),A=Tx(),e=BQ();return Yg.grammar=e,Yg.write=A,Yg.parse=t.parse,Yg.parseParams=t.parseParams,Yg.parseFmtpConfig=t.parseFmtpConfig,Yg.parsePayloads=t.parsePayloads,Yg.parseRemoteCandidates=t.parseRemoteCandidates,Yg.parseImageAttributes=t.parseImageAttributes,Yg.parseSimulcastStreamList=t.parseSimulcastStreamList,Yg}var $t=qx();function rQ(t,A,e){var g,i,I;A===void 0&&(A=50),e===void 0&&(e={});var C=(g=e.isImmediate)!=null&&g,o=(i=e.callback)!=null&&i,a=e.maxWait,Q=Date.now(),n=[];function s(){if(a!==void 0){var E=Date.now()-Q;if(E+A>=a)return a-E}return A}var B=function(){var E=[].slice.call(arguments),d=this;return new Promise(function(c,h){var r=C&&I===void 0;if(I!==void 0&&clearTimeout(I),I=setTimeout(function(){if(I=void 0,Q=Date.now(),!C){var _=t.apply(d,E);o&&o(_),n.forEach(function(l){return(0,l.resolve)(_)}),n=[]}},s()),r){var f=t.apply(d,E);return o&&o(f),c(f)}n.push({resolve:c,reject:h})})};return B.cancel=function(E){I!==void 0&&clearTimeout(I),n.forEach(function(d){return(0,d.reject)(E)}),n=[]},B}const Hx=.7,Px=20,tI={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Qr extends At.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var g;super(),this.log=Ae,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=rQ(i=>S(this,void 0,void 0,function*(){this.emit(tI.NegotiationStarted);try{yield this.createAndSendOffer()}catch(I){if(i)i(I);else throw I}}),Px),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=lt((g=e.loggerName)!==null&&g!==void 0?g:vg.PCTransport),this.loggerOptions=e,this.config=A,this._pc=this.createPC(),this.offerLock=new sg}createPC(){const A=new RTCPeerConnection(this.config);return A.onicecandidate=e=>{var g;e.candidate&&((g=this.onIceCandidate)===null||g===void 0||g.call(this,e.candidate))},A.onicecandidateerror=e=>{var g;(g=this.onIceCandidateError)===null||g===void 0||g.call(this,e)},A.oniceconnectionstatechange=()=>{var e;(e=this.onIceConnectionStateChange)===null||e===void 0||e.call(this,A.iceConnectionState)},A.onsignalingstatechange=()=>{var e;(e=this.onSignalingStatechange)===null||e===void 0||e.call(this,A.signalingState)},A.onconnectionstatechange=()=>{var e;(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,A.connectionState)},A.ondatachannel=e=>{var g;(g=this.onDataChannel)===null||g===void 0||g.call(this,e)},A.ontrack=e=>{var g;(g=this.onTrack)===null||g===void 0||g.call(this,e)},A}get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions).loggerContextCb)===null||e===void 0?void 0:e.call(A))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(A){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(A);this.pendingCandidates.push(A)})}setRemoteDescription(A,e){return S(this,void 0,void 0,function*(){var g;if(A.type==="answer"&&this.latestOfferId>0&&e>0&&e!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:e,latestOfferId:this.latestOfferId})),!1;let i;if(A.type==="offer"){let{stereoMids:I,nackMids:C}=Ox(A);this.remoteStereoMids=I,this.remoteNackMids=C}else if(A.type==="answer"){const I=$t.parse((g=A.sdp)!==null&&g!==void 0?g:"");I.media.forEach(C=>{C.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||C.mid!=o.transceiver.mid)return!1;let a=0;if(C.rtp.some(n=>n.codec.toUpperCase()===o.codec.toUpperCase()?(a=n.payload,!0):!1),a===0)return!0;let Q=!1;for(const n of C.fmtp)if(n.payload===a){n.config=n.config.split(";").filter(s=>!s.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(n.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),Q=!0;break}return Q||o.maxbr>0&&C.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),i=$t.write(I)}return yield this.setMungedSDP(A,i,!0),this.pendingCandidates.forEach(I=>{this.pc.addIceCandidate(I)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):A.type==="answer"&&(this.emit(tI.NegotiationComplete),A.sdp&&$t.parse(A.sdp).media.forEach(C=>{C.type==="video"&&this.emit(tI.RTPVideoPayloadTypes,C.rtp)})),!0})}createAndSendOffer(A){return S(this,void 0,void 0,function*(){var e;const g=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(A!=null&&A.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(A!=null&&A.iceRestart&&o)yield this._pc.setRemoteDescription(o);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 i=this.latestOfferId+1;this.latestOfferId=i;const I=yield this.pc.createOffer(A);this.log.debug("original offer",Object.assign({sdp:I.sdp},this.logContext));const C=$t.parse((e=I.sdp)!==null&&e!==void 0?e:"");if(C.media.forEach(o=>{sr(o),o.type==="audio"?nr(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let Q=0;if(o.rtp.some(s=>s.codec.toUpperCase()===a.codec.toUpperCase()?(Q=s.payload,!0):!1),Q===0||(et(a.codec)&&!Di()&&this.ensureVideoDDExtensionForSVC(o,C),a.codec!=="av1"))return!0;const n=Math.round(a.maxbr*Hx);for(const s of o.fmtp)if(s.payload===Q){s.config.includes("x-google-start-bitrate")||(s.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(I,$t.write(C)),this.onOffer(I,this.latestOfferId)}finally{g()}})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pc.createAnswer(),g=$t.parse((A=e.sdp)!==null&&A!==void 0?A:"");return g.media.forEach(i=>{sr(i),i.type==="audio"&&nr(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,$t.write(g)),e})}createDataChannel(A,e){return this.pc.createDataChannel(A,e)}addTransceiver(A,e){return this.pc.addTransceiver(A,e)}addTrack(A){if(!this._pc)throw new Pe("PC closed, cannot add track");return this._pc.addTrack(A)}setTrackCodecBitrate(A){this.trackBitrates.push(A)}setConfiguration(A){var e;if(!this._pc)throw new Pe("PC closed, cannot configure");return(e=this._pc)===null||e===void 0?void 0:e.setConfiguration(A)}canRemoveTrack(){var A;return!!(!((A=this._pc)===null||A===void 0)&&A.removeTrack)}removeTrack(A){var e;return(e=this._pc)===null||e===void 0?void 0:e.removeTrack(A)}getConnectionState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.connectionState)!==null&&e!==void 0?e:"closed"}getICEConnectionState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.iceConnectionState)!==null&&e!==void 0?e:"closed"}getSignallingState(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.signalingState)!==null&&e!==void 0?e:"closed"}getTransceivers(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.getTransceivers())!==null&&e!==void 0?e:[]}getSenders(){var A,e;return(e=(A=this._pc)===null||A===void 0?void 0:A.getSenders())!==null&&e!==void 0?e:[]}getLocalDescription(){var A;return(A=this._pc)===null||A===void 0?void 0:A.localDescription}getRemoteDescription(){var A;return(A=this.pc)===null||A===void 0?void 0:A.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return S(this,void 0,void 0,function*(){var A;if(!this._pc)return;let e="";const g=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":e=o.selectedCandidatePairId;break;case"candidate-pair":e===""&&o.selected&&(e=o.id),g.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),e==="")return;const C=(A=g.get(e))===null||A===void 0?void 0:A.remoteCandidateId;if(C!==void 0)return i.get(C)})}setMungedSDP(A,e,g){return S(this,void 0,void 0,function*(){if(e){const i=A.sdp;A.sdp=e;try{this.log.debug("setting munged ".concat(g?"remote":"local"," description"),this.logContext),g?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A);return}catch(I){this.log.warn("not able to set ".concat(A.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:I,sdp:e})),A.sdp=i}}try{g?yield this.pc.setRemoteDescription(A):yield this.pc.setLocalDescription(A)}catch(i){let I="unknown error";i instanceof Error?I=i.message:typeof i=="string"&&(I=i);const C={error:I,sdp:A.sdp};throw!g&&this.pc.remoteDescription&&(C.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(A.type),Object.assign(Object.assign({},this.logContext),{fields:C})),new qa(I)}})}ensureVideoDDExtensionForSVC(A,e){var g,i;if(!((g=A.ext)===null||g===void 0?void 0:g.some(C=>C.uri===TE))){if(this.ddExtID===0){let C=0;e.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(Q=>{Q.value>C&&(C=Q.value)}))}),this.ddExtID=C+1}(i=A.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:TE})}}}function nr(t,A,e){let g=0;t.rtp.some(i=>i.codec==="opus"?(g=i.payload,!0):!1),g>0&&(t.rtcpFb||(t.rtcpFb=[]),e.includes(t.mid)&&!t.rtcpFb.some(i=>i.payload===g&&i.type==="nack")&&t.rtcpFb.push({payload:g,type:"nack"}),A.includes(t.mid)&&t.fmtp.some(i=>i.payload===g?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function Ox(t){var A;const e=[],g=[],i=$t.parse((A=t.sdp)!==null&&A!==void 0?A:"");let I=0;return i.media.forEach(C=>{var o;C.type==="audio"&&(C.rtp.some(a=>a.codec==="opus"?(I=a.payload,!0):!1),!((o=C.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===I&&a.type==="nack")&&g.push(C.mid),C.fmtp.some(a=>a.payload===I?(a.config.includes("sprop-stereo=1")&&e.push(C.mid),!0):!1))}),{stereoMids:e,nackMids:g}}function sr(t){if(t.connection){const A=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&A||t.connection.version===6&&!A)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const cQ="vp8",Vx={audioPreset:Oa.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ja.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cQ,backupCodec:!0,preConnectBuffer:!1},Br={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Er={deviceId:{ideal:"default"},resolution:ZI.h720.resolution},jx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Fd,disconnectOnPageLeave:!0,webAudioMix:!1},hQ={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ge;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Ge||(Ge={}));class Wx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(A,e,g){var i;this.peerConnectionTimeout=hQ.peerConnectionTimeout,this.log=Ae,this.updateState=()=>{var I;const C=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ge.CONNECTED:o.some(a=>a==="failed")?this.state=Ge.FAILED:o.some(a=>a==="connecting")?this.state=Ge.CONNECTING:o.every(a=>a==="closed")?this.state=Ge.CLOSED:o.some(a=>a==="closed")?this.state=Ge.CLOSING:o.every(a=>a==="new")&&(this.state=Ge.NEW),C!==this.state&&(this.log.debug("pc state change: from ".concat(Ge[C]," to ").concat(Ge[this.state]),this.logContext),(I=this.onStateChange)===null||I===void 0||I.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=lt((i=g.loggerName)!==null&&i!==void 0?i:vg.PCManager),this.loggerOptions=g,this.isPublisherConnectionRequired=!e,this.isSubscriberConnectionRequired=e,this.publisher=new Qr(A,g),this.subscriber=new Qr(A,g),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=I=>{var C;(C=this.onIceCandidate)===null||C===void 0||C.call(this,I,Kg.PUBLISHER)},this.subscriber.onIceCandidate=I=>{var C;(C=this.onIceCandidate)===null||C===void 0||C.call(this,I,Kg.SUBSCRIBER)},this.subscriber.onDataChannel=I=>{var C;(C=this.onDataChannel)===null||C===void 0||C.call(this,I)},this.subscriber.onTrack=I=>{var C;(C=this.onTrack)===null||C===void 0||C.call(this,I)},this.publisher.onOffer=(I,C)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,I,C)},this.state=Ge.NEW,this.connectionLock=new sg,this.remoteOfferLock=new sg}get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions).loggerContextCb)===null||e===void 0?void 0:e.call(A))}requirePublisher(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=A,this.updateState()}requireSubscriber(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=A,this.updateState()}createAndSendPublisherOffer(A){return this.publisher.createAndSendOffer(A)}setPublisherAnswer(A,e){return this.publisher.setRemoteDescription(A,e)}removeTrack(A){return this.publisher.removeTrack(A)}close(){return S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const A=this.publisher;for(const e of A.getSenders())try{A.canRemoveTrack()&&A.removeTrack(e)}catch(g){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:g}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(A,e){return S(this,void 0,void 0,function*(){e===Kg.PUBLISHER?yield this.publisher.addIceCandidate(A):yield this.subscriber.addIceCandidate(A)})}createSubscriberAnswerFromOffer(A,e){return S(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type,sdp:A.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const g=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(A,e))?yield this.subscriber.createAndSetAnswer():void 0}finally{g()}})}updateConfiguration(A,e){this.publisher.setConfiguration(A),this.subscriber.setConfiguration(A),e&&this.triggerIceRestart()}ensurePCTransportConnection(A,e){return S(this,void 0,void 0,function*(){var g;const i=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((g=this.requiredTransports)===null||g===void 0?void 0:g.map(I=>this.ensureTransportConnected(I,A,e)))}finally{i()}})}negotiate(A){return S(this,void 0,void 0,function*(){return new Promise((e,g)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{g("negotiation timed out")},this.peerConnectionTimeout),I=()=>{clearTimeout(i),g("negotiation aborted")};A.signal.addEventListener("abort",I),this.publisher.once(tI.NegotiationStarted,()=>{A.signal.aborted||this.publisher.once(tI.NegotiationComplete,()=>{clearTimeout(i),e()})}),yield this.publisher.negotiate(C=>{clearTimeout(i),g(C)})}))})}addPublisherTransceiver(A,e){return this.publisher.addTransceiver(A,e)}addPublisherTrack(A){return this.publisher.addTrack(A)}createPublisherDataChannel(A,e){return this.publisher.createDataChannel(A,e)}getConnectedAddress(A){return A===Kg.PUBLISHER?this.publisher.getConnectedAddress():A===Kg.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const A=[];return this.isPublisherConnectionRequired&&A.push(this.publisher),this.isSubscriberConnectionRequired&&A.push(this.subscriber),A}ensureTransportConnected(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(g.getConnectionState()!=="connected")return new Promise((a,Q)=>S(I,void 0,void 0,function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),ze.clearTimeout(s),Q(new ue("room connection has been cancelled",ie.Cancelled))};i!=null&&i.signal.aborted&&n(),i==null||i.signal.addEventListener("abort",n);const s=ze.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",n),Q(new ue("could not establish pc connection",ie.InternalError))},C);for(;this.state!==Ge.CONNECTED;)if(yield rg(50),i!=null&&i.signal.aborted){Q(new ue("room connection has been cancelled",ie.Cancelled));return}ze.clearTimeout(s),i==null||i.signal.removeEventListener("abort",n),a()}))}()})}}class Me extends Error{constructor(A,e,g){super(e),this.code=A,this.message=cr(e,Me.MAX_MESSAGE_BYTES),this.data=g?cr(g,Me.MAX_DATA_BYTES):void 0}static fromProto(A){return new Me(A.code,A.message,A.data)}toProto(){return new mB({code:this.code,message:this.message,data:this.data})}static builtIn(A,e){return new Me(Me.ErrorCode[A],Me.ErrorMessage[A],e)}}Me.MAX_MESSAGE_BYTES=256,Me.MAX_DATA_BYTES=15360,Me.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},Me.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 rr=15360;function dQ(t){return new TextEncoder().encode(t).length}function cr(t,A){if(dQ(t)<=A)return t;let e=0,g=t.length;const i=new TextEncoder;for(;e<g;){const I=Math.floor((e+g+1)/2);i.encode(t.slice(0,I)).length<=A?e=I:g=I-1}return t.slice(0,e)}const xQ=2e3;function io(t,A){if(!A)return 0;let e,g;return"bytesReceived"in t?(e=t.bytesReceived,g=A.bytesReceived):"bytesSent"in t&&(e=t.bytesSent,g=A.bytesSent),e===void 0||g===void 0||t.timestamp===void 0||A.timestamp===void 0?0:(e-g)*8*1e3/(t.timestamp-A.timestamp)}const lQ=typeof MediaRecorder<"u";class Xx{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Zx=lQ?MediaRecorder:Xx;class zx extends Zx{constructor(A,e){if(!lQ)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([A.mediaStreamTrack]),e);let g,i;const I=()=>i===void 0,C=()=>{this.removeEventListener("dataavailable",g),this.removeEventListener("stop",C),this.removeEventListener("error",o),i==null||i.close(),i=void 0},o=a=>{i==null||i.error(a),this.removeEventListener("dataavailable",g),this.removeEventListener("stop",C),this.removeEventListener("error",o),i=void 0};this.byteStream=new ReadableStream({start:a=>{i=a,g=Q=>S(this,void 0,void 0,function*(){let n;if(Q.data.arrayBuffer){const s=yield Q.data.arrayBuffer();n=new Uint8Array(s)}else if(Q.data.byteArray)n=Q.data.byteArray;else throw new Error("no data available!");I()||a.enqueue(n)}),this.addEventListener("dataavailable",g)},cancel:()=>{C()}}),this.addEventListener("stop",C),this.addEventListener("error",o)}}function $x(){return lQ}const Al=1e3,el=1e4;class hr extends AA{get sender(){return this._sender}set sender(A){this._sender=A}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(A,e,g){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,I=arguments.length>4?arguments[4]:void 0;super(A,e,I),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=rQ(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(oA.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new sg,this.pauseUpstreamLock=new sg,this.trackChangeLock=new sg,this.trackChangeLock.lock().then(C=>S(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(A,!0)}finally{C()}})),this._constraints=A.getConstraints(),g&&(this._constraints=g)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==AA.Kind.Video)return;const{width:A,height:e}=this._mediaStreamTrack.getSettings();if(A&&e)return{width:A,height:e}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var A,e;return(e=(A=this.processor)===null||A===void 0?void 0:A.processedTrack)!==null&&e!==void 0?e:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(A,e){return S(this,void 0,void 0,function*(){var g;if(A===this._mediaStreamTrack&&!e)return;this._mediaStreamTrack&&(this.attachedElements.forEach(I=>{eI(this._mediaStreamTrack,I)}),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([A]),A&&(A.addEventListener("ended",this.handleEnded),A.addEventListener("mute",this.handleTrackMuteEvent),A.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=A.getConstraints());let i;if(this.processor&&A){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(AI(A,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:A,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&((g=this.sender.transport)===null||g===void 0?void 0:g.state)!=="closed"&&(yield this.sender.replaceTrack(i??A)),!this.providedByUser&&this._mediaStreamTrack!==A&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=A,A&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(I=>{AI(i??A,I)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Al;return function*(){var g;if(A.kind===AA.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((g=fg())===null||g===void 0?void 0:g.os)==="iOS"&&(yield rg(10));const i=Date.now();for(;Date.now()-i<e;){const I=A.dimensions;if(I)return I;yield rg(50)}throw new Dt("unable to get track dimensions after timeout")}()})}setDeviceId(A){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===A&&this._mediaStreamTrack.getSettings().deviceId===Xt(A)||(this._constraints.deviceId=A,this.isMuted)?!0:(yield this.restartTrack(),Xt(A)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(A.source===AA.Source.ScreenShare)return;const{deviceId:g,groupId:i}=A._mediaStreamTrack.getSettings(),I=A.kind===AA.Kind.Audio?"audioinput":"videoinput";return e?We.getInstance().normalizeDeviceId(I,g,i):g}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(A,e){return S(this,void 0,void 0,function*(){const g=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Dt("unable to replace an unpublished track");let i,I;return typeof e=="boolean"?i=e:e!==void 0&&(i=e.userProvidedTrack,I=e.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(A),I&&this.processor&&(yield this.internalStopProcessor()),this}finally{g()}})}restart(A){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const e=yield this.trackChangeLock.lock();try{A||(A=this._constraints);const{deviceId:g,facingMode:i}=A,I=Ud(A,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:A}));const C={audio:!1,video:!1};this.kind===AA.Kind.Video?C.video=g||i?{deviceId:g,facingMode:i}:!0:C.audio=g?Object.assign({deviceId:g},I):!0,this.attachedElements.forEach(Q=>{eI(this.mediaStreamTrack,Q)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(C)).getTracks()[0];return this.kind===AA.Kind.Video&&(yield a.applyConstraints(I)),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=A,this.emit(oA.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{e()}})}setTrackMuted(A){this.log.debug("setting ".concat(this.kind," track ").concat(A?"muted":"unmuted"),this.logContext),!(this.isMuted===A&&this._mediaStreamTrack.enabled!==A)&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?oA.Muted:oA.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),qE()&&(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 A;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(A=this.processor)===null||A===void 0||A.destroy(),this.processor=void 0}pauseUpstream(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(oA.UpstreamPaused,this);const g=fg();if((g==null?void 0:g.name)==="Safari"&&tt(g.version,"12.0")<0)throw new Ta("pauseUpstream is not supported on Safari < 12.");((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var A;const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(oA.UpstreamResumed,this),((A=this.sender.transport)===null||A===void 0?void 0:A.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var A;return!((A=this.sender)===null||A===void 0)&&A.getStats?yield this.sender.getStats():void 0})}setProcessor(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var I;const C=yield g.trackChangeLock.lock();try{g.log.debug("setting up processor",g.logContext);const o=document.createElement(g.kind),a={kind:g.kind,track:g._mediaStreamTrack,element:o,audioContext:g.audioContext};if(yield e.init(a),g.log.debug("processor initialized",g.logContext),g.processor&&(yield g.internalStopProcessor()),g.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(AI(g._mediaStreamTrack,o),o.muted=!0,o.play().catch(Q=>{Q instanceof DOMException&&Q.name==="AbortError"?(g.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},g.logContext),{error:Q})),setTimeout(()=>{o.play().catch(n=>{g.log.error("failed to play processor element",Object.assign(Object.assign({},g.logContext),{err:n}))})},100)):g.log.error("failed to play processor element",Object.assign(Object.assign({},g.logContext),{error:Q}))}),g.processor=e,g.processorElement=o,g.processor.processedTrack){for(const Q of g.attachedElements)Q!==g.processorElement&&i&&(eI(g._mediaStreamTrack,Q),AI(g.processor.processedTrack,Q));yield(I=g.sender)===null||I===void 0?void 0:I.replaceTrack(g.processor.processedTrack)}g.emit(oA.TrackProcessorUpdate,g.processor)}finally{C()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const g=yield A.trackChangeLock.lock();try{yield A.internalStopProcessor(e)}finally{g()}}()})}internalStopProcessor(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var g,i;A.processor&&(A.log.debug("stopping processor",A.logContext),(g=A.processor.processedTrack)===null||g===void 0||g.stop(),yield A.processor.destroy(),A.processor=void 0,e||((i=A.processorElement)===null||i===void 0||i.remove(),A.processorElement=void 0),yield A._mediaStreamTrack.applyConstraints(A._constraints),yield A.setMediaStreamTrack(A._mediaStreamTrack,!0),A.emit(oA.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!$x()){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 e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new zx(this,{mimeType:e})}this.localTrackRecorder.start(A),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},el)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.byteStream}getPreConnectBufferMimeType(){var A;return(A=this.localTrackRecorder)===null||A===void 0?void 0:A.mimeType}}class Io extends hr{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0;super(A,AA.Kind.Audio,e,g,I),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let C;try{C=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}C&&this.prevStats&&(this._currentBitrate=io(C,this.prevStats)),this.prevStats=C}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oA.AudioTrackFeatureUpdate,this,je.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oA.AudioTrackFeatureUpdate,this,je.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===AA.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{e()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const g=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Xt(this._constraints.deviceId);return this.source===AA.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||g)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this}finally{e()}})}restartTrack(A){return S(this,void 0,void 0,function*(){let e;if(A){const g=CQ({audio:A});typeof g.audio!="boolean"&&(e=g.audio)}yield this.restart(e)})}restart(A){const e=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const g=yield e.restart.call(this,A);return this.checkForSilence(),g})}startMonitor(){cg()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},xQ)))}setProcessor(A){return S(this,void 0,void 0,function*(){var e;const g=yield this.trackChangeLock.lock();try{if(!gt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(A.name),this.logContext),yield A.init(i),this.processor=A,this.processor.processedTrack&&(yield(e=this.sender)===null||e===void 0?void 0:e.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(oA.TrackProcessorUpdate,this.processor)}finally{g()}})}setAudioContext(A){this.audioContext=A}getSenderStats(){return S(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return;const e=yield this.sender.getStats();let g;return e.forEach(i=>{i.type==="outbound-rtp"&&(g={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),g})}checkForSilence(){return S(this,void 0,void 0,function*(){const A=yield zE(this);return A&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oA.AudioSilenceDetected)),A})}}function gl(t,A,e){switch(t.kind){case"audio":return new Io(t,A,!1,void 0,e);case"video":return new Co(t,A,!1,e);default:throw new Dt("unsupported track type: ".concat(t.kind))}}const tl=Object.values(ZI),il=Object.values(Va),Il=Object.values(ja),Cl=[ZI.h180,ZI.h360],ol=[Va.h180,Va.h360],al=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var g,i;return new xe(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*(((g=t.encoding.maxFramerate)!==null&&g!==void 0?g:30)/((i=e.fps)!==null&&i!==void 0?i:30))))),e.fps,t.encoding.priority)}),fQ=["q","h","f"];function uQ(t,A,e,g){var i,I;let C=g==null?void 0:g.videoEncoding;t&&(C=g==null?void 0:g.screenShareEncoding);const o=g==null?void 0:g.simulcast,a=g==null?void 0:g.scalabilityMode,Q=g==null?void 0:g.videoCodec;if(!C&&!o&&!a||!A||!e)return[{}];C||(C=nl(t,A,e,Q),Ae.debug("using video encoding",C));const n=C.maxFramerate,s=new xe(A,e,C.maxBitrate,C.maxFramerate,C.priority);if(a&&et(Q)){const d=new lr(a),c=[];if(d.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const h=fg();if(zI()||gt()||(h==null?void 0:h.name)==="Chrome"&&tt(h==null?void 0:h.version,"113")<0){const r=d.suffix=="h"?2:3,f=Ex(h);for(let _=0;_<d.spatial;_+=1)c.push({rid:fQ[2-_],maxBitrate:C.maxBitrate/Math.pow(r,_),maxFramerate:s.encoding.maxFramerate,scaleResolutionDownBy:f?Math.pow(2,_):void 0});c[0].scalabilityMode=a}else c.push({maxBitrate:C.maxBitrate,maxFramerate:s.encoding.maxFramerate,scalabilityMode:a});return s.encoding.priority&&(c[0].priority=s.encoding.priority,c[0].networkPriority=s.encoding.priority),Ae.debug("using svc encoding",{encodings:c}),c}if(!o)return[C];let B=[];t?B=(i=xr(g==null?void 0:g.screenShareSimulcastLayers))!==null&&i!==void 0?i:dr(t,s):B=(I=xr(g==null?void 0:g.videoSimulcastLayers))!==null&&I!==void 0?I:dr(t,s);let E;if(B.length>0){const d=B[0];B.length>1&&([,E]=B);const c=Math.max(A,e);if(c>=960&&E)return DQ(A,e,[d,E,s],n);if(c>=480)return DQ(A,e,[d,s],n)}return DQ(A,e,[s])}function Ql(t,A,e){var g,i,I,C;if(!e.backupCodec||e.backupCodec===!0||e.backupCodec.codec===e.videoCodec)return;A!==e.backupCodec.codec&&Ae.warn("requested a different codec than specified as backup",{serverRequested:A,backup:e.backupCodec.codec}),e.videoCodec=A,e.videoEncoding=e.backupCodec.encoding;const o=t.mediaStreamTrack.getSettings(),a=(g=o.width)!==null&&g!==void 0?g:(i=t.dimensions)===null||i===void 0?void 0:i.width,Q=(I=o.height)!==null&&I!==void 0?I:(C=t.dimensions)===null||C===void 0?void 0:C.height;return t.source===AA.Source.ScreenShare&&e.simulcast&&(e.simulcast=!1),uQ(t.source===AA.Source.ScreenShare,a,Q,e)}function nl(t,A,e,g){const i=sl(t,A,e);let{encoding:I}=i[0];const C=Math.max(A,e);for(let o=0;o<i.length;o+=1){const a=i[o];if(I=a.encoding,a.width>=C)break}if(g)switch(g){case"av1":case"h265":I=Object.assign({},I),I.maxBitrate=I.maxBitrate*.7;break;case"vp9":I=Object.assign({},I),I.maxBitrate=I.maxBitrate*.85;break}return I}function sl(t,A,e){if(t)return Il;const g=A>e?A/e:e/A;return Math.abs(g-16/9)<Math.abs(g-4/3)?tl:il}function dr(t,A){if(t)return al(A);const{width:e,height:g}=A,i=e>g?e/g:g/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cl:ol}function DQ(t,A,e,g){const i=[];if(e.forEach((I,C)=>{if(C>=fQ.length)return;const o=Math.min(t,A),Q={rid:fQ[C],scaleResolutionDownBy:Math.max(1,o/Math.min(I.width,I.height)),maxBitrate:I.encoding.maxBitrate},n=g&&I.encoding.maxFramerate?Math.min(g,I.encoding.maxFramerate):I.encoding.maxFramerate;n&&(Q.maxFramerate=n);const s=ui()||C===0;I.encoding.priority&&s&&(Q.priority=I.encoding.priority,Q.networkPriority=I.encoding.priority),i.push(Q)}),gt()&&PE()==="ios"){let I;i.forEach(o=>{I?o.maxFramerate&&o.maxFramerate>I&&(I=o.maxFramerate):I=o.maxFramerate});let C=!0;i.forEach(o=>{var a;o.maxFramerate!=I&&(C&&(C=!1,Ae.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ae.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(I)),o.maxFramerate=I)})}return i}function xr(t){if(t)return t.sort((A,e)=>{const{encoding:g}=A,{encoding:i}=e;return g.maxBitrate>i.maxBitrate?1:g.maxBitrate<i.maxBitrate?-1:g.maxBitrate===i.maxBitrate&&g.maxFramerate&&i.maxFramerate?g.maxFramerate>i.maxFramerate?1:-1:0})}class lr{constructor(A){const e=A.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw new Error("invalid scalability mode");if(this.spatial=parseInt(e[1]),this.temporal=parseInt(e[2]),e.length>3)switch(e[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=e[3]}}toString(){var A;return"L".concat(this.spatial,"T").concat(this.temporal).concat((A=this.suffix)!==null&&A!==void 0?A:"")}}function Bl(t){return t.source===AA.Source.ScreenShare||t.constraints.height&&Xt(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const El=5e3;class Co extends hr{get sender(){return this._sender}set sender(A){this._sender=A,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(A,AA.Kind.Video,e,g,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let I;try{I=yield this.getSenderStats()}catch(a){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const C=new Map(I.map(a=>[a.rid,a])),o=I.some(a=>a.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(oA.CpuConstrained)),this.prevStats){let a=0;C.forEach((Q,n)=>{var s;const B=(s=this.prevStats)===null||s===void 0?void 0:s.get(n);a+=io(Q,B)}),this._currentBitrate=a}this.prevStats=C}),this.senderLock=new sg}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(A){var e;if(this.signalClient=A,!cg())return;const g=(e=this.sender)===null||e===void 0?void 0:e.getParameters();g&&(this.encodings=g.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},xQ))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(A=>{A.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const A=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var e,g,i,I,C;yield A.pauseUpstream.call(this);try{for(var o=!0,a=ft(this.simulcastCodecs.values()),Q;Q=yield a.next(),e=Q.done,!e;o=!0)I=Q.value,o=!1,yield(C=I.sender)===null||C===void 0?void 0:C.replaceTrack(null)}catch(n){g={error:n}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(g)throw g.error}}})}resumeUpstream(){const A=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var e,g,i,I,C;yield A.resumeUpstream.call(this);try{for(var o=!0,a=ft(this.simulcastCodecs.values()),Q;Q=yield a.next(),e=Q.done,!e;o=!0){I=Q.value,o=!1;const n=I;yield(C=n.sender)===null||C===void 0?void 0:C.replaceTrack(n.mediaStreamTrack)}}catch(n){g={error:n}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(g)throw g.error}}})}mute(){const A=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===AA.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield A.mute.call(this),this)}finally{e()}})}unmute(){const A=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source===AA.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield A.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{e()}})}setTrackMuted(A){super.setTrackMuted(A);for(const e of this.simulcastCodecs.values())e.mediaStreamTrack.enabled=!A}getSenderStats(){return S(this,void 0,void 0,function*(){var A;if(!(!((A=this.sender)===null||A===void 0)&&A.getStats))return[];const e=[],g=yield this.sender.getStats();return g.forEach(i=>{var I;if(i.type==="outbound-rtp"){const C={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(I=i.rid)!==null&&I!==void 0?I:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=g.get(i.remoteId);o&&(C.jitter=o.jitter,C.packetsLost=o.packetsLost,C.roundTripTime=o.roundTripTime),e.push(C)}}),e.sort((i,I)=>{var C,o;return((C=I.frameWidth)!==null&&C!==void 0?C:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),e})}setPublishingQuality(A){const e=[];for(let g=ug.LOW;g<=ug.HIGH;g+=1)e.push(new Sa({quality:g,enabled:g<=A}));this.log.debug("setting publishing quality. max quality ".concat(A),this.logContext),this.setPublishingLayers(et(this.codec),e)}restartTrack(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C;let o;if(A){const s=CQ({video:A});typeof s.video!="boolean"&&(o=s.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var a=!0,Q=ft(this.simulcastCodecs.values()),n;n=yield Q.next(),e=n.done,!e;a=!0){I=n.value,a=!1;const s=I;s.sender&&((C=s.sender.transport)===null||C===void 0?void 0:C.state)!=="closed"&&(s.mediaStreamTrack=this.mediaStreamTrack.clone(),yield s.sender.replaceTrack(s.mediaStreamTrack))}}catch(s){g={error:s}}finally{try{!a&&!e&&(i=Q.return)&&(yield i.call(Q))}finally{if(g)throw g.error}}})}setProcessor(A){const e=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(g){var i=this;let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var C,o,a,Q,n,s;if(yield e.setProcessor.call(i,g,I),!((n=i.processor)===null||n===void 0)&&n.processedTrack)try{for(var B=!0,E=ft(i.simulcastCodecs.values()),d;d=yield E.next(),C=d.done,!C;B=!0)Q=d.value,B=!1,yield(s=Q.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}catch(c){o={error:c}}finally{try{!B&&!C&&(a=E.return)&&(yield a.call(E))}finally{if(o)throw o.error}}}()})}setDegradationPreference(A){return S(this,void 0,void 0,function*(){if(this.degradationPreference=A,this.sender)try{this.log.debug("setting degradationPreference to ".concat(A),this.logContext);const e=this.sender.getParameters();e.degradationPreference=A,this.sender.setParameters(e)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(A,e){if(this.simulcastCodecs.has(A)){this.log.error("".concat(A," already added, skipping adding simulcast codec"),this.logContext);return}const g={codec:A,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:e};return this.simulcastCodecs.set(A,g),g}setSimulcastTrackSender(A,e){const g=this.simulcastCodecs.get(A);g&&(g.sender=e,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},El))}setPublishingCodecs(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:A,currentCodec:this.codec})),!this.codec&&A.length>0)return yield this.setPublishingLayers(et(A[0].codec),A[0].qualities),[];this.subscribedCodecs=A;const Q=[];try{for(e=!0,g=ft(A);i=yield g.next(),I=i.done,!I;e=!0){a=i.value,e=!1;const n=a;if(!this.codec||this.codec===n.codec)yield this.setPublishingLayers(et(n.codec),n.qualities);else{const s=this.simulcastCodecs.get(n.codec);if(this.log.debug("try setPublishingCodec for ".concat(n.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:s})),!s||!s.sender){for(const B of n.qualities)if(B.enabled){Q.push(n.codec);break}}else s.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(n.codec),this.logContext),yield fr(s.sender,s.encodings,n.qualities,this.senderLock,et(n.codec),this.log,this.logContext))}}}catch(n){C={error:n}}finally{try{!e&&!I&&(o=g.return)&&(yield o.call(g))}finally{if(C)throw C.error}}return Q})}setPublishingLayers(A,e){return S(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:e}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield fr(this.sender,this.encodings,e,this.senderLock,A,this.log,this.logContext))})}prioritizePerformance(){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const A=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((g,i)=>{var I;return Object.assign(Object.assign({},g),{active:i===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((I=this.mediaStreamTrack.getSettings().height)!==null&&I!==void 0?I:360)/360)),scalabilityMode:i===0&&et(this.codec)?"L1T3":void 0,maxFramerate:i===0?15:0,maxBitrate:i===0?g.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{A()}})}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),qE()&&this.isInBackground&&this.source===AA.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function fr(t,A,e,g,i,I,C){return S(this,void 0,void 0,function*(){const o=yield g.lock();I.debug("setPublishingLayersForSender",Object.assign(Object.assign({},C),{sender:t,qualities:e,senderEncodings:A}));try{const a=t.getParameters(),{encodings:Q}=a;if(!Q)return;if(Q.length!==A.length){I.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},C),{encodings:Q,senderEncodings:A}));return}let n=!1;!1&&Q[0].scalabilityMode||(i&&e.some(E=>E.enabled)&&e.forEach(E=>E.enabled=!0),Q.forEach((B,E)=>{var d;let c=(d=B.rid)!==null&&d!==void 0?d:"";c===""&&(c="q");const h=ur(c),r=e.find(f=>f.quality===h);r&&B.active!==r.enabled&&(n=!0,B.active=r.enabled,I.debug("setting layer ".concat(r.quality," to ").concat(B.active?"enabled":"disabled"),C),ui()&&(r.enabled?(B.scaleResolutionDownBy=A[E].scaleResolutionDownBy,B.maxBitrate=A[E].maxBitrate,B.maxFrameRate=A[E].maxFrameRate):(B.scaleResolutionDownBy=4,B.maxBitrate=10,B.maxFrameRate=2)))})),n&&(a.encodings=Q,I.debug("setting encodings",Object.assign(Object.assign({},C),{encodings:a.encodings})),yield t.setParameters(a))}finally{o()}})}function ur(t){switch(t){case"f":return ug.HIGH;case"h":return ug.MEDIUM;case"q":return ug.LOW;default:return ug.HIGH}}function Dr(t,A,e,g){if(!e)return[new xi({quality:ug.HIGH,width:t,height:A,bitrate:0,ssrc:0})];if(g){const i=e[0].scalabilityMode,I=new lr(i),C=[],o=I.suffix=="h"?1.5:2,a=I.suffix=="h"?2:3;for(let Q=0;Q<I.spatial;Q+=1)C.push(new xi({quality:Math.min(ug.HIGH,I.spatial-1)-Q,width:Math.ceil(t/Math.pow(o,Q)),height:Math.ceil(A/Math.pow(o,Q)),bitrate:e[0].maxBitrate?Math.ceil(e[0].maxBitrate/Math.pow(a,Q)):0,ssrc:0}));return C}return e.map(i=>{var I,C,o;const a=(I=i.scaleResolutionDownBy)!==null&&I!==void 0?I:1;let Q=ur((C=i.rid)!==null&&C!==void 0?C:"");return new xi({quality:Q,width:Math.ceil(t/a),height:Math.ceil(A/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const _r="_lossy",wr="_reliable",rl=2*1e3,_Q="leave-reconnect",cl=3e4;var Tg;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(Tg||(Tg={}));class hl extends At.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(A){var e;super(),this.options=A,this.rtcConfig={},this.peerConnectionTimeout=hQ.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Tg.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=Ae,this.reliableDataSequence=1,this.reliableMessageBuffer=new ir,this.reliableReceivedState=new Jx(cl),this.handleDataChannel=g=>S(this,[g],void 0,function(i){var I=this;let{channel:C}=i;return function*(){if(C){if(C.label===wr)I.reliableDCSub=C;else if(C.label===_r)I.lossyDCSub=C;else return;I.log.debug("on data channel ".concat(C.id,", ").concat(C.label),I.logContext),C.onmessage=I.handleDataMessage}}()}),this.handleDataMessage=g=>S(this,void 0,void 0,function*(){var i,I;const C=yield this.dataProcessLock.lock();try{let o;if(g.data instanceof ArrayBuffer)o=g.data;else if(g.data instanceof Blob)o=yield g.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:g.data}));return}const a=Eg.fromBinary(new Uint8Array(o));if(a.sequence>0&&a.participantSid!==""){const Q=this.reliableReceivedState.get(a.participantSid);if(Q&&a.sequence<=Q)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(nA.ActiveSpeakersUpdate,a.value.value.speakers):(((I=a.value)===null||I===void 0?void 0:I.case)==="user"&&xl(a,a.value.value),this.emit(nA.DataPacketReceived,a))}finally{C()}}),this.handleDataError=g=>{const I=g.currentTarget.maxRetransmits===0?"lossy":"reliable";if(g instanceof ErrorEvent&&g.error){const{error:C}=g.error;this.log.error("DataChannel error on ".concat(I,": ").concat(g.message),Object.assign(Object.assign({},this.logContext),{error:C}))}else this.log.error("Unknown DataChannel error on ".concat(I),Object.assign(Object.assign({},this.logContext),{event:g}))},this.handleBufferedAmountLow=g=>{const I=g.currentTarget.maxRetransmits===0?PA.LOSSY:PA.RELIABLE;this.updateAndEmitDCBufferStatus(I)},this.handleDisconnect=(g,i)=>{if(this._isClosed)return;this.log.warn("".concat(g," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const I=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(nA.Disconnected),this.close()},C=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:C,retryCount:this.reconnectAttempts});if(o===null){I(C);return}g===_Q&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ze.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((g,i)=>{this.pcState===Tg.Connected&&g();const I=()=>{this.off(nA.Disconnected,C),g()},C=()=>{this.off(nA.Restarted,I),i()};this.once(nA.Restarted,I),this.once(nA.Disconnected,C)}),this.updateAndEmitDCBufferStatus=g=>{const i=this.isBufferStatusLow(g);typeof i<"u"&&i!==this.dcBufferStatus.get(g)&&(this.dcBufferStatus.set(g,i),this.emit(nA.DCBufferStatusChanged,i,g))},this.isBufferStatusLow=g=>{const i=this.dataChannelForKind(g);if(i)return g===PA.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(i.bufferedAmount),i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ye.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Wi.RR_SIGNAL_DISCONNECTED))},this.log=lt((e=A.loggerName)!==null&&e!==void 0?e:vg.Engine),this.loggerOptions={loggerName:A.loggerName,loggerContextCb:()=>this.logContext},this.client=new QQ(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new sg,this.dataProcessLock=new sg,this.dcBufferStatus=new Map([[PA.LOSSY,!0],[PA.RELIABLE,!0]]),this.client.onParticipantUpdate=g=>this.emit(nA.ParticipantUpdate,g),this.client.onConnectionQuality=g=>this.emit(nA.ConnectionQualityUpdate,g),this.client.onRoomUpdate=g=>this.emit(nA.RoomUpdate,g),this.client.onSubscriptionError=g=>this.emit(nA.SubscriptionError,g),this.client.onSubscriptionPermissionUpdate=g=>this.emit(nA.SubscriptionPermissionUpdate,g),this.client.onSpeakersChanged=g=>this.emit(nA.SpeakersChanged,g),this.client.onStreamStateUpdate=g=>this.emit(nA.StreamStateChanged,g),this.client.onRequestResponse=g=>this.emit(nA.SignalRequestResponse,g)}get logContext(){var A,e,g,i,I,C;return{room:(e=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.room)===null||e===void 0?void 0:e.name,roomID:(i=(g=this.latestJoinResponse)===null||g===void 0?void 0:g.room)===null||i===void 0?void 0:i.sid,participant:(C=(I=this.latestJoinResponse)===null||I===void 0?void 0:I.participant)===null||C===void 0?void 0:C.identity,pID:this.participantSid}}join(A,e,g,i){return S(this,void 0,void 0,function*(){this.url=A,this.token=e,this.signalOpts=g,this.maxJoinAttempts=g.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const I=yield this.client.join(A,e,g,i);return this._isClosed=!1,this.latestJoinResponse=I,this.subscriberPrimary=I.subscriberPrimary,this.pcManager||(yield this.configure(I)),(!this.subscriberPrimary||I.fastPublish)&&this.negotiate(),this.clientConfiguration=I.clientConfiguration,this.emit(nA.SignalConnected,I),I}catch(I){if(I instanceof ue&&I.reason===ie.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(A,e,g,i);throw I}})}close(){return S(this,void 0,void 0,function*(){const A=yield this.closingLock.lock();if(this.isClosed){A();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(nA.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{A()}})}cleanupPeerConnections(){return S(this,void 0,void 0,function*(){var A;yield(A=this.pcManager)===null||A===void 0?void 0:A.close(),this.pcManager=void 0;const e=g=>{g&&(g.close(),g.onbufferedamountlow=null,g.onclose=null,g.onclosing=null,g.onerror=null,g.onmessage=null,g.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ir,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(A){if(this.pendingTrackResolvers[A.cid])throw new Dt("a track with the same ID has already been published");return new Promise((e,g)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[A.cid],g(new ue("publication of local track timed out, no response from server",ie.Timeout))},1e4);this.pendingTrackResolvers[A.cid]={resolve:I=>{clearTimeout(i),e(I)},reject:()=>{clearTimeout(i),g(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(A)})}removeTrack(A){if(A.track&&this.pendingTrackResolvers[A.track.id]){const{reject:e}=this.pendingTrackResolvers[A.track.id];e&&e(),delete this.pendingTrackResolvers[A.track.id]}try{return this.pcManager.removeTrack(A),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(A,e){this.client.sendMuteTrack(A,e)}get dataSubscriberReadyState(){var A;return(A=this.reliableDCSub)===null||A===void 0?void 0:A.readyState}getConnectedServerAddress(){return S(this,void 0,void 0,function*(){var A;return(A=this.pcManager)===null||A===void 0?void 0:A.getConnectedAddress()})}setRegionUrlProvider(A){this.regionUrlProvider=A}configure(A){return S(this,void 0,void 0,function*(){var e,g;if(this.pcManager&&this.pcManager.currentState!==Ge.NEW)return;this.participantSid=(e=A.participant)===null||e===void 0?void 0:e.sid;const i=this.makeRTCConfiguration(A);this.pcManager=new Wx(i,A.subscriberPrimary,this.loggerOptions),this.emit(nA.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(I,C)=>{this.client.sendIceCandidate(I,C)},this.pcManager.onPublisherOffer=(I,C)=>{this.client.sendOffer(I,C)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(I,C,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(I),this.logContext),["closed","disconnected","failed"].includes(C)&&(this.publisherConnectionPromise=void 0),I===Ge.CONNECTED){const n=this.pcState===Tg.New;this.pcState=Tg.Connected,n&&this.emit(nA.Connected,A)}else I===Ge.FAILED&&this.pcState===Tg.Connected&&(this.pcState=Tg.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Wi.RR_SUBSCRIBER_FAILED:Wi.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===ye.RECONNECTING,Q=[Ge.FAILED,Ge.CLOSING,Ge.CLOSED].includes(I);a&&Q&&!this._isClosed&&this.emit(nA.Offline)}),this.pcManager.onTrack=I=>{this.emit(nA.MediaTrackAdded,I.track,I.streams[0],I.receiver)},dl((g=A.serverInfo)===null||g===void 0?void 0:g.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(A,e)=>S(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:A.type})),yield this.pcManager.setPublisherAnswer(A,e))}),this.client.onTrickle=(A,e)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:A,target:e})),this.pcManager.addIceCandidate(A,e))},this.client.onOffer=(A,e)=>S(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=e,!this.pcManager)return;const g=yield this.pcManager.createSubscriberAnswerFromOffer(A,e);g&&this.client.sendAnswer(g,e)}),this.client.onLocalTrackPublished=A=>{var e;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:A.cid,track:(e=A.track)===null||e===void 0?void 0:e.sid})),!this.pendingTrackResolvers[A.cid]){this.log.error("missing track resolver for ".concat(A.cid),Object.assign(Object.assign({},this.logContext),{cid:A.cid}));return}const{resolve:g}=this.pendingTrackResolvers[A.cid];delete this.pendingTrackResolvers[A.cid],g(A.track)},this.client.onLocalTrackUnpublished=A=>{this.emit(nA.LocalTrackUnpublished,A)},this.client.onLocalTrackSubscribed=A=>{this.emit(nA.LocalTrackSubscribed,A)},this.client.onTokenRefresh=A=>{this.token=A},this.client.onRemoteMuteChanged=(A,e)=>{this.emit(nA.RemoteMute,A,e)},this.client.onSubscribedQualityUpdate=A=>{this.emit(nA.SubscribedQualityUpdate,A)},this.client.onRoomMoved=A=>{var e;this.participantSid=(e=A.participant)===null||e===void 0?void 0:e.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=A.room),this.emit(nA.RoomMoved,A)},this.client.onClose=()=>{this.handleDisconnect("signal",Wi.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=A=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:A==null?void 0:A.reason})),A.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(A.regions)),A.action){case zi.DISCONNECT:this.emit(nA.Disconnected,A==null?void 0:A.reason),this.close();break;case zi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(_Q);break;case zi.RESUME:this.handleDisconnect(_Q)}}}makeRTCConfiguration(A){var e;const g=Object.assign({},this.rtcConfig);if(!((e=this.signalOpts)===null||e===void 0)&&e.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),g.encodedInsertableStreams=!0),A.iceServers&&!g.iceServers){const i=[];A.iceServers.forEach(I=>{const C={urls:I.urls};I.username&&(C.username=I.username),I.credential&&(C.credential=I.credential),i.push(C)}),g.iceServers=i}return A.clientConfiguration&&A.clientConfiguration.forceRelay===PI.ENABLED&&(g.iceTransportPolicy="relay"),g.sdpSemantics="unified-plan",g.continualGatheringPolicy="gather_continually",g}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(_r,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wr,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(A,e,g){return S(this,void 0,void 0,function*(){if(Wa())return yield this.createTransceiverRTCRtpSender(A,e,g);if(Xa())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(A.mediaStreamTrack);throw new Pe("Required webRTC APIs not supported on this device")})}createSimulcastSender(A,e,g,i){return S(this,void 0,void 0,function*(){if(Wa())return this.createSimulcastTransceiverSender(A,e,g,i);if(Xa())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(A.mediaStreamTrack);throw new Pe("Cannot stream on this device")})}createTransceiverRTCRtpSender(A,e,g){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const i=[];A.mediaStream&&i.push(A.mediaStream),Zt(A)&&(A.codec=e.videoCodec);const I={direction:"sendonly",streams:i};return g&&(I.sendEncodings=g),(yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,I)).sender})}createSimulcastTransceiverSender(A,e,g,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");const I={direction:"sendonly"};i&&(I.sendEncodings=i);const C=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,I);if(g.videoCodec)return A.setSimulcastTrackSender(g.videoCodec,C.sender),C.sender})}createRTCRtpSender(A){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("publisher is closed");return this.pcManager.addPublisherTrack(A)})}attemptReconnect(A){return S(this,void 0,void 0,function*(){var e,g,i;if(!this._isClosed){if(this.attemptingReconnect){Ae.warn("already attempting reconnect, returning early",this.logContext);return}(((e=this.clientConfiguration)===null||e===void 0?void 0:e.resumeConnection)===PI.DISABLED||((i=(g=this.pcManager)===null||g===void 0?void 0:g.currentState)!==null&&i!==void 0?i:Ge.NEW)===Ge.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(A),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(I){this.reconnectAttempts+=1;let C=!0;I instanceof Pe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:I})),C=!1):I instanceof iI||(this.fullReconnectOnNext=!0),C?this.handleDisconnect("reconnect",Wi.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(nA.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(A){try{return this.reconnectPolicy.nextRetryDelayInMs(A)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(A){return S(this,void 0,void 0,function*(){var e,g,i;try{if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(nA.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let I;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new iI;I=yield this.join(A??this.url,this.token,this.signalOpts)}catch(C){throw C instanceof ue&&C.reason===ie.NotAllowed?new Pe("could not reconnect, token might be expired"):new iI}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(nA.SignalRestarted,I),yield this.waitForPCReconnected(),this.client.currentState!==ye.CONNECTED)throw new iI("Signal connection got severed during reconnect");(e=this.regionUrlProvider)===null||e===void 0||e.resetAttempts(),this.emit(nA.Restarted)}catch(I){const C=yield(g=this.regionUrlProvider)===null||g===void 0?void 0:g.getNextBestRegionUrl();if(C){yield this.restartConnection(C);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),I}})}resumeConnection(A){return S(this,void 0,void 0,function*(){var e;if(!this.url||!this.token)throw new Pe("could not reconnect, url or token not saved");if(!this.pcManager)throw new Pe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(nA.Resuming);let g;try{this.setupSignalClientCallbacks(),g=yield this.client.reconnect(this.url,this.token,this.participantSid,A)}catch(i){let I="";throw i instanceof Error&&(I=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof ue&&i.reason===ie.NotAllowed?new Pe("could not reconnect, token might be expired"):i instanceof ue&&i.reason===ie.LeaveRequest?i:new iI(I)}if(this.emit(nA.SignalResumed),g){const i=this.makeRTCConfiguration(g);this.pcManager.updateConfiguration(i),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=g.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!==ye.CONNECTED)throw new iI("Signal connection got severed during reconnect");this.client.setReconnected(),((e=this.reliableDC)===null||e===void 0?void 0:e.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),g!=null&&g.lastMessageSeq&&this.resendReliableMessagesForResume(g.lastMessageSeq),this.emit(nA.Resumed)})}waitForPCInitialConnection(A,e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,A)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=Tg.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield rg(rl),!this.pcManager)throw new Pe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Tg.Connected}catch(A){throw this.pcState=Tg.Disconnected,new ue("could not establish PC connection, ".concat(A.message),ie.InternalError)}})}publishRpcResponse(A,e,g,i){return S(this,void 0,void 0,function*(){const I=new Eg({destinationIdentities:[A],kind:PA.RELIABLE,value:{case:"rpcResponse",value:new pB({requestId:e,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:g??""}})}});yield this.sendDataPacket(I,PA.RELIABLE)})}publishRpcAck(A,e){return S(this,void 0,void 0,function*(){const g=new Eg({destinationIdentities:[A],kind:PA.RELIABLE,value:{case:"rpcAck",value:new wB({requestId:e})}});yield this.sendDataPacket(g,PA.RELIABLE)})}sendDataPacket(A,e){return S(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(e),e===PA.RELIABLE&&(A.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const g=A.toBinary(),i=this.dataChannelForKind(e);if(i){if(e===PA.RELIABLE&&this.reliableMessageBuffer.push({data:g,sequence:A.sequence}),this.attemptingReconnect)return;i.send(g)}this.updateAndEmitDCBufferStatus(e)})}resendReliableMessagesForResume(A){return S(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(PA.RELIABLE);const e=this.dataChannelForKind(PA.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(A),this.reliableMessageBuffer.getAll().forEach(g=>{e.send(g.data)})),this.updateAndEmitDCBufferStatus(PA.RELIABLE)})}waitForBufferStatusLow(A){return new Promise((e,g)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(A))e();else{const i=()=>g("Engine closed");for(this.once(nA.Closing,i);!this.dcBufferStatus.get(A);)yield rg(10);this.off(nA.Closing,i),e()}}))}ensureDataTransportConnected(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var I;if(!g.pcManager)throw new Pe("PC manager is closed");const C=i?g.pcManager.subscriber:g.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!C)throw new ue("".concat(o," connection not set"),ie.InternalError);let a=!1;!i&&!g.dataChannelForKind(e,i)&&(g.createDataChannels(),a=!0),!a&&!i&&!g.pcManager.publisher.isICEConnected&&g.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&g.negotiate();const Q=g.dataChannelForKind(e,i);if((Q==null?void 0:Q.readyState)==="open")return;const n=new Date().getTime()+g.peerConnectionTimeout;for(;new Date().getTime()<n;){if(C.isICEConnected&&((I=g.dataChannelForKind(e,i))===null||I===void 0?void 0:I.readyState)==="open")return;yield rg(50)}throw new ue("could not establish ".concat(o," connection, state: ").concat(C.getICEConnectionState()),ie.InternalError)}()})}ensurePublisherConnected(A){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(A,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ge.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((A,e)=>S(this,void 0,void 0,function*(){if(!this.pcManager){e(new qa("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const g=new AbortController,i=()=>{g.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),A()};this.isClosed&&e("cannot negotiate on closed engine"),this.on(nA.Closing,i),this.pcManager.publisher.once(tI.RTPVideoPayloadTypes,I=>{const C=new Map;I.forEach(o=>{const a=o.codec.toLowerCase();xx(a)&&C.set(o.payload,a)}),this.emit(nA.RTPVideoMapUpdate,C)});try{yield this.pcManager.negotiate(g),A()}catch(I){I instanceof qa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Wi.RR_UNKNOWN),e(I)}finally{this.off(nA.Closing,i)}}))})}dataChannelForKind(A,e){if(e){if(A===PA.LOSSY)return this.lossyDCSub;if(A===PA.RELIABLE)return this.reliableDCSub}else{if(A===PA.LOSSY)return this.lossyDC;if(A===PA.RELIABLE)return this.reliableDC}}sendSyncState(A,e){var g,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const I=this.pcManager.subscriber.getLocalDescription(),C=this.pcManager.subscriber.getRemoteDescription(),o=(i=(g=this.signalOpts)===null||g===void 0?void 0:g.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,Q=new Array;A.forEach(n=>{n.isDesired!==o&&a.push(n.trackSid),n.isEnabled||Q.push(n.trackSid)}),this.client.sendSyncState(new HB({answer:I?to({sdp:I.sdp,type:I.type}):void 0,offer:C?to({sdp:C.sdp,type:C.type}):void 0,subscription:new HC({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:yx(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:Q,datachannelReceiveStates:this.reliableReceivedState.map((n,s)=>new PB({publisherSid:s,lastSeq:n}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const A=[],e=(g,i)=>{(g==null?void 0:g.id)!==void 0&&g.id!==null&&A.push(new OB({label:g.label,id:g.id,target:i}))};return e(this.dataChannelForKind(PA.LOSSY),Kg.PUBLISHER),e(this.dataChannelForKind(PA.RELIABLE),Kg.PUBLISHER),e(this.dataChannelForKind(PA.LOSSY,!0),Kg.SUBSCRIBER),e(this.dataChannelForKind(PA.RELIABLE,!0),Kg.SUBSCRIBER),A}clearReconnectTimeout(){this.reconnectTimeout&&ze.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){cg()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){cg()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class iI extends Error{}function dl(t){return t!==void 0&&t>13}function xl(t,A){const e=t.participantIdentity?t.participantIdentity:A.participantIdentity;t.participantIdentity=e,A.participantIdentity=e;const g=t.destinationIdentities.length!==0?t.destinationIdentities:A.destinationIdentities;t.destinationIdentities=g,A.destinationIdentities=g}class wQ{constructor(A,e){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(A),this.token=e}updateToken(A){this.token=A}isCloud(){return za(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(A){return S(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(A));const e=this.regionSettings.regions.filter(g=>!this.attemptedRegions.find(i=>i.url===g.url));if(e.length>0){const g=e[0];return this.attemptedRegions.push(g),Ae.debug("next region: ".concat(g.region)),g.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(A){return S(this,void 0,void 0,function*(){const e=yield fetch("".concat(ll(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:A});if(e.ok){const g=yield e.json();return this.lastUpdateAt=Date.now(),g}else throw new ue("Could not fetch region settings: ".concat(e.statusText),e.status===401?ie.NotAllowed:ie.InternalError,e.status)})}setServerReportedRegions(A){this.regionSettings=A,this.lastUpdateAt=Date.now()}}function ll(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class pr{get info(){return this._info}validateBytesReceived(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(A&&this.bytesReceived<this.totalByteSize)throw new Wt("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Jg.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Wt("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Jg.LengthExceeded)}}constructor(A,e,g,i){this.reader=e,this.totalByteSize=g,this._info=A,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class fl extends pr{handleChunkReceived(A){var e;this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const g=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(e=this.onProgress)===null||e===void 0||e.call(this,g)}[Symbol.asyncIterator](){const A=this.reader.getReader();let e=new it,g=null,i=null;if(this.signal){const C=this.signal;i=()=>{var o;(o=e.reject)===null||o===void 0||o.call(e,C.reason)},C.addEventListener("abort",i),g=C}const I=()=>{A.releaseLock(),g&&i&&g.removeEventListener("abort",i),this.signal=void 0};return{next:()=>S(this,void 0,void 0,function*(){var C,o;try{const{done:a,value:Q}=yield Promise.race([A.read(),e.promise,(o=(C=this.outOfBandFailureRejectingFuture)===null||C===void 0?void 0:C.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return a?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(Q),{done:!1,value:Q.content})}catch(a){throw I(),a}}),return(){return S(this,void 0,void 0,function*(){return I(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var g,i,I,C;let o=new Set;const a=e.signal?A.withAbortSignal(e.signal):A;try{for(var Q=!0,n=ft(a),s;s=yield n.next(),g=s.done,!g;Q=!0){C=s.value,Q=!1;const B=C;o.add(B)}}catch(B){i={error:B}}finally{try{!Q&&!g&&(I=n.return)&&(yield I.call(n))}finally{if(i)throw i.error}}return Array.from(o)}()})}}class ul extends pr{constructor(A,e,g,i){super(A,e,g,i),this.receivedChunks=new Map}handleChunkReceived(A){var e;const g=go(A.chunkIndex),i=this.receivedChunks.get(g);if(i&&i.version>A.version)return;this.receivedChunks.set(g,A),this.bytesReceived+=A.content.byteLength,this.validateBytesReceived();const I=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(e=this.onProgress)===null||e===void 0||e.call(this,I)}[Symbol.asyncIterator](){const A=this.reader.getReader(),e=new TextDecoder("utf-8",{fatal:!0});let g=new it,i=null,I=null;if(this.signal){const o=this.signal;I=()=>{var a;(a=g.reject)===null||a===void 0||a.call(g,o.reason)},o.addEventListener("abort",I),i=o}const C=()=>{A.releaseLock(),i&&I&&i.removeEventListener("abort",I),this.signal=void 0};return{next:()=>S(this,void 0,void 0,function*(){var o,a;try{const{done:Q,value:n}=yield Promise.race([A.read(),g.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);if(Q)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(n);let s;try{s=e.decode(n.content)}catch(B){throw new Wt("Cannot decode datastream chunk ".concat(n.chunkIndex," as text: ").concat(B),Jg.DecodeFailed)}return{done:!1,value:s}}}catch(Q){throw C(),Q}}),return(){return S(this,void 0,void 0,function*(){return C(),{done:!0,value:void 0}})}}}withAbortSignal(A){return this.signal=A,this}readAll(){return S(this,arguments,void 0,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var g,i,I,C;let o="";const a=e.signal?A.withAbortSignal(e.signal):A;try{for(var Q=!0,n=ft(a),s;s=yield n.next(),g=s.done,!g;Q=!0)C=s.value,Q=!1,o+=C}catch(B){i={error:B}}finally{try{!Q&&!g&&(I=n.return)&&(yield I.call(n))}finally{if(i)throw i.error}}return o}()})}}class Dl{constructor(){this.log=Ae,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(A,e){if(this.textStreamHandlers.has(A))throw new Wt('A text stream handler for topic "'.concat(A,'" has already been set.'),Jg.HandlerAlreadyRegistered);this.textStreamHandlers.set(A,e)}unregisterTextStreamHandler(A){this.textStreamHandlers.delete(A)}registerByteStreamHandler(A,e){if(this.byteStreamHandlers.has(A))throw new Wt('A byte stream handler for topic "'.concat(A,'" has already been set.'),Jg.HandlerAlreadyRegistered);this.byteStreamHandlers.set(A,e)}unregisterByteStreamHandler(A){this.byteStreamHandlers.delete(A)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(A){var e,g,i,I;const C=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A),o=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===A);if(C.length>0||o.length>0){const a=new Wt("Participant ".concat(A," unexpectedly disconnected in the middle of sending data"),Jg.AbnormalEnd);for(const[Q,n]of o)(g=(e=n.outOfBandFailureRejectingFuture).reject)===null||g===void 0||g.call(e,a),this.byteStreamControllers.delete(Q);for(const[Q,n]of C)(I=(i=n.outOfBandFailureRejectingFuture).reject)===null||I===void 0||I.call(i,a),this.textStreamControllers.delete(Q)}}handleDataStreamPacket(A){return S(this,void 0,void 0,function*(){switch(A.value.case){case"streamHeader":return this.handleStreamHeader(A.value.value,A.participantIdentity);case"streamChunk":return this.handleStreamChunk(A.value.value);case"streamTrailer":return this.handleStreamTrailer(A.value.value);default:throw new Error('DataPacket of value "'.concat(A.value.case,'" is not data stream related!'))}})}handleStreamHeader(A,e){return S(this,void 0,void 0,function*(){var g;if(A.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(A.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",A.topic);return}let I;const C=new it,o={id:A.streamId,name:(g=A.contentHeader.value.name)!==null&&g!==void 0?g:"unknown",mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:go(A.timestamp),attributes:A.attributes},a=new ReadableStream({start:Q=>{if(I=Q,this.textStreamControllers.has(A.streamId))throw new Wt("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),Jg.AlreadyOpened);this.byteStreamControllers.set(A.streamId,{info:o,controller:I,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:C})}});i(new fl(o,a,go(A.totalLength),C),{identity:e})}else if(A.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(A.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",A.topic);return}let I;const C=new it,o={id:A.streamId,mimeType:A.mimeType,size:A.totalLength?Number(A.totalLength):void 0,topic:A.topic,timestamp:Number(A.timestamp),attributes:A.attributes},a=new ReadableStream({start:Q=>{if(I=Q,this.textStreamControllers.has(A.streamId))throw new Wt("A data stream read is already in progress for a stream with id ".concat(A.streamId,"."),Jg.AlreadyOpened);this.textStreamControllers.set(A.streamId,{info:o,controller:I,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:C})}});i(new ul(o,a,go(A.totalLength),C),{identity:e})}})}handleStreamChunk(A){const e=this.byteStreamControllers.get(A.streamId);e&&A.content.length>0&&e.controller.enqueue(A);const g=this.textStreamControllers.get(A.streamId);g&&A.content.length>0&&g.controller.enqueue(A)}handleStreamTrailer(A){const e=this.textStreamControllers.get(A.streamId);e&&(e.info.attributes=Object.assign(Object.assign({},e.info.attributes),A.attributes),e.controller.close(),this.textStreamControllers.delete(A.streamId));const g=this.byteStreamControllers.get(A.streamId);g&&(g.info.attributes=Object.assign(Object.assign({},g.info.attributes),A.attributes),g.controller.close(),this.byteStreamControllers.delete(A.streamId))}}class mr{constructor(A,e,g){this.writableStream=A,this.defaultWriter=A.getWriter(),this.onClose=g,this.info=e}write(A){return this.defaultWriter.write(A)}close(){return S(this,void 0,void 0,function*(){var A;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(A=this.onClose)===null||A===void 0||A.call(this)})}}class _l extends mr{}class wl extends mr{}const yr=15e3;class pl{constructor(A,e){this.engine=A,this.log=e}setupEngine(A){this.engine=A}sendText(A,e){return S(this,void 0,void 0,function*(){var g;const i=crypto.randomUUID(),C=new TextEncoder().encode(A).byteLength,o=(g=e==null?void 0:e.attachments)===null||g===void 0?void 0:g.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),Q=(s,B)=>{var E;a[B]=s;const d=a.reduce((c,h)=>c+h,0);(E=e==null?void 0:e.onProgress)===null||E===void 0||E.call(e,d)},n=yield this.streamText({streamId:i,totalSize:C,destinationIdentities:e==null?void 0:e.destinationIdentities,topic:e==null?void 0:e.topic,attachedStreamIds:o,attributes:e==null?void 0:e.attributes});return yield n.write(A),Q(1,0),yield n.close(),e!=null&&e.attachments&&o&&(yield Promise.all(e.attachments.map((s,B)=>S(this,void 0,void 0,function*(){return this._sendFile(o[B],s,{topic:e.topic,mimeType:s.type,onProgress:E=>{Q(E,B+1)}})})))),n.info})}streamText(A){return S(this,void 0,void 0,function*(){var e,g;const i=(e=A==null?void 0:A.streamId)!==null&&e!==void 0?e:crypto.randomUUID(),I={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(g=A==null?void 0:A.topic)!==null&&g!==void 0?g:"",size:A==null?void 0:A.totalSize,attributes:A==null?void 0:A.attributes},C=new ua({streamId:i,mimeType:I.mimeType,topic:I.topic,timestamp:_i(I.timestamp),totalLength:_i(A==null?void 0:A.totalSize),attributes:I.attributes,contentHeader:{case:"textHeader",value:new MB({version:A==null?void 0:A.version,attachedStreamIds:A==null?void 0:A.attachedStreamIds,replyToStreamId:A==null?void 0:A.replyToStreamId,operationType:(A==null?void 0:A.type)==="update"?fa.UPDATE:fa.CREATE})}}),o=A==null?void 0:A.destinationIdentities,a=new Eg({destinationIdentities:o,value:{case:"streamHeader",value:C}});yield this.engine.sendDataPacket(a,PA.RELIABLE);let Q=0;const n=this.engine,s=new WritableStream({write(d){return S(this,void 0,void 0,function*(){for(const c of wx(d,yr)){yield n.waitForBufferStatusLow(PA.RELIABLE);const h=new Da({content:c,streamId:i,chunkIndex:_i(Q)}),r=new Eg({destinationIdentities:o,value:{case:"streamChunk",value:h}});yield n.sendDataPacket(r,PA.RELIABLE),Q+=1}})},close(){return S(this,void 0,void 0,function*(){const d=new _a({streamId:i}),c=new Eg({destinationIdentities:o,value:{case:"streamTrailer",value:d}});yield n.sendDataPacket(c,PA.RELIABLE)})},abort(d){console.log("Sink error:",d)}});let B=()=>S(this,void 0,void 0,function*(){yield E.close()});n.once(nA.Closing,B);const E=new _l(s,I,()=>this.engine.off(nA.Closing,B));return E})}sendFile(A,e){return S(this,void 0,void 0,function*(){const g=crypto.randomUUID();return yield this._sendFile(g,A,e),{id:g}})}_sendFile(A,e,g){return S(this,void 0,void 0,function*(){var i;const I=yield this.streamBytes({streamId:A,totalSize:e.size,name:e.name,mimeType:(i=g==null?void 0:g.mimeType)!==null&&i!==void 0?i:e.type,topic:g==null?void 0:g.topic,destinationIdentities:g==null?void 0:g.destinationIdentities}),C=e.stream().getReader();for(;;){const{done:o,value:a}=yield C.read();if(o)break;yield I.write(a)}return yield I.close(),I.info})}streamBytes(A){return S(this,void 0,void 0,function*(){var e,g,i,I,C;const o=(e=A==null?void 0:A.streamId)!==null&&e!==void 0?e:crypto.randomUUID(),a=A==null?void 0:A.destinationIdentities,Q={id:o,mimeType:(g=A==null?void 0:A.mimeType)!==null&&g!==void 0?g:"application/octet-stream",topic:(i=A==null?void 0:A.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:A==null?void 0:A.attributes,size:A==null?void 0:A.totalSize,name:(I=A==null?void 0:A.name)!==null&&I!==void 0?I:"unknown"},n=new ua({totalLength:_i((C=Q.size)!==null&&C!==void 0?C:0),mimeType:Q.mimeType,streamId:o,topic:Q.topic,timestamp:_i(Date.now()),attributes:Q.attributes,contentHeader:{case:"byteHeader",value:new FB({name:Q.name})}}),s=new Eg({destinationIdentities:a,value:{case:"streamHeader",value:n}});yield this.engine.sendDataPacket(s,PA.RELIABLE);let B=0;const E=new sg,d=this.engine,c=this.log,h=new WritableStream({write(f){return S(this,void 0,void 0,function*(){const _=yield E.lock();let l=0;try{for(;l<f.byteLength;){const D=f.slice(l,l+yr);yield d.waitForBufferStatusLow(PA.RELIABLE);const p=new Eg({destinationIdentities:a,value:{case:"streamChunk",value:new Da({content:D,streamId:o,chunkIndex:_i(B)})}});yield d.sendDataPacket(p,PA.RELIABLE),B+=1,l+=D.byteLength}}finally{_()}})},close(){return S(this,void 0,void 0,function*(){const f=new _a({streamId:o}),_=new Eg({destinationIdentities:a,value:{case:"streamTrailer",value:f}});yield d.sendDataPacket(_,PA.RELIABLE)})},abort(f){c.error("Sink error:",f)}});return new wl(h,Q)})}}class br extends AA{constructor(A,e,g,i,I){super(A,g,I),this.sid=e,this.receiver=i}get isLocal(){return!1}setMuted(A){this.isMuted!==A&&(this.isMuted=A,this._mediaStreamTrack.enabled=!A,this.emit(A?oA.Muted:oA.Unmuted,this))}setMediaStream(A){this.mediaStream=A;const e=g=>{g.track===this._mediaStreamTrack&&(A.removeEventListener("removetrack",e),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(oA.Ended,this))};A.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var A;return!((A=this.receiver)===null||A===void 0)&&A.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(A){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=A: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(),xQ)),bx()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const A=()=>{var e;this.timeSyncHandle=requestAnimationFrame(()=>A());const g=(e=this.receiver)===null||e===void 0?void 0:e.getSynchronizationSources()[0];if(g){const{timestamp:i,rtpTimestamp:I}=g;I&&this.rtpTimestamp!==I&&(this.emit(oA.TimeSyncUpdate,{timestamp:i,rtpTimestamp:I}),this.rtpTimestamp=I)}};A()}}class ml extends br{constructor(A,e,g,i,I,C){super(A,e,AA.Kind.Audio,g,C),this.monitorReceiver=()=>S(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=io(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],I&&(this.sinkId=I.deviceId)}setVolume(A){var e;for(const g of this.attachedElements)this.audioContext?(e=this.gainNode)===null||e===void 0||e.gain.setTargetAtTime(A,0,.1):g.volume=A;gt()&&this._mediaStreamTrack._setVolume(A),this.elementVolume=A}getVolume(){if(this.elementVolume)return this.elementVolume;if(gt())return 1;let A=0;return this.attachedElements.forEach(e=>{e.volume>A&&(A=e.volume)}),A}setSinkId(A){return S(this,void 0,void 0,function*(){this.sinkId=A,yield Promise.all(this.attachedElements.map(e=>{if(Za(e))return e.setSinkId(A)}))})}attach(A){const e=this.attachedElements.length===0;return A?super.attach(A):A=super.attach(),this.sinkId&&Za(A)&&A.setSinkId(this.sinkId).catch(g=>{this.log.error("Failed to set sink id on remote audio track",g,this.logContext)}),this.audioContext&&e&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,A),A.volume=0,A.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),A}detach(A){let e;return A?(e=super.detach(A),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(e=super.detach(),this.disconnectWebAudio()),e}setAudioContext(A){this.audioContext=A,A&&this.attachedElements.length>0?this.connectWebAudio(A,this.attachedElements[0]):A||this.disconnectWebAudio()}setWebAudioPlugins(A){this.webAudioPluginNodes=A,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(A,e){this.disconnectWebAudio(),this.sourceNode=A.createMediaStreamSource(e.srcObject);let g=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{g.connect(i),g=i}),this.gainNode=A.createGain(),g.connect(this.gainNode),this.gainNode.connect(A.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),A.state!=="running"&&A.resume().then(()=>{A.state!=="running"&&this.emit(oA.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(oA.AudioPlaybackFailed,i)})}disconnectWebAudio(){var A,e;(A=this.gainNode)===null||A===void 0||A.disconnect(),(e=this.sourceNode)===null||e===void 0||e.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let e;return A.forEach(g=>{g.type==="inbound-rtp"&&(e={type:"audio",streamId:g.id,timestamp:g.timestamp,jitter:g.jitter,bytesReceived:g.bytesReceived,concealedSamples:g.concealedSamples,concealmentEvents:g.concealmentEvents,silentConcealedSamples:g.silentConcealedSamples,silentConcealmentEvents:g.silentConcealmentEvents,totalAudioEnergy:g.totalAudioEnergy,totalSamplesDuration:g.totalSamplesDuration})}),e})}}const pQ=100;class yl extends br{constructor(A,e,g,i,I){super(A,e,AA.Kind.Video,g,I),this.elementInfos=[],this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const C=yield this.getReceiverStats();C&&this.prevStats&&this.receiver&&(this._currentBitrate=io(C,this.prevStats)),this.prevStats=C}),this.debouncedHandleResize=rQ(()=>{this.updateDimensions()},pQ),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(A){super.setStreamState(A),console.log("setStreamState",A),A===AA.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(A){super.setMuted(A),this.attachedElements.forEach(e=>{A?eI(this._mediaStreamTrack,e):AI(this._mediaStreamTrack,e)})}attach(A){if(A?super.attach(A):A=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(e=>e.element===A)===void 0){const e=new bl(A);this.observeElementInfo(e)}return A}observeElementInfo(A){this.adaptiveStreamSettings&&this.elementInfos.find(e=>e===A)===void 0?(A.handleResize=()=>{this.debouncedHandleResize()},A.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(A),A.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(A){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const e=this.elementInfos.filter(g=>g===A);for(const g of e)g.stopObserving();this.elementInfos=this.elementInfos.filter(g=>g!==A),this.updateVisibility(),this.debouncedHandleResize()}detach(A){let e=[];if(A)return this.stopObservingElement(A),super.detach(A);e=super.detach();for(const g of e)this.stopObservingElement(g);return e}getDecoderImplementation(){var A;return(A=this.prevStats)===null||A===void 0?void 0:A.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const A=yield this.receiver.getStats();let e,g="",i=new Map;return A.forEach(I=>{I.type==="inbound-rtp"?(g=I.codecId,e={type:"video",streamId:I.id,framesDecoded:I.framesDecoded,framesDropped:I.framesDropped,framesReceived:I.framesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost,frameWidth:I.frameWidth,frameHeight:I.frameHeight,pliCount:I.pliCount,firCount:I.firCount,nackCount:I.nackCount,jitter:I.jitter,timestamp:I.timestamp,bytesReceived:I.bytesReceived,decoderImplementation:I.decoderImplementation}):I.type==="codec"&&i.set(I.id,I)}),e&&g!==""&&i.get(g)&&(e.mimeType=i.get(g).mimeType),e})}stopObservingElement(A){const e=this.elementInfos.filter(g=>g.element===A);for(const g of e)this.stopObservingElementInfo(g)}handleAppVisibilityChanged(){const A=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield A.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(A){var e,g;const i=this.elementInfos.reduce((a,Q)=>Math.max(a,Q.visibilityChangedAt||0),0),I=!((g=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&g!==void 0)||g?this.isInBackground:!1,C=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!I||C;if(!(this.lastVisible===o&&!A)){if(!o&&Date.now()-i<pQ){ze.setTimeout(()=>{this.updateVisibility()},pQ);return}this.lastVisible=o,this.emit(oA.VisibilityChanged,o,this)}}updateDimensions(){var A,e;let g=0,i=0;const I=this.getPixelDensity();for(const C of this.elementInfos){const o=C.width()*I,a=C.height()*I;o+a>g+i&&(g=o,i=a)}((A=this.lastDimensions)===null||A===void 0?void 0:A.width)===g&&((e=this.lastDimensions)===null||e===void 0?void 0:e.height)===i||(this.lastDimensions={width:g,height:i},this.emit(oA.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var A;const e=(A=this.adaptiveStreamSettings)===null||A===void 0?void 0:A.pixelDensity;return e==="screen"?OE():e||(OE()>2?2:1)}}class bl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(A,e){this.onVisibilityChanged=g=>{var i;const{target:I,isIntersecting:C}=g;I===this.element&&(this.isIntersecting=C,this.isPiP=gC(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var g,i,I;(i=(g=window.documentPictureInPicture)===null||g===void 0?void 0:g.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=gC(this.element),(I=this.handleVisibilityChanged)===null||I===void 0||I.call(this)},this.onLeavePiP=()=>{var g;this.isPiP=gC(this.element),(g=this.handleVisibilityChanged)===null||g===void 0||g.call(this)},this.element=A,this.isIntersecting=e??mQ(A),this.isPiP=cg()&&gC(A),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var A,e,g;this.isIntersecting=mQ(this.element),this.isPiP=gC(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,jE().observe(this.element),VE().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(A=window.documentPictureInPicture)===null||A===void 0||A.addEventListener("enter",this.onEnterPiP),(g=(e=window.documentPictureInPicture)===null||e===void 0?void 0:e.window)===null||g===void 0||g.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var A,e,g,i,I;(A=jE())===null||A===void 0||A.unobserve(this.element),(e=VE())===null||e===void 0||e.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(g=window.documentPictureInPicture)===null||g===void 0||g.removeEventListener("enter",this.onEnterPiP),(I=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||I===void 0||I.removeEventListener("pagehide",this.onLeavePiP)}}function gC(t){var A,e;return document.pictureInPictureElement===t?!0:!((A=window.documentPictureInPicture)===null||A===void 0)&&A.window?mQ(t,(e=window.documentPictureInPicture)===null||e===void 0?void 0:e.window):!1}function mQ(t,A){const e=A||window;let g=t.offsetTop,i=t.offsetLeft;const I=t.offsetWidth,C=t.offsetHeight,{hidden:o}=t,{display:a}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,g+=t.offsetTop,i+=t.offsetLeft;return g<e.pageYOffset+e.innerHeight&&i<e.pageXOffset+e.innerWidth&&g+C>e.pageYOffset&&i+I>e.pageXOffset&&!o&&a!=="none"}class wt extends At.EventEmitter{constructor(A,e,g,i){var I;super(),this.metadataMuted=!1,this.encryption=lg.NONE,this.log=Ae,this.handleMuted=()=>{this.emit(oA.Muted)},this.handleUnmuted=()=>{this.emit(oA.Unmuted)},this.log=lt((I=i==null?void 0:i.loggerName)!==null&&I!==void 0?I:vg.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=A,this.trackSid=e,this.trackName=g,this.source=AA.Source.Unknown}setTrack(A){this.track&&(this.track.off(oA.Muted,this.handleMuted),this.track.off(oA.Unmuted,this.handleUnmuted)),this.track=A,A&&(A.on(oA.Muted,this.handleMuted),A.on(oA.Unmuted,this.handleUnmuted))}get logContext(){var A;return Object.assign(Object.assign({},(A=this.loggerContextCb)===null||A===void 0?void 0:A.call(this)),WA(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==lg.NONE}get audioTrack(){if(It(this.track))return this.track}get videoTrack(){if(Zt(this.track))return this.track}updateInfo(A){this.trackSid=A.sid,this.trackName=A.name,this.source=AA.sourceFromProto(A.source),this.mimeType=A.mimeType,this.kind===AA.Kind.Video&&A.width>0&&(this.dimensions={width:A.width,height:A.height},this.simulcasted=A.simulcast),this.encryption=A.encryption,this.trackInfo=A,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:A}))}}(function(t){(function(A){A.Desired="desired",A.Subscribed="subscribed",A.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(A){A.Allowed="allowed",A.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(wt||(wt={}));class yQ extends wt{get isUpstreamPaused(){var A;return(A=this.track)===null||A===void 0?void 0:A.isUpstreamPaused}constructor(A,e,g,i){super(A,e.sid,e.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(oA.Ended)},this.handleCpuConstrained=()=>{this.track&&Zt(this.track)&&this.emit(oA.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(g)}setTrack(A){this.track&&(this.track.off(oA.Ended,this.handleTrackEnded),this.track.off(oA.CpuConstrained,this.handleCpuConstrained)),super.setTrack(A),A&&(A.on(oA.Ended,this.handleTrackEnded),A.on(oA.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 S(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.mute()})}unmute(){return S(this,void 0,void 0,function*(){var A;return(A=this.track)===null||A===void 0?void 0:A.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var A;yield(A=this.track)===null||A===void 0?void 0:A.resumeUpstream()})}getTrackFeatures(){var A;if(It(this.track)){const e=this.track.getSourceTrackSettings(),g=new Set;return e.autoGainControl&&g.add(je.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&g.add(je.TF_ECHO_CANCELLATION),e.noiseSuppression&&g.add(je.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&g.add(je.TF_STEREO),!((A=this.options)===null||A===void 0)&&A.dtx||g.add(je.TF_NO_DTX),this.track.enhancedNoiseCancellation&&g.add(je.TF_ENHANCED_NOISE_CANCELLATION),Array.from(g.values())}else return[]}}function oo(t,A){return S(this,void 0,void 0,function*(){t??(t={});let e=!1;const{audioProcessor:g,videoProcessor:i,optionsWithoutProcessor:I}=Ar(t);let C=I.audio,o=I.video;if(g&&typeof I.audio=="object"&&(I.audio.processor=g),i&&typeof I.video=="object"&&(I.video.processor=i),t.audio&&typeof I.audio=="object"&&typeof I.audio.deviceId=="string"){const s=I.audio.deviceId;I.audio.deviceId={exact:s},e=!0,C=Object.assign(Object.assign({},I.audio),{deviceId:{ideal:s}})}if(I.video&&typeof I.video=="object"&&typeof I.video.deviceId=="string"){const s=I.video.deviceId;I.video.deviceId={exact:s},e=!0,o=Object.assign(Object.assign({},I.video),{deviceId:{ideal:s}})}(I.audio===!0||typeof I.audio=="object"&&!I.audio.deviceId)&&(I.audio={deviceId:"default"}),I.video===!0?I.video={deviceId:"default"}:typeof I.video=="object"&&!I.video.deviceId&&(I.video.deviceId="default");const a=ZE(I,Br,Er),Q=CQ(a),n=navigator.mediaDevices.getUserMedia(Q);I.audio&&(We.userMediaPromiseMap.set("audioinput",n),n.catch(()=>We.userMediaPromiseMap.delete("audioinput"))),I.video&&(We.userMediaPromiseMap.set("videoinput",n),n.catch(()=>We.userMediaPromiseMap.delete("videoinput")));try{const s=yield n;return yield Promise.all(s.getTracks().map(B=>S(this,void 0,void 0,function*(){const E=B.kind==="audio";let d=E?a.audio:a.video;(typeof d=="boolean"||!d)&&(d={});let c;const h=E?Q.audio:Q.video;typeof h!="boolean"&&(c=h);const r=B.getSettings().deviceId;c!=null&&c.deviceId&&Xt(c.deviceId)!==r?c.deviceId=r:c||(c={deviceId:r});const f=gl(B,c,A);return f.kind===AA.Kind.Video?f.source=AA.Source.Camera:f.kind===AA.Kind.Audio&&(f.source=AA.Source.Microphone),f.mediaStream=s,It(f)&&g?yield f.setProcessor(g):Zt(f)&&i&&(yield f.setProcessor(i)),f})))}catch(s){if(!e)throw s;return oo(Object.assign(Object.assign({},t),{audio:C,video:o}),A)}})}function Nl(t){return S(this,void 0,void 0,function*(){return(yield oo({audio:!1,video:!0}))[0]})}function Sl(t){return S(this,void 0,void 0,function*(){return(yield oo({audio:!0,video:!1}))[0]})}var Ai;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(Ai||(Ai={}));function kl(t){switch(t){case HI.EXCELLENT:return Ai.Excellent;case HI.GOOD:return Ai.Good;case HI.POOR:return Ai.Poor;case HI.LOST:return Ai.Lost;default:return Ai.Unknown}}class Nr extends At.EventEmitter{get logContext(){var A,e;return Object.assign({},(e=(A=this.loggerOptions)===null||A===void 0?void 0:A.loggerContextCb)===null||e===void 0?void 0:e.call(A))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(A=>A.isEncrypted)}get isAgent(){var A;return((A=this.permissions)===null||A===void 0?void 0:A.agent)||this.kind===OI.AGENT}get isActive(){var A;return((A=this.participantInfo)===null||A===void 0?void 0:A.state)===Xi.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(A,e,g,i,I,C){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:OI.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ai.Unknown,this.log=Ae,this.log=lt((a=C==null?void 0:C.loggerName)!==null&&a!==void 0?a:vg.Participant),this.loggerOptions=C,this.setMaxListeners(100),this.sid=A,this.identity=e,this.name=g,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=I??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(A){for(const[,e]of this.trackPublications)if(e.source===A)return e}getTrackPublicationByName(A){for(const[,e]of this.trackPublications)if(e.trackName===A)return e}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new it,this.once(QA.Active,()=>{var A,e;(e=(A=this.activeFuture)===null||A===void 0?void 0:A.resolve)===null||e===void 0||e.call(A),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var A;const e=this.getTrackPublication(AA.Source.Camera);return!(!((A=e==null?void 0:e.isMuted)!==null&&A!==void 0)||A)}get isMicrophoneEnabled(){var A;const e=this.getTrackPublication(AA.Source.Microphone);return!(!((A=e==null?void 0:e.isMuted)!==null&&A!==void 0)||A)}get isScreenShareEnabled(){return!!this.getTrackPublication(AA.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(A){var e;return this.participantInfo&&this.participantInfo.sid===A.sid&&this.participantInfo.version>A.version?!1:(this.identity=A.identity,this.sid=A.sid,this._setName(A.name),this._setMetadata(A.metadata),this._setAttributes(A.attributes),A.state===Xi.ACTIVE&&((e=this.participantInfo)===null||e===void 0?void 0:e.state)!==Xi.ACTIVE&&this.emit(QA.Active),A.permission&&this.setPermissions(A.permission),this.participantInfo=A,!0)}_setMetadata(A){const e=this.metadata!==A,g=this.metadata;this.metadata=A,e&&this.emit(QA.ParticipantMetadataChanged,g)}_setName(A){const e=this.name!==A;this.name=A,e&&this.emit(QA.ParticipantNameChanged,A)}_setAttributes(A){const e=Nx(this.attributes,A);this._attributes=A,Object.keys(e).length>0&&this.emit(QA.AttributesChanged,e)}setPermissions(A){var e,g,i,I,C,o;const a=this.permissions,Q=A.canPublish!==((e=this.permissions)===null||e===void 0?void 0:e.canPublish)||A.canSubscribe!==((g=this.permissions)===null||g===void 0?void 0:g.canSubscribe)||A.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||A.hidden!==((I=this.permissions)===null||I===void 0?void 0:I.hidden)||A.recorder!==((C=this.permissions)===null||C===void 0?void 0:C.recorder)||A.canPublishSources.length!==this.permissions.canPublishSources.length||A.canPublishSources.some((n,s)=>{var B;return n!==((B=this.permissions)===null||B===void 0?void 0:B.canPublishSources[s])})||A.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=A,Q&&this.emit(QA.ParticipantPermissionsChanged,a),Q}setIsSpeaking(A){A!==this.isSpeaking&&(this.isSpeaking=A,A&&(this.lastSpokeAt=new Date),this.emit(QA.IsSpeakingChanged,A))}setConnectionQuality(A){const e=this._connectionQuality;this._connectionQuality=kl(A),e!==this._connectionQuality&&this.emit(QA.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var A,e;this.activeFuture&&((e=(A=this.activeFuture).reject)===null||e===void 0||e.call(A,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(A){this.audioContext=A,this.audioTrackPublications.forEach(e=>It(e.track)&&e.track.setAudioContext(A))}addTrackPublication(A){A.on(oA.Muted,()=>{this.emit(QA.TrackMuted,A)}),A.on(oA.Unmuted,()=>{this.emit(QA.TrackUnmuted,A)});const e=A;switch(e.track&&(e.track.sid=A.trackSid),this.trackPublications.set(A.trackSid,A),A.kind){case AA.Kind.Audio:this.audioTrackPublications.set(A.trackSid,A);break;case AA.Kind.Video:this.videoTrackPublications.set(A.trackSid,A);break}}}function Rl(t){var A,e,g;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new TB({participantIdentity:(A=t.participantIdentity)!==null&&A!==void 0?A:"",participantSid:(e=t.participantSid)!==null&&e!==void 0?e:"",allTracks:(g=t.allowAll)!==null&&g!==void 0?g:!1,trackSids:t.allowedTrackSids||[]})}class Gl extends Nr{constructor(A,e,g,i,I,C){super(A,e,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=lg.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new it)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,a,Q,n,s,B;this.reconnectFuture&&(this.reconnectFuture.promise.catch(E=>this.log.warn(E.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((n=(Q=this.signalConnectedFuture).reject)===null||n===void 0||n.call(Q,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(B=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||B===void 0||B.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,Q;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new it),(Q=(a=this.signalConnectedFuture).resolve)===null||Q===void 0||Q.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:Q,message:n}=o,s=this.pendingSignalRequests.get(a);s&&(Q!==ka.OK&&s.reject(new vE(n,Q)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,Q=null,n=null;a.value.case==="payload"?Q=a.value.value:a.value.case==="error"&&(n=Me.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,Q,n);break;case"rpcAck":let s=o.value.value;this.handleIncomingRpcAck(s.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(o=>Rl(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),WA(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),WA(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),WA(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.onTrackCpuConstrained=(o,a)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),WA(a))),this.emit(QA.LocalTrackCpuConstrained,o,a)},this.handleSubscribedQualityUpdate=o=>S(this,void 0,void 0,function*(){var a,Q,n,s,B;if(!(!((B=this.roomOptions)===null||B===void 0)&&B.dynacast))return;const E=this.videoTrackPublications.get(o.trackSid);if(!E){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!E.videoTrack)return;const d=yield E.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var c=!0,h=ft(d),r;r=yield h.next(),a=r.done,!a;c=!0){s=r.value,c=!1;const f=s;Cx(f)&&(this.log.debug("publish ".concat(f," for ").concat(E.videoTrack.sid),Object.assign(Object.assign({},this.logContext),WA(E))),yield this.publishAdditionalCodecForTrack(E.videoTrack,f,E.options))}}catch(f){Q={error:f}}finally{try{!c&&!a&&(n=h.return)&&(yield n.call(h))}finally{if(Q)throw Q.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>S(this,void 0,void 0,function*(){if(o.source===AA.Source.ScreenShare||o.source===AA.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),WA(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(_t(o)||zt(o))try{if(cg())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===AA.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),WA(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),WA(o))),_t(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),WA(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=g,this.roomOptions=i,this.setupEngine(g),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=I,this.roomOutgoingDataStreamManager=C}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==lg.NONE}getTrackPublication(A){const e=super.getTrackPublication(A);if(e)return e}getTrackPublicationByName(A){const e=super.getTrackPublicationByName(A);if(e)return e}setupEngine(A){var e;this.engine=A,this.engine.on(nA.RemoteMute,(g,i)=>{const I=this.trackPublications.get(g);!I||!I.track||(i?I.mute():I.unmute())}),!((e=this.signalConnectedFuture)===null||e===void 0)&&e.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(nA.Connected,this.handleReconnected).on(nA.SignalConnected,this.handleSignalConnected).on(nA.SignalRestarted,this.handleReconnected).on(nA.SignalResumed,this.handleReconnected).on(nA.Restarting,this.handleReconnecting).on(nA.Resuming,this.handleReconnecting).on(nA.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(nA.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(nA.Closing,this.handleClosing).on(nA.SignalRequestResponse,this.handleSignalRequestResponse).on(nA.DataPacketReceived,this.handleDataPacket)}setMetadata(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:A})})}setName(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:A})})}setAttributes(A){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:A})})}requestMetadataUpdate(A){return S(this,arguments,void 0,function(e){var g=this;let{metadata:i,name:I,attributes:C}=e;return function*(){return new Promise((o,a)=>S(g,void 0,void 0,function*(){var Q,n;try{let s=!1;const B=yield this.engine.client.sendUpdateLocalMetadata((Q=i??this.metadata)!==null&&Q!==void 0?Q:"",(n=I??this.name)!==null&&n!==void 0?n:"",C),E=performance.now();for(this.pendingSignalRequests.set(B,{resolve:o,reject:d=>{a(d),s=!0},values:{name:I,metadata:i,attributes:C}});performance.now()-E<5e3&&!s;){if((!I||this.name===I)&&(!i||this.metadata===i)&&(!C||Object.entries(C).every(d=>{let[c,h]=d;return this.attributes[c]===h||h===""&&!this.attributes[c]}))){this.pendingSignalRequests.delete(B),o();return}yield rg(50)}a(new vE("Request to update local metadata timed out","TimeoutError"))}catch(s){s instanceof Error&&a(s)}}))}()})}setCameraEnabled(A,e,g){return this.setTrackEnabled(AA.Source.Camera,A,e,g)}setMicrophoneEnabled(A,e,g){return this.setTrackEnabled(AA.Source.Microphone,A,e,g)}setScreenShareEnabled(A,e,g){return this.setTrackEnabled(AA.Source.ScreenShare,A,e,g)}setPermissions(A){const e=this.permissions,g=super.setPermissions(A);return g&&e&&this.emit(QA.ParticipantPermissionsChanged,e),g}setE2EEEnabled(A){return S(this,void 0,void 0,function*(){this.encryptionType=A?lg.GCM:lg.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(A,e,g,i){return S(this,void 0,void 0,function*(){var I,C;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:A,enabled:e})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(A);if(e)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(A)){const Q=yield this.waitForPendingPublicationOfSource(A);return Q||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A})),yield Q==null?void 0:Q.unmute(),Q}this.pendingPublishing.add(A);try{switch(A){case AA.Source.Camera:a=yield this.createTracks({video:(I=g)!==null&&I!==void 0?I:!0});break;case AA.Source.Microphone:a=yield this.createTracks({audio:(C=g)!==null&&C!==void 0?C:!0});break;case AA.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},g));break;default:throw new Dt(A)}}catch(Q){throw a==null||a.forEach(n=>{n.stop()}),Q instanceof Error&&this.emit(QA.MediaDevicesError,Q,oQ(A)),this.pendingPublishing.delete(A),Q}for(const Q of a){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),g);A===AA.Source.Microphone&&It(Q)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),Q.startPreConnectBuffer())}try{const Q=[];for(const s of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),WA(s))),Q.push(this.publishTrack(s,i));[o]=yield Promise.all(Q)}catch(Q){throw a==null||a.forEach(n=>{n.stop()}),Q}finally{this.pendingPublishing.delete(A)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(A)&&(o=yield this.waitForPendingPublicationOfSource(A),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:A}))),o&&o.track)if(A===AA.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(AA.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(AA.Source.Camera)||this.pendingPublishing.has(AA.Source.Microphone))){this.pendingPublishing.add(AA.Source.Camera),this.pendingPublishing.add(AA.Source.Microphone);try{const A=yield this.createTracks({audio:!0,video:!0});yield Promise.all(A.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(AA.Source.Camera),this.pendingPublishing.delete(AA.Source.Microphone)}}})}createTracks(A){return S(this,void 0,void 0,function*(){var e,g;A??(A={});const i=ZE(A,(e=this.roomOptions)===null||e===void 0?void 0:e.audioCaptureDefaults,(g=this.roomOptions)===null||g===void 0?void 0:g.videoCaptureDefaults);try{return(yield oo(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(It(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=AA.Source.Microphone,this.emit(QA.AudioStreamAcquired)),Zt(o)&&(this.cameraError=void 0,o.source=AA.Source.Camera),o))}catch(I){throw I instanceof Error&&(A.audio&&(this.microphoneError=I),A.video&&(this.cameraError=I)),I}})}createScreenTracks(A){return S(this,void 0,void 0,function*(){if(A===void 0&&(A={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ta("getDisplayMedia not supported");A.resolution===void 0&&!Bx()&&(A.resolution=ja.h1080fps30.resolution);const e=mx(A),g=yield navigator.mediaDevices.getDisplayMedia(e),i=g.getVideoTracks();if(i.length===0)throw new Dt("no video track found");const I=new Co(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});I.source=AA.Source.ScreenShare,A.contentHint&&(I.mediaStreamTrack.contentHint=A.contentHint);const C=[I];if(g.getAudioTracks().length>0){this.emit(QA.AudioStreamAcquired);const o=new Io(g.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=AA.Source.ScreenShareAudio,C.push(o)}return C})}publishTrack(A,e){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(A,e)})}publishOrRepublishTrack(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,Q,n;_t(g)&&g.setAudioContext(I.audioContext),yield(o=I.reconnectFuture)===null||o===void 0?void 0:o.promise,I.republishPromise&&!C&&(yield I.republishPromise),gI(g)&&I.pendingPublishPromises.has(g)&&(yield I.pendingPublishPromises.get(g));let s;if(g instanceof MediaStreamTrack)s=g.getConstraints();else{s=g.constraints;let r;switch(g.source){case AA.Source.Microphone:r="audioinput";break;case AA.Source.Camera:r="videoinput"}r&&I.activeDeviceMap.has(r)&&(s=Object.assign(Object.assign({},s),{deviceId:I.activeDeviceMap.get(r)}))}if(g instanceof MediaStreamTrack)switch(g.kind){case"audio":g=new Io(g,s,!0,I.audioContext,{loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});break;case"video":g=new Co(g,s,!0,{loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});break;default:throw new Dt("unsupported MediaStreamTrack kind ".concat(g.kind))}else g.updateLoggerOptions({loggerName:I.roomOptions.loggerName,loggerContextCb:()=>I.logContext});let B;if(I.trackPublications.forEach(r=>{r.track&&r.track===g&&(B=r)}),B)return I.log.warn("track has already been published, skipping",Object.assign(Object.assign({},I.logContext),WA(B))),B;const E="channelCount"in g.mediaStreamTrack.getSettings()&&g.mediaStreamTrack.getSettings().channelCount===2||g.mediaStreamTrack.getConstraints().channelCount===2,d=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:E;d&&(i||(i={}),i.dtx===void 0&&I.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},I.logContext),WA(g))),i.red===void 0&&I.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(Q=i.dtx)!==null&&Q!==void 0||(i.dtx=!1),(n=i.red)!==null&&n!==void 0||(i.red=!1));const c=Object.assign(Object.assign({},I.roomOptions.publishDefaults),i);!rx()&&I.roomOptions.e2ee&&(I.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},I.logContext)),c.simulcast=!1),c.source&&(g.source=c.source);const h=new Promise((r,f)=>S(I,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ye.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:WA(g)}));const _=setTimeout(()=>{f(new KE("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(_);const l=yield this.publish(g,c,d);r(l)}else try{const _=yield this.publish(g,c,d);r(_)}catch(_){f(_)}}catch(_){f(_)}}));I.pendingPublishPromises.set(g,h);try{return yield h}catch(r){throw r}finally{I.pendingPublishPromises.delete(g)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new it),this.signalConnectedFuture.promise}hasPermissionsToPublish(A){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),WA(A))),!1;const{canPublish:e,canPublishSources:g}=this.permissions;return e&&(g.length===0||g.map(i=>Sx(i)).includes(A.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),WA(A))),!1)}publish(A,e,g){return S(this,void 0,void 0,function*(){var i,I,C,o,a,Q,n,s,B,E;if(!this.hasPermissionsToPublish(A))throw new KE("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(x=>gI(A)&&x.source===A.source)&&A.source!==AA.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(A.source),Object.assign(Object.assign({},this.logContext),WA(A))),e.stopMicTrackOnMute&&It(A)&&(A.stopOnMute=!0),A.source===AA.Source.ScreenShare&&ui()&&(e.simulcast=!1),e.videoCodec==="av1"&&!Qx()&&(e.videoCodec=void 0),e.videoCodec==="vp9"&&!nx()&&(e.videoCodec=void 0),e.videoCodec===void 0&&(e.videoCodec=cQ),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(x=>e.videoCodec===AC(x.mime))||(e.videoCodec=AC(this.enabledPublishVideoCodecs[0].mime)));const c=e.videoCodec;A.on(oA.Muted,this.onTrackMuted),A.on(oA.Unmuted,this.onTrackUnmuted),A.on(oA.Ended,this.handleTrackEnded),A.on(oA.UpstreamPaused,this.onTrackUpstreamPaused),A.on(oA.UpstreamResumed,this.onTrackUpstreamResumed),A.on(oA.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const h=[],r=!(!((i=e.dtx)!==null&&i!==void 0)||i),f=A.getSourceTrackSettings();f.autoGainControl&&h.push(je.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&h.push(je.TF_ECHO_CANCELLATION),f.noiseSuppression&&h.push(je.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&h.push(je.TF_STEREO),r&&h.push(je.TF_NO_DTX),_t(A)&&A.hasPreConnectBuffer&&h.push(je.TF_PRECONNECT_BUFFER);const _=new ma({cid:A.mediaStreamTrack.id,name:e.name,type:AA.kindToProto(A.kind),muted:A.isMuted,source:AA.sourceToProto(A.source),disableDtx:r,encryption:this.encryptionType,stereo:g,disableRed:this.isE2EEEnabled||!(!((I=e.red)!==null&&I!==void 0)||I),stream:e==null?void 0:e.stream,backupCodecPolicy:e==null?void 0:e.backupCodecPolicy,audioFeatures:h});let l;if(A.kind===AA.Kind.Video){let x={width:0,height:0};try{x=yield A.waitForDimensions()}catch{const N=(o=(C=this.roomOptions.videoCaptureDefaults)===null||C===void 0?void 0:C.resolution)!==null&&o!==void 0?o:ZI.h720.resolution;x={width:N.width,height:N.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{dims:x}))}_.width=x.width,_.height=x.height,zt(A)&&(et(c)&&(A.source===AA.Source.ScreenShare&&(e.scalabilityMode="L1T3","contentHint"in A.mediaStreamTrack&&(A.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),WA(A))))),e.scalabilityMode=(a=e.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),_.simulcastCodecs=[new pa({codec:c,cid:A.mediaStreamTrack.id})],e.backupCodec===!0&&(e.backupCodec={codec:cQ}),e.backupCodec&&c!==e.backupCodec.codec&&_.encryption===lg.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),_.simulcastCodecs.push(new pa({codec:e.backupCodec.codec,cid:""})))),l=uQ(A.source===AA.Source.ScreenShare,_.width,_.height,e),_.layers=Dr(_.width,_.height,l,et(e.videoCodec))}else A.kind===AA.Kind.Audio&&(l=[{maxBitrate:(Q=e.audioPreset)===null||Q===void 0?void 0:Q.maxBitrate,priority:(s=(n=e.audioPreset)===null||n===void 0?void 0:n.priority)!==null&&s!==void 0?s:"high",networkPriority:(E=(B=e.audioPreset)===null||B===void 0?void 0:B.priority)!==null&&E!==void 0?E:"high"}]);if(!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const D=()=>S(this,void 0,void 0,function*(){var x,w,N;if(!this.engine.pcManager)throw new Pe("pcManager is not ready");if(A.sender=yield this.engine.createSender(A,e,l),this.emit(QA.LocalSenderCreated,A.sender,A),zt(A)&&((x=e.degradationPreference)!==null&&x!==void 0||(e.degradationPreference=Bl(A)),A.setDegradationPreference(e.degradationPreference)),l)if(ui()&&A.kind===AA.Kind.Audio){let U;for(const K of this.engine.pcManager.publisher.getTransceivers())if(K.sender===A.sender){U=K;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((w=l[0])===null||w===void 0)&&w.maxBitrate?l[0].maxBitrate/1e3:0})}else A.codec&&et(A.codec)&&(!((N=l[0])===null||N===void 0)&&N.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:_.cid,codec:A.codec,maxbr:l[0].maxBitrate/1e3});yield this.engine.negotiate()});let p;const y=new Promise((x,w)=>S(this,void 0,void 0,function*(){var N;try{p=yield this.engine.addTrack(_),x(p)}catch(U){A.sender&&(!((N=this.engine.pcManager)===null||N===void 0)&&N.publisher)&&(this.engine.pcManager.publisher.removeTrack(A.sender),yield this.engine.negotiate().catch(K=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{error:K}))})),w(U)}}));if(this.enabledPublishVideoCodecs.length>0)p=(yield Promise.all([y,D()]))[0];else{p=yield y;let x;if(p.codecs.forEach(w=>{x===void 0&&(x=w.mimeType)}),x&&A.kind===AA.Kind.Video){const w=AC(x);w!==c&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{codec:w})),e.videoCodec=w,l=uQ(A.source===AA.Source.ScreenShare,_.width,_.height,e))}yield D()}const k=new yQ(A.kind,p,A,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(oA.CpuConstrained,x=>this.onTrackCpuConstrained(x,k)),k.options=e,A.sid=p.sid,this.log.debug("publishing ".concat(A.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:l,trackInfo:p})),zt(A)?A.startMonitor(this.engine.client):_t(A)&&A.startMonitor(),this.addTrackPublication(k),this.emit(QA.LocalTrackPublished,k),_t(A)&&p.audioFeatures.includes(je.TF_PRECONNECT_BUFFER)){const x=A.getPreConnectBuffer(),w=A.getPreConnectBufferMimeType();this.on(QA.LocalTrackSubscribed,N=>{if(N.trackSid===p.sid){if(!A.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),WA(A))),A.stopPreConnectBuffer()}}),x&&new Promise((U,K)=>S(this,void 0,void 0,function*(){var P,j,H,O,z,xA;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),WA(A)));const vA=setTimeout(()=>{K(new Error("agent not active within 10 seconds"))},1e4),be=yield this.waitUntilActiveAgentPresent();clearTimeout(vA),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),WA(A)));const le=yield this.streamBytes({name:"preconnect-buffer",mimeType:w,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[be.identity],attributes:{trackId:k.trackSid,sampleRate:String((z=f.sampleRate)!==null&&z!==void 0?z:"48000"),channels:String((xA=f.channelCount)!==null&&xA!==void 0?xA:"1")}});try{for(var sA=!0,fA=ft(x),JA;JA=yield fA.next(),P=JA.done,!P;sA=!0){O=JA.value,sA=!1;const Z=O;yield le.write(Z)}}catch(Z){j={error:Z}}finally{try{!sA&&!P&&(H=fA.return)&&(yield H.call(fA))}finally{if(j)throw j.error}}yield le.close(),U()}catch(vA){K(vA)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),WA(A)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{error:U}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(A,e,g){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==lg.NONE)return;let I;if(this.trackPublications.forEach(E=>{E.track&&E.track===A&&(I=E)}),!I)throw new Dt("track is not published");if(!zt(A))throw new Dt("track is not a video track");const C=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),g),o=Ql(A,e,C);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),WA(A)));return}const a=A.addSimulcastTrack(e,o);if(!a)return;const Q=new ma({cid:a.mediaStreamTrack.id,type:AA.kindToProto(A.kind),muted:A.isMuted,source:AA.sourceToProto(A.source),sid:A.sid,simulcastCodecs:[{codec:C.videoCodec,cid:a.mediaStreamTrack.id}]});if(Q.layers=Dr(Q.width,Q.height,o),!this.engine||this.engine.isClosed)throw new Pe("cannot publish track when not connected");const n=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(A,a,C,o),yield this.engine.negotiate()}),B=(yield Promise.all([this.engine.addTrack(Q),n()]))[0];this.log.debug("published ".concat(e," for track ").concat(A.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:B}))})}unpublishTrack(A,e){return S(this,void 0,void 0,function*(){var g,i;if(gI(A)){const Q=this.pendingPublishPromises.get(A);Q&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),WA(A))),yield Q)}const I=this.getPublicationForTrack(A),C=I?WA(I):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),C)),!I||!I.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),C));return}A=I.track,A.off(oA.Muted,this.onTrackMuted),A.off(oA.Unmuted,this.onTrackUnmuted),A.off(oA.Ended,this.handleTrackEnded),A.off(oA.UpstreamPaused,this.onTrackUpstreamPaused),A.off(oA.UpstreamResumed,this.onTrackUpstreamResumed),A.off(oA.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),e===void 0&&(e=(i=(g=this.roomOptions)===null||g===void 0?void 0:g.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),e?A.stop():A.stopMonitor();let o=!1;const a=A.sender;if(A.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ge.FAILED&&a)try{for(const Q of this.engine.pcManager.publisher.getTransceivers())Q.sender===a&&(Q.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),zt(A)){for(const[,Q]of A.simulcastCodecs)Q.sender&&(this.engine.removeTrack(Q.sender)&&(o=!0),Q.sender=void 0);A.simulcastCodecs.clear()}}catch(Q){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),C),{error:Q}))}switch(this.trackPublications.delete(I.trackSid),I.kind){case AA.Kind.Audio:this.audioTrackPublications.delete(I.trackSid);break;case AA.Kind.Video:this.videoTrackPublications.delete(I.trackSid);break}return this.emit(QA.LocalTrackUnpublished,I),I.setTrack(void 0),o&&(yield this.engine.negotiate()),I})}unpublishTracks(A){return S(this,void 0,void 0,function*(){return(yield Promise.all(A.map(g=>this.unpublishTrack(g)))).filter(g=>!!g)})}republishAllTracks(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){g.republishPromise&&(yield g.republishPromise),g.republishPromise=new Promise((I,C)=>S(g,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(e&&(a.options=Object.assign(Object.assign({},a.options),e)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const Q=a.track;yield this.unpublishTrack(Q,!1),i&&!Q.isMuted&&Q.source!==AA.Source.ScreenShare&&Q.source!==AA.Source.ScreenShareAudio&&(_t(Q)||zt(Q))&&!Q.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield Q.restartTrack()),yield this.publishOrRepublishTrack(Q,a.options,!0)}))),I()}catch(o){C(o)}finally{this.republishPromise=void 0}})),yield g.republishPromise}()})}publishData(A){return S(this,arguments,void 0,function(e){var g=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const I=i.reliable?PA.RELIABLE:PA.LOSSY,C=i.destinationIdentities,o=i.topic,a=new Eg({kind:I,value:{case:"user",value:new uB({participantIdentity:g.identity,payload:e,destinationIdentities:C,topic:o})}});yield g.engine.sendDataPacket(a,I)}()})}publishDtmf(A,e){return S(this,void 0,void 0,function*(){const g=new Eg({kind:PA.RELIABLE,value:{case:"sipDtmf",value:new DB({code:A,digit:e})}});yield this.engine.sendDataPacket(g,PA.RELIABLE)})}sendChatMessage(A,e){return S(this,void 0,void 0,function*(){const g={id:crypto.randomUUID(),message:A,timestamp:Date.now(),attachedFiles:e==null?void 0:e.attachments},i=new Eg({value:{case:"chatMessage",value:new la(Object.assign(Object.assign({},g),{timestamp:Ne.parse(g.timestamp)}))}});return yield this.engine.sendDataPacket(i,PA.RELIABLE),this.emit(QA.ChatMessage,g),g})}editChatMessage(A,e){return S(this,void 0,void 0,function*(){const g=Object.assign(Object.assign({},e),{message:A,editTimestamp:Date.now()}),i=new Eg({value:{case:"chatMessage",value:new la(Object.assign(Object.assign({},g),{timestamp:Ne.parse(g.timestamp),editTimestamp:Ne.parse(g.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,PA.RELIABLE),this.emit(QA.ChatMessage,g),g})}sendText(A,e){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(A,e)})}streamText(A){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(A)})}sendFile(A,e){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(A,e)})}streamBytes(A){return S(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(A)})}performRpc(A){return S(this,arguments,void 0,function(e){var g=this;let{destinationIdentity:i,method:I,payload:C,responseTimeout:o=1e4}=e;return function*(){return new Promise((Q,n)=>S(g,void 0,void 0,function*(){var s,B,E,d;if(dQ(C)>rr){n(Me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((B=(s=this.engine.latestJoinResponse)===null||s===void 0?void 0:s.serverInfo)===null||B===void 0)&&B.version&&tt((d=(E=this.engine.latestJoinResponse)===null||E===void 0?void 0:E.serverInfo)===null||d===void 0?void 0:d.version,"1.8.0")<0){n(Me.builtIn("UNSUPPORTED_SERVER"));return}const c=crypto.randomUUID();yield this.publishRpcRequest(i,c,I,C,o-2e3);const h=setTimeout(()=>{this.pendingAcks.delete(c),n(Me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(c),clearTimeout(r)},2e3);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(h)},participantIdentity:i});const r=setTimeout(()=>{this.pendingResponses.delete(c),n(Me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(c,{resolve:(f,_)=>{clearTimeout(r),this.pendingAcks.has(c)&&(console.warn("RPC response received before ack",c),this.pendingAcks.delete(c),clearTimeout(h)),_?n(_):Q(f??"")},participantIdentity:i})}))}()})}registerRpcMethod(A,e){this.rpcHandlers.has(A)&&this.log.warn("you're overriding the RPC handler for method ".concat(A,", in the future this will throw an error")),this.rpcHandlers.set(A,e)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setTrackSubscriptionPermissions(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=e,this.allParticipantsAllowedToSubscribe=A,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(A){const e=this.pendingAcks.get(A);e?(e.resolve(),this.pendingAcks.delete(A)):console.error("Ack received for unexpected RPC request",A)}handleIncomingRpcResponse(A,e,g){const i=this.pendingResponses.get(A);i?(i.resolve(e,g),this.pendingResponses.delete(A)):console.error("Response received for unexpected RPC request",A)}publishRpcRequest(A,e,g,i,I){return S(this,void 0,void 0,function*(){const C=new Eg({destinationIdentities:[A],kind:PA.RELIABLE,value:{case:"rpcRequest",value:new _B({id:e,method:g,payload:i,responseTimeoutMs:I,version:1})}});yield this.engine.sendDataPacket(C,PA.RELIABLE)})}handleParticipantDisconnected(A){for(const[e,{participantIdentity:g}]of this.pendingAcks)g===A&&this.pendingAcks.delete(e);for(const[e,{participantIdentity:g,resolve:i}]of this.pendingResponses)g===A&&(i(null,Me.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(e))}setEnabledPublishCodecs(A){this.enabledPublishVideoCodecs=A.filter(e=>e.mime.split("/")[0].toLowerCase()==="video")}updateInfo(A){return super.updateInfo(A)?(A.tracks.forEach(e=>{var g,i;const I=this.trackPublications.get(e.sid);if(I){const C=I.isMuted||((i=(g=I.track)===null||g===void 0?void 0:g.isUpstreamPaused)!==null&&i!==void 0?i:!1);C!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),WA(I)),{mutedOnServer:C})),this.engine.client.sendMuteTrack(e.sid,C))}}),!0):!1}setActiveAgent(A){var e,g,i,I;this.firstActiveAgent=A,A&&!this.firstActiveAgent&&(this.firstActiveAgent=A),A?(g=(e=this.activeAgentFuture)===null||e===void 0?void 0:e.resolve)===null||g===void 0||g.call(e,A):(I=(i=this.activeAgentFuture)===null||i===void 0?void 0:i.reject)===null||I===void 0||I.call(i,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new it),this.activeAgentFuture.promise)}getPublicationForTrack(A){let e;return this.trackPublications.forEach(g=>{const i=g.track;i&&(A instanceof MediaStreamTrack?(_t(i)||zt(i))&&i.mediaStreamTrack===A&&(e=g):A===i&&(e=g))}),e}waitForPendingPublicationOfSource(A){return S(this,void 0,void 0,function*(){const g=Date.now();for(;Date.now()<g+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(I=>{let[C]=I;return C.source===A});if(i)return i[1];yield rg(20)}})}}class Ml extends wt{constructor(A,e,g,i){super(A,e.sid,e.name,i),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=I=>{this.setTrack(void 0),this.emit(oA.Ended,I)},this.handleVisibilityChange=I=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(I),this.logContext),this.visible=I,this.emitTrackUpdate()},this.handleVideoDimensionsChange=I=>{this.log.debug("adaptivestream video dimensions ".concat(I.width,"x").concat(I.height),this.logContext),this.videoDimensionsAdaptiveStream=I,this.emitTrackUpdate()},this.subscribed=g,this.updateInfo(e)}setSubscribed(A){const e=this.subscriptionStatus,g=this.permissionStatus;this.subscribed=A,A&&(this.allowed=!0);const i=new HC({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new yB({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oA.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(g)}get subscriptionStatus(){return this.subscribed===!1?wt.SubscriptionStatus.Unsubscribed:super.isSubscribed?wt.SubscriptionStatus.Subscribed:wt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?wt.PermissionStatus.Allowed:wt.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(A){!this.isManualOperationAllowed()||this.requestedDisabled===!A||(this.requestedDisabled=!A,this.emitTrackUpdate())}setVideoQuality(A){!this.isManualOperationAllowed()||this.requestedMaxQuality===A||(this.requestedMaxQuality=A,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(A){var e,g;this.isManualOperationAllowed()&&(((e=this.requestedVideoDimensions)===null||e===void 0?void 0:e.width)===A.width&&((g=this.requestedVideoDimensions)===null||g===void 0?void 0:g.height)===A.height||(iQ(this.track)&&(this.requestedVideoDimensions=A),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(A){this.isManualOperationAllowed()&&iQ(this.track)&&this.fps!==A&&(this.fps=A,this.emitTrackUpdate())}get videoQuality(){var A;return(A=this.requestedMaxQuality)!==null&&A!==void 0?A:ug.HIGH}setTrack(A){const e=this.subscriptionStatus,g=this.permissionStatus,i=this.track;i!==A&&(i&&(i.off(oA.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(oA.VisibilityChanged,this.handleVisibilityChange),i.off(oA.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(oA.Unsubscribed,i)),super.setTrack(A),A&&(A.sid=this.trackSid,A.on(oA.VideoDimensionsChanged,this.handleVideoDimensionsChange),A.on(oA.VisibilityChanged,this.handleVisibilityChange),A.on(oA.Ended,this.handleEnded),this.emit(oA.Subscribed,A)),this.emitPermissionUpdateIfChanged(g),this.emitSubscriptionUpdateIfChanged(e))}setAllowed(A){const e=this.subscriptionStatus,g=this.permissionStatus;this.allowed=A,this.emitPermissionUpdateIfChanged(g),this.emitSubscriptionUpdateIfChanged(e)}setSubscriptionError(A){this.emit(oA.SubscriptionFailed,A)}updateInfo(A){super.updateInfo(A);const e=this.metadataMuted;this.metadataMuted=A.muted,this.track?this.track.setMuted(A.muted):e!==A.muted&&this.emit(A.muted?oA.Muted:oA.Unmuted)}emitSubscriptionUpdateIfChanged(A){const e=this.subscriptionStatus;A!==e&&this.emit(oA.SubscriptionStatusChanged,e,A)}emitPermissionUpdateIfChanged(A){this.permissionStatus!==A&&this.emit(oA.SubscriptionPermissionChanged,this.permissionStatus,A)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return iQ(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const A=new LB({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===AA.Kind.Video){let e=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(e)er(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const g=kx(this.trackInfo,this.requestedMaxQuality);g&&er(this.videoDimensionsAdaptiveStream,g)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream;e?(A.width=Math.ceil(e.width),A.height=Math.ceil(e.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),A.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ug.HIGH})),A.quality=ug.HIGH)}this.emit(oA.UpdateSettings,A)}}class ao extends Nr{static fromParticipantInfo(A,e,g){return new ao(A,e.sid,e.identity,e.name,e.metadata,e.attributes,g,e.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(A,e,g,i,I,C,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:OI.STANDARD;super(e,g||"",i,I,C,o,a),this.signalClient=A,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(A){super.addTrackPublication(A),A.on(oA.UpdateSettings,e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),WA(A)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)}),A.on(oA.UpdateSubscription,e=>{e.participantTracks.forEach(g=>{g.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),A.on(oA.SubscriptionPermissionChanged,e=>{this.emit(QA.TrackSubscriptionPermissionChanged,A,e)}),A.on(oA.SubscriptionStatusChanged,e=>{this.emit(QA.TrackSubscriptionStatusChanged,A,e)}),A.on(oA.Subscribed,e=>{this.emit(QA.TrackSubscribed,e,A)}),A.on(oA.Unsubscribed,e=>{this.emit(QA.TrackUnsubscribed,e,A)}),A.on(oA.SubscriptionFailed,e=>{this.emit(QA.TrackSubscriptionFailed,A.trackSid,e)})}getTrackPublication(A){const e=super.getTrackPublication(A);if(e)return e}getTrackPublicationByName(A){const e=super.getTrackPublicationByName(A);if(e)return e}setVolume(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:AA.Source.Microphone;this.volumeMap.set(e,A);const g=this.getTrackPublication(e);g&&g.track&&g.track.setVolume(A)}getVolume(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:AA.Source.Microphone;const e=this.getTrackPublication(A);return e&&e.track?e.track.getVolume():this.volumeMap.get(A)}addSubscribedMediaTrack(A,e,g,i,I,C){let o=this.getTrackPublicationBySid(e);if(o||e.startsWith("TR")||this.trackPublications.forEach(n=>{!o&&A.kind===n.kind.toString()&&(o=n)}),!o){if(C===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:e})),this.emit(QA.TrackSubscriptionFailed,e);return}C===void 0&&(C=20),setTimeout(()=>{this.addSubscribedMediaTrack(A,e,g,i,I,C-1)},150);return}if(A.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),WA(o))),this.emit(QA.TrackSubscriptionFailed,e);return}const a=A.kind==="video";let Q;return a?Q=new yl(A,e,i,I):Q=new ml(A,e,i,this.audioContext,this.audioOutput),Q.source=o.source,Q.isMuted=o.isMuted,Q.setMediaStream(g),Q.start(),o.setTrack(Q),this.volumeMap.has(o.source)&&tQ(Q)&&It(Q)&&Q.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(A){return this.trackPublications.get(A)}updateInfo(A){if(!super.updateInfo(A))return!1;const e=new Map,g=new Map;return A.tracks.forEach(i=>{var I,C;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=AA.kindFromProto(i.type);if(!a)return;o=new Ml(a,i,(I=this.signalClient.connectOptions)===null||I===void 0?void 0:I.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(C=this.loggerOptions)===null||C===void 0?void 0:C.loggerName}),o.updateInfo(i),g.set(i.sid,o);const Q=Array.from(this.trackPublications.values()).find(n=>n.source===(o==null?void 0:o.source));Q&&o.source!==AA.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:WA(Q),newTrack:WA(o)})),this.addTrackPublication(o)}e.set(i.sid,o)}),this.trackPublications.forEach(i=>{e.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),WA(i))),this.unpublishTrack(i.trackSid,!0))}),g.forEach(i=>{this.emit(QA.TrackPublished,i)}),!0}unpublishTrack(A,e){const g=this.trackPublications.get(A);if(!g)return;const{track:i}=g;switch(i&&(i.stop(),g.setTrack(void 0)),this.trackPublications.delete(A),g.kind){case AA.Kind.Audio:this.audioTrackPublications.delete(A);break;case AA.Kind.Video:this.videoTrackPublications.delete(A);break}e&&this.emit(QA.TrackUnpublished,g)}setAudioOutput(A){return S(this,void 0,void 0,function*(){this.audioOutput=A;const e=[];this.audioTrackPublications.forEach(g=>{var i;It(g.track)&&tQ(g.track)&&e.push(g.track.setSinkId((i=A.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(e)})}emit(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:A,args:g})),super.emit(A,...g)}}var se;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(se||(se={}));const Fl=4*1e3;class II extends At.EventEmitter{constructor(A){var e,g,i,I;if(super(),e=this,this.state=se.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ae,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(C,o,a)=>S(this,void 0,void 0,function*(){var Q;if(!sx())throw gt()?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 n=yield this.disconnectLock.lock();if(this.state===se.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),n(),Promise.resolve();if(this.connectFuture)return n(),this.connectFuture.promise;this.setAndEmitConnectionState(se.Connecting),((Q=this.regionUrlProvider)===null||Q===void 0?void 0:Q.getServerUrl().toString())!==C&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),za(new URL(C))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new wQ(C,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(E=>{var d;(d=this.regionUrlProvider)===null||d===void 0||d.setServerReportedRegions(E)}).catch(E=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:E}))}));const s=(E,d,c)=>S(this,void 0,void 0,function*(){var h,r;this.abortController&&this.abortController.abort();const f=new AbortController;this.abortController=f,n==null||n();try{yield this.attemptConnection(c??C,o,a,f),this.abortController=void 0,E()}catch(_){if(this.regionUrlProvider&&_ instanceof ue&&_.reason!==ie.Cancelled&&_.reason!==ie.NotAllowed){let l=null;try{l=yield this.regionUrlProvider.getNextBestRegionUrl((h=this.abortController)===null||h===void 0?void 0:h.signal)}catch(D){if(D instanceof ue&&(D.status===401||D.reason===ie.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),d(D);return}}l&&!(!((r=this.abortController)===null||r===void 0)&&r.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(_.message,". Retrying with another region: ").concat(l),this.logContext),this.recreateEngine(),yield s(E,d,l)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,XE(_)),d(_))}else{let l=Lg.UNKNOWN_REASON;_ instanceof ue&&(l=XE(_)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,l),d(_)}}}),B=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new it((E,d)=>{s(E,d,B)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(C,o,a,Q,n,s)=>S(this,void 0,void 0,function*(){var B,E,d;const c=yield a.join(C,o,{autoSubscribe:Q.autoSubscribe,adaptiveStream:typeof n.adaptiveStream=="object"?!0:n.adaptiveStream,maxRetries:Q.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:Q.websocketTimeout},s.signal);let h=c.serverInfo;if(h||(h={version:c.serverVersion,region:c.serverRegion}),this.serverInfo=h,this.log.debug("connected to Livekit Server ".concat(Object.entries(h).map(r=>{let[f,_]=r;return"".concat(f,": ").concat(_)}).join(", ")),{room:(B=c.room)===null||B===void 0?void 0:B.name,roomSid:(E=c.room)===null||E===void 0?void 0:E.sid,identity:(d=c.participant)===null||d===void 0?void 0:d.identity}),!h.version)throw new Xd("unknown server version");return h.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),n.dynacast=!1),c}),this.applyJoinResponse=C=>{const o=C.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(C.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(C.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...C.otherParticipants]),C.room&&this.handleRoomUpdate(C.room)},this.attemptConnection=(C,o,a,Q)=>S(this,void 0,void 0,function*(){var n,s;this.state===se.Reconnecting||this.isResuming||!((n=this.engine)===null||n===void 0)&&n.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((s=this.regionUrlProvider)===null||s===void 0)&&s.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},hQ),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const B=yield this.connectSignal(C,o,this.engine,this.connOptions,this.options,Q);this.applyJoinResponse(B),this.setupLocalParticipantEvents(),this.emit(tA.SignalConnected)}catch(B){yield this.engine.close(),this.recreateEngine();const E=new ue("could not establish signal connection",ie.ServerUnreachable);throw B instanceof Error&&(E.message="".concat(E.message,": ").concat(B.message)),B instanceof ue&&(E.reason=B.reason,E.status=B.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:B})),E}if(Q.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ue("Connection attempt aborted",ie.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,Q)}catch(B){throw yield this.engine.close(),this.recreateEngine(),B}cg()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),cg()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(se.Connected),this.emit(tA.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var C=arguments.length,o=new Array(C),a=0;a<C;a++)o[a]=arguments[a];return S(e,[...o],void 0,function(){var Q=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var s,B,E,d;const c=yield Q.disconnectLock.lock();try{if(Q.state===se.Disconnected){Q.log.debug("already disconnected",Q.logContext);return}Q.log.info("disconnect from room",Object.assign({},Q.logContext)),(Q.state===se.Connecting||Q.state===se.Reconnecting||Q.isResuming)&&(Q.log.warn("abort connection attempt",Q.logContext),(s=Q.abortController)===null||s===void 0||s.abort(),(E=(B=Q.connectFuture)===null||B===void 0?void 0:B.reject)===null||E===void 0||E.call(B,new ue("Client initiated disconnect",ie.Cancelled)),Q.connectFuture=void 0),!((d=Q.engine)===null||d===void 0)&&d.client.isDisconnected||(yield Q.engine.client.sendLeave()),Q.engine&&(yield Q.engine.close()),Q.handleDisconnect(n,Lg.CLIENT_INITIATED),Q.engine=void 0}finally{c()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const C=[],o=fg();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let Q=document.getElementById(a);if(!Q){Q=document.createElement("audio"),Q.id=a,Q.autoplay=!0,Q.hidden=!0;const n=eQ();n.enabled=!0;const s=new MediaStream([n]);Q.srcObject=s,document.addEventListener("visibilitychange",()=>{Q&&(Q.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(Q),this.once(tA.Disconnected,()=>{Q==null||Q.remove(),Q=null})}C.push(Q)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(Q=>{Q.track&&Q.track.attachedElements.forEach(n=>{C.push(n)})})});try{yield Promise.all([this.acquireAudioContext(),...C.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const C=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var Q;(Q=a.track)===null||Q===void 0||Q.attachedElements.forEach(n=>{C.includes(n)||C.push(n)})});yield Promise.all(C.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const C of this.remoteParticipants.values())this.handleParticipantDisconnected(C.identity,C);this.setAndEmitConnectionState(se.Reconnecting)&&this.emit(tA.Reconnecting)},this.handleSignalRestarted=C=>S(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(C.serverRegion),Object.assign(Object.assign({},this.logContext),{region:C.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(C);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:C.serverRegion}))}catch{return}this.setAndEmitConnectionState(se.Connected),this.emit(tA.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=C=>{C.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let Q=this.remoteParticipants.get(o.identity);o.state===Xi.DISCONNECTED?this.handleParticipantDisconnected(o.identity,Q):Q=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=C=>{const o=[],a={};C.forEach(Q=>{if(a[Q.sid]=!0,Q.sid===this.localParticipant.sid)this.localParticipant.audioLevel=Q.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const n=this.getRemoteParticipantBySid(Q.sid);n&&(n.audioLevel=Q.level,n.setIsSpeaking(!0),o.push(n))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(Q=>{a[Q.sid]||(Q.audioLevel=0,Q.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(tA.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=C=>{const o=new Map;this.activeSpeakers.forEach(Q=>{const n=this.remoteParticipants.get(Q.identity);n&&n.sid!==Q.sid||o.set(Q.sid,Q)}),C.forEach(Q=>{let n=this.getRemoteParticipantBySid(Q.sid);Q.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=Q.level,n.setIsSpeaking(Q.active),Q.active?o.set(Q.sid,n):o.delete(Q.sid))});const a=Array.from(o.values());a.sort((Q,n)=>n.audioLevel-Q.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(tA.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=C=>{C.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const Q=a.getTrackPublicationBySid(o.trackSid);if(!Q||!Q.track)return;const n=AA.streamStateFromProto(o.state);Q.track.setStreamState(n),n!==Q.track.streamState&&(a.emit(QA.TrackStreamStateChanged,Q,Q.track.streamState),this.emitWhenConnected(tA.TrackStreamStateChanged,Q,Q.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=C=>{const o=this.getRemoteParticipantBySid(C.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(C.trackSid);a&&a.setAllowed(C.allowed)},this.handleSubscriptionError=C=>{const o=Array.from(this.remoteParticipants.values()).find(Q=>Q.trackPublications.has(C.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(C.trackSid);a&&a.setSubscriptionError(C.err)},this.handleDataPacket=C=>{const o=this.remoteParticipants.get(C.participantIdentity);if(C.value.case==="user")this.handleUserPacket(o,C.value.value,C.kind);else if(C.value.case==="transcription")this.handleTranscription(o,C.value.value);else if(C.value.case==="sipDtmf")this.handleSipDtmf(o,C.value.value);else if(C.value.case==="chatMessage")this.handleChatMessage(o,C.value.value);else if(C.value.case==="metrics")this.handleMetrics(C.value.value,o);else if(C.value.case==="streamHeader"||C.value.case==="streamChunk"||C.value.case==="streamTrailer")this.handleDataStream(C);else if(C.value.case==="rpcRequest"){const a=C.value.value;this.handleIncomingRpcRequest(C.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(C,o,a)=>{this.emit(tA.DataReceived,o.payload,C,a,o.topic),C==null||C.emit(QA.DataReceived,o.payload,a)},this.handleSipDtmf=(C,o)=>{this.emit(tA.SipDTMFReceived,o,C),C==null||C.emit(QA.SipDTMFReceived,o)},this.handleTranscription=(C,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),Q=a==null?void 0:a.trackPublications.get(o.trackId),n=fx(o,this.transcriptionReceivedTimes);Q==null||Q.emit(oA.TranscriptionReceived,n),a==null||a.emit(QA.TranscriptionReceived,n,Q),this.emit(tA.TranscriptionReceived,n,a,Q)},this.handleChatMessage=(C,o)=>{const a=ux(o);this.emit(tA.ChatMessage,a,C)},this.handleMetrics=(C,o)=>{this.emit(tA.MetricsReceived,C,o)},this.handleDataStream=C=>{this.incomingDataStreamManager.handleDataStreamPacket(C)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(tA.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=C=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:C})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(tA.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(tA.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(tA.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var C;((C=fg())===null||C===void 0?void 0:C.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(tA.MediaDevicesChanged)}),this.handleRoomUpdate=C=>{const o=this.roomInfo;this.roomInfo=C,o&&o.metadata!==C.metadata&&this.emitWhenConnected(tA.RoomMetadataChanged,C.metadata),(o==null?void 0:o.activeRecording)!==C.activeRecording&&this.emitWhenConnected(tA.RecordingStatusChanged,C.activeRecording)},this.handleConnectionQualityUpdate=C=>{C.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=C=>{this.emit(tA.ParticipantMetadataChanged,C,this.localParticipant)},this.onLocalParticipantNameChanged=C=>{this.emit(tA.ParticipantNameChanged,C,this.localParticipant)},this.onLocalAttributesChanged=C=>{this.emit(tA.ParticipantAttributesChanged,C,this.localParticipant)},this.onLocalTrackMuted=C=>{this.emit(tA.TrackMuted,C,this.localParticipant)},this.onLocalTrackUnmuted=C=>{this.emit(tA.TrackUnmuted,C,this.localParticipant)},this.onTrackProcessorUpdate=C=>{var o;(o=C==null?void 0:C.onPublish)===null||o===void 0||o.call(C,this)},this.onLocalTrackPublished=C=>S(this,void 0,void 0,function*(){var o,a,Q,n,s,B;(o=C.track)===null||o===void 0||o.on(oA.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=C.track)===null||a===void 0||a.on(oA.Restarted,this.onLocalTrackRestarted),(s=(n=(Q=C.track)===null||Q===void 0?void 0:Q.getProcessor())===null||n===void 0?void 0:n.onPublish)===null||s===void 0||s.call(n,this),this.emit(tA.LocalTrackPublished,C,this.localParticipant),_t(C.track)&&(yield C.track.checkForSilence())&&this.emit(tA.LocalAudioSilenceDetected,C);const E=yield(B=C.track)===null||B===void 0?void 0:B.getDeviceId(!1),d=oQ(C.source);d&&E&&E!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,E),this.emit(tA.ActiveDeviceChanged,d,E))}),this.onLocalTrackUnpublished=C=>{var o,a;(o=C.track)===null||o===void 0||o.off(oA.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=C.track)===null||a===void 0||a.off(oA.Restarted,this.onLocalTrackRestarted),this.emit(tA.LocalTrackUnpublished,C,this.localParticipant)},this.onLocalTrackRestarted=C=>S(this,void 0,void 0,function*(){const o=yield C.getDeviceId(!1),a=oQ(C.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(tA.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=C=>{this.emit(tA.ConnectionQualityChanged,C,this.localParticipant)},this.onMediaDevicesError=(C,o)=>{this.emit(tA.MediaDevicesError,C,o)},this.onLocalParticipantPermissionsChanged=C=>{this.emit(tA.ParticipantPermissionsChanged,C,this.localParticipant)},this.onLocalChatMessageSent=C=>{this.emit(tA.ChatMessage,C,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},jx),A),this.log=lt((g=this.options.loggerName)!==null&&g!==void 0?g:vg.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Br),A==null?void 0:A.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Er),A==null?void 0:A.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Vx),A==null?void 0:A.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Dl,this.outgoingDataStreamManager=new pl(this.engine,this.log),this.disconnectLock=new sg,this.localParticipant=new Gl("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Xt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Xt(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",Xt(this.options.audioOutput.deviceId)).catch(C=>this.log.warn("Could not set audio output: ".concat(C.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),cg()){const C=new AbortController;(I=navigator.mediaDevices)===null||I===void 0||I.addEventListener("devicechange",this.handleDeviceChange,{signal:C.signal}),II.cleanupRegistry&&II.cleanupRegistry.register(this,()=>{C.abort()})}}registerTextStreamHandler(A,e){return this.incomingDataStreamManager.registerTextStreamHandler(A,e)}unregisterTextStreamHandler(A){return this.incomingDataStreamManager.unregisterTextStreamHandler(A)}registerByteStreamHandler(A,e){return this.incomingDataStreamManager.registerByteStreamHandler(A,e)}unregisterByteStreamHandler(A){return this.incomingDataStreamManager.unregisterByteStreamHandler(A)}registerRpcMethod(A,e){if(this.rpcHandlers.has(A))throw Error("RPC handler already registered for method ".concat(A,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(A,e)}unregisterRpcMethod(A){this.rpcHandlers.delete(A)}setE2EEEnabled(A){return S(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(A)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(A,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var A;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Rx(this.options.e2ee),this.e2eeManager.on(jt.ParticipantEncryptionStatusChanged,(e,g)=>{_x(g)&&(this.isE2EEEnabled=e),this.emit(tA.ParticipantEncryptionStatusChanged,e,g)}),this.e2eeManager.on(jt.EncryptionError,e=>this.emit(tA.EncryptionError,e)),(A=this.e2eeManager)===null||A===void 0||A.setup(this))}get logContext(){var A;return{room:this.name,roomID:(A=this.roomInfo)===null||A===void 0?void 0:A.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.activeRecording)!==null&&e!==void 0?e:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===se.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((A,e)=>{const g=i=>{i.sid!==""&&(this.engine.off(nA.RoomUpdate,g),A(i.sid))};this.engine.on(nA.RoomUpdate,g),this.once(tA.Disconnected,()=>{this.engine.off(nA.RoomUpdate,g),e("Room disconnected before room server id was available")})})})}get name(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.name)!==null&&e!==void 0?e:""}get metadata(){var A;return(A=this.roomInfo)===null||A===void 0?void 0:A.metadata}get numParticipants(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.numParticipants)!==null&&e!==void 0?e:0}get numPublishers(){var A,e;return(e=(A=this.roomInfo)===null||A===void 0?void 0:A.numPublishers)!==null&&e!==void 0?e:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new hl(this.options),this.engine.on(nA.ParticipantUpdate,this.handleParticipantUpdates).on(nA.RoomUpdate,this.handleRoomUpdate).on(nA.SpeakersChanged,this.handleSpeakersChanged).on(nA.StreamStateChanged,this.handleStreamStateUpdate).on(nA.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(nA.SubscriptionError,this.handleSubscriptionError).on(nA.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(nA.MediaTrackAdded,(A,e,g)=>{this.onTrackAdded(A,e,g)}).on(nA.Disconnected,A=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,A)}).on(nA.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(nA.DataPacketReceived,this.handleDataPacket).on(nA.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(se.SignalReconnecting)&&this.emit(tA.SignalReconnecting)}).on(nA.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(se.Connected)&&this.emit(tA.Reconnected)}).on(nA.SignalResumed,()=>{this.bufferedEvents=[],(this.state===se.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(nA.Restarting,this.handleRestarting).on(nA.SignalRestarted,this.handleSignalRestarted).on(nA.Offline,()=>{this.setAndEmitConnectionState(se.Reconnecting)&&this.emit(tA.Reconnecting)}).on(nA.DCBufferStatusChanged,(A,e)=>{this.emit(tA.DCBufferStatusChanged,A,e)}).on(nA.LocalTrackSubscribed,A=>{const e=this.localParticipant.getTrackPublications().find(g=>{let{trackSid:i}=g;return i===A});if(!e){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(QA.LocalTrackSubscribed,e),this.emitWhenConnected(tA.LocalTrackSubscribed,e,this.localParticipant)}).on(nA.RoomMoved,A=>{this.log.debug("room moved",A),A.room&&this.handleRoomUpdate(A.room),this.remoteParticipants.forEach((e,g)=>{this.handleParticipantDisconnected(g,e)}),this.emit(tA.Moved,A.room.name),A.participant?this.handleParticipantUpdates([A.participant,...A.otherParticipants]):this.handleParticipantUpdates(A.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return We.getInstance().getDevices(A,e)}prepareConnection(A,e){return S(this,void 0,void 0,function*(){if(this.state===se.Disconnected){this.log.debug("prepareConnection to ".concat(A),this.logContext);try{if(za(new URL(A))&&e){this.regionUrlProvider=new wQ(A,e);const g=yield this.regionUrlProvider.getNextBestRegionUrl();g&&this.state===se.Disconnected&&(this.regionUrl=g,yield fetch(gQ(g),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(g),this.logContext))}else yield fetch(gQ(A),{method:"HEAD"})}catch(g){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:g}))}}})}getParticipantByIdentity(A){return this.localParticipant.identity===A?this.localParticipant:this.remoteParticipants.get(A)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(A,e){return S(this,void 0,void 0,function*(){let g=()=>{},i;switch(A){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new $g({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new $g({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new $g({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new $g({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":g=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new $g({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":g=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new $g({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new $g({scenario:{case:"switchCandidateProtocol",value:A==="force-tls"?2:1}}),g=()=>S(this,void 0,void 0,function*(){const I=this.engine.client.onLeave;I&&I(new PC({reason:Lg.CLIENT_INITIATED,action:zi.RECONNECT}))});break;case"subscriber-bandwidth":if(e===void 0||typeof e!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new $g({scenario:{case:"subscriberBandwidth",value:_i(e)}});break;case"leave-full-reconnect":i=new $g({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield g())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(A){return this.localParticipant.activeDeviceMap.get(A)}switchActiveDevice(A,e){return S(this,arguments,void 0,function(g,i){var I=this;let C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,Q,n,s,B,E;let d=!0,c=!1;const h=C?{exact:i}:i;if(g==="audioinput"){c=I.localParticipant.audioTrackPublications.size===0;const r=(o=I.getActiveDevice(g))!==null&&o!==void 0?o:I.options.audioCaptureDefaults.deviceId;I.options.audioCaptureDefaults.deviceId=h;const f=Array.from(I.localParticipant.audioTrackPublications.values()).filter(l=>l.source===AA.Source.Microphone);try{d=(yield Promise.all(f.map(l=>{var D;return(D=l.audioTrack)===null||D===void 0?void 0:D.setDeviceId(h)}))).every(l=>l===!0)}catch(l){throw I.options.audioCaptureDefaults.deviceId=r,l}const _=f.some(l=>{var D,p;return(p=(D=l.track)===null||D===void 0?void 0:D.isMuted)!==null&&p!==void 0?p:!1});d&&_&&(c=!0)}else if(g==="videoinput"){c=I.localParticipant.videoTrackPublications.size===0;const r=(a=I.getActiveDevice(g))!==null&&a!==void 0?a:I.options.videoCaptureDefaults.deviceId;I.options.videoCaptureDefaults.deviceId=h;const f=Array.from(I.localParticipant.videoTrackPublications.values()).filter(l=>l.source===AA.Source.Camera);try{d=(yield Promise.all(f.map(l=>{var D;return(D=l.videoTrack)===null||D===void 0?void 0:D.setDeviceId(h)}))).every(l=>l===!0)}catch(l){throw I.options.videoCaptureDefaults.deviceId=r,l}const _=f.some(l=>{var D,p;return(p=(D=l.track)===null||D===void 0?void 0:D.isMuted)!==null&&p!==void 0?p:!1});d&&_&&(c=!0)}else if(g==="audiooutput"){if(c=!0,!Za()&&!I.options.webAudioMix||I.options.webAudioMix&&I.audioContext&&!("setSinkId"in I.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");I.options.webAudioMix&&(i=(Q=yield We.getInstance().normalizeDeviceId("audiooutput",i))!==null&&Q!==void 0?Q:""),(n=(E=I.options).audioOutput)!==null&&n!==void 0||(E.audioOutput={});const r=(s=I.getActiveDevice(g))!==null&&s!==void 0?s:I.options.audioOutput.deviceId;I.options.audioOutput.deviceId=i;try{I.options.webAudioMix&&((B=I.audioContext)===null||B===void 0||B.setSinkId(i)),yield Promise.all(Array.from(I.remoteParticipants.values()).map(f=>f.setAudioOutput({deviceId:i})))}catch(f){throw I.options.audioOutput.deviceId=r,f}}return c&&(I.localParticipant.activeDeviceMap.set(g,i),I.emit(tA.ActiveDeviceChanged,g,i)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(QA.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(QA.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(QA.AttributesChanged,this.onLocalAttributesChanged).on(QA.TrackMuted,this.onLocalTrackMuted).on(QA.TrackUnmuted,this.onLocalTrackUnmuted).on(QA.LocalTrackPublished,this.onLocalTrackPublished).on(QA.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(QA.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(QA.MediaDevicesError,this.onMediaDevicesError).on(QA.AudioStreamAcquired,this.startAudio).on(QA.ChatMessage,this.onLocalChatMessageSent).on(QA.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var A;(A=this.engine)===null||A===void 0||A.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(A,e,g){if(this.state===se.Connecting||this.state===se.Reconnecting){const s=()=>{this.onTrackAdded(A,e,g),B()},B=()=>{this.off(tA.Reconnected,s),this.off(tA.Connected,s),this.off(tA.Disconnected,B)};this.once(tA.Reconnected,s),this.once(tA.Connected,s),this.once(tA.Disconnected,B);return}if(this.state===se.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(A.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=ax(e.id),I=i[0];let C=i[1],o=A.id;if(C&&C.startsWith("TR")&&(o=C),I===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(s=>s.sid===I);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(I),this.logContext);return}let Q;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?Q=this.options.adaptiveStream:Q={});const n=a.addSubscribedMediaTrack(A,o,e,g,Q);n!=null&&n.isEncrypted&&!this.e2eeManager&&this.emit(tA.EncryptionError,new Error("Encrypted ".concat(n.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1?arguments[1]:void 0;var g;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==se.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(I=>{i.unpublishTrack(I.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var I,C,o;i.track&&this.localParticipant.unpublishTrack(i.track,A),A?((I=i.track)===null||I===void 0||I.detach(),(C=i.track)===null||C===void 0||C.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(QA.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(QA.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(QA.AttributesChanged,this.onLocalAttributesChanged).off(QA.TrackMuted,this.onLocalTrackMuted).off(QA.TrackUnmuted,this.onLocalTrackUnmuted).off(QA.LocalTrackPublished,this.onLocalTrackPublished).off(QA.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(QA.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(QA.MediaDevicesError,this.onMediaDevicesError).off(QA.AudioStreamAcquired,this.startAudio).off(QA.ChatMessage,this.onLocalChatMessageSent).off(QA.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),cg()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(g=navigator.mediaDevices)===null||g===void 0||g.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(se.Disconnected),this.emit(tA.Disconnected,e)}}}handleParticipantDisconnected(A,e){var g;this.remoteParticipants.delete(A),e&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(A),e.trackPublications.forEach(i=>{e.unpublishTrack(i.trackSid,!0)}),this.emit(tA.ParticipantDisconnected,e),e.setDisconnected(),(g=this.localParticipant)===null||g===void 0||g.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(A,e,g,i,I,C){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(A,e),C!==1){yield this.engine.publishRpcResponse(A,e,null,Me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(g);if(!o){yield this.engine.publishRpcResponse(A,e,null,Me.builtIn("UNSUPPORTED_METHOD"));return}let a=null,Q=null;try{const n=yield o({requestId:e,callerIdentity:A,payload:i,responseTimeout:I});dQ(n)>rr?(a=Me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(g))):Q=n}catch(n){n instanceof Me?a=n:(console.warn("Uncaught error returned by RPC handler for ".concat(g,". Returning APPLICATION_ERROR instead."),n),a=Me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(A,e,Q,a)})}selectDefaultDevices(){return S(this,void 0,void 0,function*(){var A,e,g;const i=We.getInstance().previousDevices,I=yield We.getInstance().getDevices(void 0,!1),C=fg();if((C==null?void 0:C.name)==="Chrome"&&C.os!=="iOS")for(let a of I){const Q=i.find(n=>n.deviceId===a.deviceId);Q&&Q.label!==""&&Q.kind===a.kind&&Q.label!==a.label&&this.getActiveDevice(a.kind)==="default"&&this.emit(tA.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const Q=px(a),n=this.localParticipant.getTrackPublication(Q);if(n&&(!((A=n.track)===null||A===void 0)&&A.isUserProvided))continue;const s=I.filter(E=>E.kind===a),B=this.getActiveDevice(a);if(B===((e=i.filter(E=>E.kind===a)[0])===null||e===void 0?void 0:e.deviceId)&&s.length>0&&((g=s[0])===null||g===void 0?void 0:g.deviceId)!==B){yield this.switchActiveDevice(a,s[0].deviceId);continue}a==="audioinput"&&!zI()||a==="videoinput"||s.length>0&&!s.find(E=>E.deviceId===this.getActiveDevice(a))&&(a!=="audiooutput"||!zI())&&(yield this.switchActiveDevice(a,s[0].deviceId))}})}acquireAudioContext(){return S(this,void 0,void 0,function*(){var A,e;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(A=$E())!==null&&A!==void 0?A:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),rg(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const g=((e=this.audioContext)===null||e===void 0?void 0:e.state)==="running";g!==this.canPlaybackAudio&&(this.audioEnabled=g,this.emit(tA.AudioPlaybackStatusChanged,g))})}createParticipant(A,e){var g;let i;return e?i=ao.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new ao(this.engine.client,"",A,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((g=this.options.audioOutput)===null||g===void 0)&&g.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(I=>this.log.warn("Could not set audio output: ".concat(I.message),this.logContext)),i}getOrCreateParticipant(A,e){if(this.remoteParticipants.has(A)){const i=this.remoteParticipants.get(A);return e&&i.updateInfo(e)&&this.sidToIdentity.set(e.sid,e.identity),i}const g=this.createParticipant(A,e);return this.remoteParticipants.set(A,g),this.sidToIdentity.set(e.sid,e.identity),this.emitWhenConnected(tA.ParticipantConnected,g),g.on(QA.TrackPublished,i=>{this.emitWhenConnected(tA.TrackPublished,i,g)}).on(QA.TrackSubscribed,(i,I)=>{i.kind===AA.Kind.Audio?(i.on(oA.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(oA.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===AA.Kind.Video&&(i.on(oA.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(oA.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(tA.TrackSubscribed,i,I,g)}).on(QA.TrackUnpublished,i=>{this.emit(tA.TrackUnpublished,i,g)}).on(QA.TrackUnsubscribed,(i,I)=>{this.emit(tA.TrackUnsubscribed,i,I,g)}).on(QA.TrackMuted,i=>{this.emitWhenConnected(tA.TrackMuted,i,g)}).on(QA.TrackUnmuted,i=>{this.emitWhenConnected(tA.TrackUnmuted,i,g)}).on(QA.ParticipantMetadataChanged,i=>{this.emitWhenConnected(tA.ParticipantMetadataChanged,i,g)}).on(QA.ParticipantNameChanged,i=>{this.emitWhenConnected(tA.ParticipantNameChanged,i,g)}).on(QA.AttributesChanged,i=>{this.emitWhenConnected(tA.ParticipantAttributesChanged,i,g)}).on(QA.ConnectionQualityChanged,i=>{this.emitWhenConnected(tA.ConnectionQualityChanged,i,g)}).on(QA.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(tA.ParticipantPermissionsChanged,i,g)}).on(QA.TrackSubscriptionStatusChanged,(i,I)=>{this.emitWhenConnected(tA.TrackSubscriptionStatusChanged,i,I,g)}).on(QA.TrackSubscriptionFailed,(i,I)=>{this.emit(tA.TrackSubscriptionFailed,i,g,I)}).on(QA.TrackSubscriptionPermissionChanged,(i,I)=>{this.emitWhenConnected(tA.TrackSubscriptionPermissionChanged,i,I,g)}).on(QA.Active,()=>{this.emitWhenConnected(tA.ParticipantActive,g),g.kind===OI.AGENT&&this.localParticipant.setActiveAgent(g)}),e&&g.updateInfo(e),g}sendSyncState(){const A=Array.from(this.remoteParticipants.values()).reduce((g,i)=>(g.push(...i.getTrackPublications()),g),[]),e=this.localParticipant.getTrackPublications();this.engine.sendSyncState(A,e)}updateSubscriptions(){for(const A of this.remoteParticipants.values())for(const e of A.videoTrackPublications.values())e.isSubscribed&&Dx(e)&&e.emitTrackUpdate()}getRemoteParticipantBySid(A){const e=this.sidToIdentity.get(A);if(e)return this.remoteParticipants.get(e)}registerConnectionReconcile(){this.clearConnectionReconcile();let A=0;this.connectionReconcileInterval=ze.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(A++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:A,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),A>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Lg.STATE_MISMATCH))):A=0},Fl)}clearConnectionReconcile(){this.connectionReconcileInterval&&ze.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(A){return A===this.state?!1:(this.state=A,this.emit(tA.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(A=>{let[e,g]=A;this.emit(e,...g)}),this.bufferedEvents=[]}emitWhenConnected(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];if(this.state===se.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([A,g]);else if(this.state===se.Connected)return this.emit(A,...g);return!1}simulateParticipants(A){return S(this,void 0,void 0,function*(){var e,g;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},A.publish),I=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},A.participants);if(this.handleDisconnect(),this.roomInfo=new TC({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ne.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new di({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(tA.SignalConnected),this.emit(tA.Connected),this.setAndEmitConnectionState(se.Connected),i.video){const C=new yQ(AA.Kind.Video,new Zi({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO,name:"video-dummy"}),new Co(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:WE(160*((e=I.aspectRatios[0])!==null&&e!==void 0?e: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(QA.LocalTrackPublished,C)}if(i.audio){const C=new yQ(AA.Kind.Audio,new Zi({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO}),new Io(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:eQ(),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(QA.LocalTrackPublished,C)}for(let C=0;C<I.count-1;C+=1){let o=new di({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(C),state:Xi.ACTIVE,tracks:[],joinedAt:Ne.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(I.video){const Q=WE(160*((g=I.aspectRatios[C%I.aspectRatios.length])!==null&&g!==void 0?g:1),160,!1,!0),n=new Zi({source:ve.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO});a.addSubscribedMediaTrack(Q,n.sid,new MediaStream([Q]),new RTCRtpReceiver),o.tracks=[...o.tracks,n]}if(I.audio){const Q=eQ(),n=new Zi({source:ve.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ug.AUDIO});a.addSubscribedMediaTrack(Q,n.sid,new MediaStream([Q]),new RTCRtpReceiver),o.tracks=[...o.tracks,n]}a.updateInfo(o)}})}emit(A){for(var e=arguments.length,g=new Array(e>1?e-1:0),i=1;i<e;i++)g[i-1]=arguments[i];if(A!==tA.ActiveSpeakersChanged&&A!==tA.TranscriptionReceived){const I=Sr(g).filter(C=>C!==void 0);this.log.debug("room event ".concat(A),Object.assign(Object.assign({},this.logContext),{event:A,args:I}))}return super.emit(A,...g)}}II.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function Sr(t){return t.map(A=>{if(A)return Array.isArray(A)?Sr(A):typeof A=="object"?"logContext"in A?A.logContext:void 0:A})}var qg;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(qg||(qg={}));class ei extends At.EventEmitter{constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qg.IDLE,this.logs=[],this.options={},this.url=A,this.token=e,this.name=this.constructor.name,this.room=new II(g.roomOptions),this.connectOptions=g.connectOptions,this.options=g}run(A){return S(this,void 0,void 0,function*(){if(this.status!==qg.IDLE)throw Error("check is running already");this.setStatus(qg.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==qg.SKIPPED&&this.setStatus(this.isSuccess()?qg.SUCCESS:qg.FAILED),A&&A(),this.getInfo()})}isSuccess(){return!this.logs.some(A=>A.level==="error")}connect(A){return S(this,void 0,void 0,function*(){return this.room.state===se.Connected?this.room:(A||(A=this.url),yield this.room.connect(A,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==se.Disconnected&&(yield this.room.disconnect(),yield new Promise(A=>setTimeout(A,500)))})}skip(){this.setStatus(qg.SKIPPED)}switchProtocol(A){return S(this,void 0,void 0,function*(){let e=!1,g=!1;if(this.room.on(tA.Reconnecting,()=>{e=!0}),this.room.once(tA.Reconnected,()=>{g=!0}),this.room.simulateScenario("force-".concat(A)),yield new Promise(I=>setTimeout(I,1e3)),!e)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(g)return;yield rg(100)}throw new Error("Could not reconnect using ".concat(A," protocol after 10 seconds"))})}appendMessage(A){this.logs.push({level:"info",message:A}),this.emit("update",this.getInfo())}appendWarning(A){this.logs.push({level:"warning",message:A}),this.emit("update",this.getInfo())}appendError(A){this.logs.push({level:"error",message:A}),this.emit("update",this.getInfo())}setStatus(A){this.status=A,this.emit("update",this.getInfo())}get engine(){var A;return(A=this.room)===null||A===void 0?void 0:A.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Ul extends ei{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const A=new wQ(this.url,this.token);if(!A.isCloud()){this.skip();return}const e=[],g=new Set;for(let I=0;I<3;I++){const C=yield A.getNextBestRegionUrl();if(!C)break;if(g.has(C))continue;g.add(C);const o=yield this.checkCloudRegion(C);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),e.push(o)}e.sort((I,C)=>(I.duration-C.duration)*.5+(I.rtt-C.rtt)*.5);const i=e[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkCloudRegion(A){return S(this,void 0,void 0,function*(){var e,g;yield this.connect(A),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(e=this.room.serverInfo)===null||e===void 0?void 0:e.region;if(!i)throw new Error("Region not found");const I=yield this.room.localParticipant.streamText({topic:"test"}),C=1e3,a=1e6/C,Q="A".repeat(C),n=Date.now();for(let d=0;d<a;d++)yield I.write(Q);yield I.close();const s=Date.now(),B=yield(g=this.room.engine.pcManager)===null||g===void 0?void 0:g.publisher.getStats(),E={region:i,rtt:1e4,duration:s-n};return B==null||B.forEach(d=>{d.type==="candidate-pair"&&d.nominated&&(E.rtt=d.currentRoundTripTime*1e3)}),yield this.disconnect(),E})}}const bQ=1e4;class Ll extends ei{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const A=yield this.checkConnectionProtocol("udp"),e=yield this.checkConnectionProtocol("tcp");this.bestStats=A,A.qualityLimitationDurations.bandwidth-e.qualityLimitationDurations.bandwidth>.5||(A.packetsLost-e.packetsLost)/A.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=e):this.appendMessage("best connection quality via udp");const g=this.bestStats;this.appendMessage("upstream bitrate: ".concat((g.bitrateTotal/g.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((g.rttTotal/g.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((g.jitterTotal/g.count*1e3).toFixed(2)," ms")),g.packetsLost>0&&this.appendWarning("packets lost: ".concat((g.packetsLost/g.packetsSent*100).toFixed(2),"%")),g.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((g.qualityLimitationDurations.bandwidth/(bQ/1e3)*100).toFixed(2),"%")),g.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((g.qualityLimitationDurations.cpu/(bQ/1e3)*100).toFixed(2),"%"))})}getInfo(){const A=super.getInfo();return A.data=this.bestStats,A}checkConnectionProtocol(A){return S(this,void 0,void 0,function*(){yield this.connect(),A==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const e=document.createElement("canvas");e.width=1280,e.height=720;const g=e.getContext("2d");if(!g)throw new Error("Could not get canvas context");let i=0;const I=()=>{i=(i+1)%360,g.fillStyle="hsl(".concat(i,", 100%, 50%)"),g.fillRect(0,0,e.width,e.height),requestAnimationFrame(I)};I();const o=e.captureStream(30).getVideoTracks()[0],Q=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,n={protocol:A,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},s=setInterval(()=>S(this,void 0,void 0,function*(){const B=yield Q.getRTCStatsReport();B==null||B.forEach(E=>{E.type==="outbound-rtp"?(n.packetsSent=E.packetsSent,n.qualityLimitationDurations=E.qualityLimitationDurations,n.bitrateTotal+=E.targetBitrate,n.count++):E.type==="remote-inbound-rtp"&&(n.packetsLost=E.packetsLost,n.rttTotal+=E.roundTripTime,n.jitterTotal+=E.jitter)})}),1e3);return yield new Promise(B=>setTimeout(B,bQ)),clearInterval(s),o.stop(),e.remove(),yield this.disconnect(),n})}}class Kl extends ei{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect(),g=yield Sl();if(yield zE(g,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),e.localParticipant.publishTrack(g),yield new Promise(o=>setTimeout(o,3e3));const I=yield(A=g.sender)===null||A===void 0?void 0:A.getStats();if(!I)throw new Error("Could not get RTCStats");let C=0;if(I.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(C=o.packetsSent)}),C===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(C," audio packets"))})}}class vl extends ei{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect(),g=yield Nl();yield this.checkForVideo(g.mediaStreamTrack),e.localParticipant.publishTrack(g),yield new Promise(C=>setTimeout(C,5e3));const i=yield(A=g.sender)===null||A===void 0?void 0:A.getStats();if(!i)throw new Error("Could not get RTCStats");let I=0;if(i.forEach(C=>{C.type==="outbound-rtp"&&(C.kind==="video"||!C.kind&&C.mediaType==="video")&&(I+=C.packetsSent)}),I===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(I," video packets"))})}checkForVideo(A){return S(this,void 0,void 0,function*(){const e=new MediaStream;e.addTrack(A.clone());const g=document.createElement("video");g.srcObject=e,g.muted=!0,yield new Promise(i=>{g.onplay=()=>{setTimeout(()=>{var I,C,o,a;const Q=document.createElement("canvas"),n=A.getSettings(),s=(C=(I=n.width)!==null&&I!==void 0?I:g.videoWidth)!==null&&C!==void 0?C:1280,B=(a=(o=n.height)!==null&&o!==void 0?o:g.videoHeight)!==null&&a!==void 0?a:720;Q.width=s,Q.height=B;const E=Q.getContext("2d");E.drawImage(g,0,0);const c=E.getImageData(0,0,Q.width,Q.height).data;let h=!0;for(let r=0;r<c.length;r+=4)if(c[r]!==0||c[r+1]!==0||c[r+2]!==0){h=!1;break}h?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},g.play()}),e.getTracks().forEach(i=>i.stop()),g.remove()})}}class Jl extends ei{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var A;const e=yield this.connect();let g=!1,i=!1,I;const C=new Promise(Q=>{setTimeout(Q,5e3),I=Q}),o=()=>{g=!0};e.on(tA.SignalReconnecting,o).on(tA.Reconnecting,o).on(tA.Reconnected,()=>{i=!0,I(!0)}),(A=e.engine.client.ws)===null||A===void 0||A.close();const a=e.engine.client.onClose;if(a&&a(""),yield C,g){if(!i||e.state!==se.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 Yl extends ei{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var A,e;const g=new QQ,i=yield g.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let I=!1,C=!1,o=!1;for(let a of i.iceServers)for(let Q of a.urls)Q.startsWith("turn:")?(C=!0,o=!0):Q.startsWith("turns:")&&(C=!0,o=!0,I=!0),Q.startsWith("stun:")&&(o=!0);o?C&&!I&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield g.close(),!((e=(A=this.connectOptions)===null||A===void 0?void 0:A.rtcConfig)===null||e===void 0)&&e.iceServers||C?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class Tl extends ei{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let A=!1,e=!1;this.room.on(tA.SignalConnected,()=>{const g=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,I)=>{if(i.candidate){const C=new RTCIceCandidate(i);let o="".concat(C.protocol," ").concat(C.address,":").concat(C.port," ").concat(C.type);C.address&&(ql(C.address)?o+=" (private)":C.protocol==="tcp"&&C.tcpType==="passive"?(A=!0,o+=" (passive)"):C.protocol==="udp"&&(e=!0)),this.appendMessage(o)}g&&g(i,I)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),Ae.info("now the room is connected")}catch(g){throw this.appendWarning("ports need to be open on firewall in order to connect."),g}A||this.appendWarning("Server is not configured for ICE/TCP"),e||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function ql(t){const A=t.split(".");if(A.length===4){if(A[0]==="10")return!0;if(A[0]==="192"&&A[1]==="168")return!0;if(A[0]==="172"){const e=parseInt(A[1],10);if(e>=16&&e<=31)return!0}}return!1}class Hl extends ei{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var A,e,g;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new QQ;const I=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(I.serverVersion,".")),((A=I.serverInfo)===null||A===void 0?void 0:A.edition)===NB.Cloud&&(!((e=I.serverInfo)===null||e===void 0)&&e.region)&&this.appendMessage("LiveKit Cloud: ".concat((g=I.serverInfo)===null||g===void 0?void 0:g.region)),yield i.close()})}}class rp extends At.EventEmitter{constructor(A,e){let g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=A,this.token=e,this.options=g}getNextCheckId(){const A=this.checkResults.size;return this.checkResults.set(A,{logs:[],status:qg.IDLE,name:"",description:""}),A}updateCheck(A,e){this.checkResults.set(A,e),this.emit("checkUpdate",A,e)}isSuccess(){return Array.from(this.checkResults.values()).every(A=>A.status!==qg.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(A){return S(this,void 0,void 0,function*(){const e=this.getNextCheckId(),g=new A(this.url,this.token,this.options),i=C=>{this.updateCheck(e,C)};g.on("update",i);const I=yield g.run();return g.off("update",i),I})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Hl)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Tl)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Yl)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Jl)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Kl)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(vl)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const A=yield this.createAndRunCheck(Ll);if(A.data&&"protocol"in A.data){const e=A.data;this.options.protocol=e.protocol}return A})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Ul)})}}var Pl=Object.defineProperty,Ol=(t,A,e)=>A in t?Pl(t,A,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[A]=e,pt=(t,A,e)=>(Ol(t,typeof A!="symbol"?A+"":A,e),e),NQ=(t,A,e)=>{if(!A.has(t))throw TypeError("Cannot "+e)},XA=(t,A,e)=>(NQ(t,A,"read from private field"),e?e.call(t):A.get(t)),mt=(t,A,e)=>{if(A.has(t))throw TypeError("Cannot add the same private member more than once");A instanceof WeakSet?A.add(t):A.set(t,e)},Ng=(t,A,e,g)=>(NQ(t,A,"write to private field"),A.set(t,e),e),kr=(t,A,e)=>(NQ(t,A,"access private method"),e);function Qo(){const t=[`
|
|
85
85
|
<div>`,"LOG_INPUT_AUDIO","ak5370","jbl xtreme","j5create meeting mic","disposing Krisp filter","1374rMsVjx","AudioFilterNode","_free","promedia 2.0","_inputData","cp700","map","jbl charge","BYTES_PER_ELEMENT","ready","fmt ","collectFrom","majority rs1","thronmax mdrill ","bluetooth soundbar","startedAt","ugreen-40758e","fantech leviosa","edifier s880","webcam","razer nommo chroma","enumerateDevices","srs-xb43","usb/xlr dynamic microphone","responseURL","277218WfDGdn","STATE","logic sp2",'"><source src="',"dell slim soundbar sb522a","models","live microphone","audioContext","AudioFilterNode:dispose","attachShadow","SUPPORTED_INBOUND_SAMPLE_RATES","akg s30","jabra speak ","logPort","dataCache","yas-108 yamaha","avantree saturn pro","impulse","baseLatency","_outputData","zv-e10","secondsCounterInterval","logitech z337","lifecam","jbl clip ","fifine k658d microphone","__esModule","clientY","runtimeAllowedDevices","buffer_overflow","trust gxt 232 microphone","hd 450bt","disable","yoyo","inboundModels","toISOString","edifier g2000","418924BhpHNI","INVALID_AUDIO_CONTEXT","AudioFiletrNode:constructor","ue boom","innerHTML","setUint32","reaxt omni-1.0 pair","moman em","from","redcam rc-250","absolute","usb lavalier microphone","3Prtkcb","send toggle NC message","paths","charCodeAt","isFloat","info","join","anua mic cm 900","hk esquire mini","BVC:isCompatible","elgato wave","kilburn ii","INVALID_ASSET_URL","error","button","ModelLoader","template","BUFFER_OVERFLOW_MS","dm-40bt","Logger","WORKER_URL","logitech usb speaker","uc40m audio","INIT_WASM_PROCESSOR","hd 458bt","woburn speaker",`</div>
|
|
86
86
|
<details>
|
|
87
87
|
<summary>Logs</summary>
|
|
@@ -144,15 +144,15 @@ a=extmap-allow-mixed`)!==-1){const I=i.sdp.split(`
|
|
|
144
144
|
</div>
|
|
145
145
|
</div>
|
|
146
146
|
`,this[o(512)]({mode:o(726)}),(C=this[o(453)])==null||C[o(364)](a[o(737)][o(885)](!0))}[g(778)](){var C,o;const a=g;let Q=0,n=0,s=0,B=0;this[a(861)][a(649)]=a(550),this[a(861)].top=a(582),this[a(861)].right=a(582),this[a(715)]=E=>{const d=a;s=E[d(602)],B=E[d(530)],document[d(581)]=()=>{const c=d;document[c(581)]=null,document[c(880)]=null},document[d(880)]=c=>{const h=d;c.preventDefault(),Q=s-c[h(602)],n=B-c.clientY,s=c[h(602)],B=c.clientY,this.style[h(609)]=this.offsetTop-n+"px",this.style[h(626)]=this.offsetLeft-Q+"px"}},(o=(C=this[a(453)])==null?void 0:C[a(636)](a(566)))==null||o[a(643)](a(948),()=>i[a(571)][a(718)]())}}):i[g(571)][g(675)](g(840))},967:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(571)]=void 0;const i=e(687),I=e(67);A.Logger=new class{constructor(){const C=g;this.logs="",this.threadName=C(714),this[C(374)]=[],this[C(661)]=!1;let o=C(714);C(441)!=typeof WorkerGlobalScope?o=C(791):typeof AudioWorkletProcessor<"u"&&(o=C(775)),this[C(347)]=o}setOptions(C=!1){this.debugLogs=C}[g(877)](C){const o=g;this[o(516)]=C}[g(557)](...C){const o=g;this.debugLogs&&(this[o(786)]("I",C[o(558)](" ")),console[o(557)](o(376),...C))}[g(675)](...C){const o=g;this[o(661)]&&this[o(786)]("W",C.join(" ")),console[o(557)](o(376),...C)}[g(565)](...C){const o=g;this[o(661)]&&this[o(786)]("E",C.join(" ")),console.error(o(376),...C)}[g(695)](...C){const o=g;this[o(661)]&&(this[o(786)]("I",C[o(558)](" ")),console[o(695)]("KrispSDK -",...C))}[g(346)](C){const o=g;this.logAudio(o(473),C)}logAudioOutputSamples(C){const o=g;this[o(592)](o(600),C)}[g(489)](C,o){const a=g,Q={channel:new MessageChannel,recorder:void 0,startedAt:new Date,options:o};C instanceof MessagePort&&(Q[a(385)]=new I.DebugRecorder(o.sampleRate)),C instanceof Window?this[a(516)]=Q.channel[a(468)]:C[a(732)]({event:a(846),data:void 0},[Q[a(902)][a(468)]]),Q[a(902)].port1.addEventListener(a(755),n=>{var s,B;const E=a;E(420)==typeof n[E(648)]?this.logs+=n[E(648)]:Q[E(385)]&&((s=n[E(648)])==null?void 0:s.event)==="LOG_INPUT_AUDIO"?Q[E(385)][E(340)](n[E(648)][E(648)]):Q[E(385)]&&E(600)===((B=n[E(648)])==null?void 0:B[E(711)])&&Q.recorder[E(579)](n[E(648)][E(648)])}),this[a(374)][a(784)](Q),Q[a(902)][a(819)][a(438)]()}async[g(718)](){const C=g;try{const o=[];for(let Q in this[C(374)]){const n=this[C(374)][Q];if(n[C(385)]){const{input:s,output:B}=n[C(385)][C(663)]();o.push(C(665)+n[C(493)]+C(625)+Q+'"><source src="'+await(0,i[C(360)])(s)+C(449)+Q+C(506)+await(0,i[C(360)])(B)+C(833))}}const a=C(472)+o+C(578)+this[C(417)]+C(350);return(0,i.downloadBlob)(C(713)+new Date()[C(538)]()+".html",new Blob([a],{type:C(741)})),!0}catch{return console[C(565)](C(660)),!1}}[g(592)](C,o){const a=g;if(this.debugLogs&&this[a(516)]){const Q=new Float32Array(o.length);Q[a(676)](o,0),this[a(516)].postMessage({event:C,data:Q},[Q[a(721)]])}}postLog(C,o){const a=g,Q="["+new Date().toLocaleString()+"]["+this[a(347)]+"]["+C+a(886)+o+`
|
|
147
|
-
`;if(!this.logPort)return console[a(565)]("KrispSDK -",a(635),Q);this.logPort[a(732)](Q)}}},851:(t,A)=>{const e=Se;Object.defineProperty(A,"__esModule",{value:!0}),A[e(567)]=void 0,A[e(567)]=class{constructor(g={}){const i=e;this[i(554)]=g,this.dataCache={}}static async preload(g){const i=e,I=typeof g=="string"?g:g.url;return fetch(I,{cache:i(603)})}addPath(g,i){const I=e;this[I(554)][g]=i}removePath(g){const i=e;this[i(554)][g]&&(this.unloadModel(g),delete this[i(554)][g])}[e(831)](g){const i=e;if(!this[i(554)][g])throw new Error("Krisp SDK - Please add model path before loading");return this[i(517)][g]?this[i(517)][g]:new Promise((I,C)=>{const o=i;this[o(368)](this[o(554)][g],a=>{const Q=o;this[Q(517)][g]=a,I(a)},C)})}async[e(875)](g,i){const I=e;try{const C=await this.loadModel(i),o=new Uint8Array(C),a=g[I(688)](o[I(422)]);return g[I(865)][I(742)](a,a+o[I(422)])[I(676)](o),{bufferAddress:a,bufferLength:o[I(422)]}}catch(C){throw new Error(I(430)+C)}}[e(628)](g,i){g[e(480)](i)}[e(426)](g){this[e(517)][g]&&delete this.dataCache[g]}[e(368)](g,i,I){const C=e;var o=new XMLHttpRequest;o[C(726)]("GET",g,!0),o[C(817)]=C(858),o[C(633)]=function(){I("Network error during model loading")},o[C(731)]=function(){const a=C;o[a(434)]==200||o[a(434)]==304||o[a(434)]==206||o[a(434)]==0&&o[a(679)]?i(o[a(679)]):I(o.statusText+" : "+o[a(502)])},o[C(357)](null)}[e(799)](){const g=e;this.dataCache={},this[g(554)]={}}}},785:(t,A,e)=>{const g=Se;Object[g(815)](A,"__esModule",{value:!0}),A.SharedRingBuffer=void 0;const i=e(967),I={READ_INDEX:0,WRITE_INDEX:1};class C{constructor(a,Q=1){const n=g;this._channelData=[],this[n(457)]=Q,this[n(751)]=new Uint32Array(new SharedArrayBuffer(Object[n(881)](I)[n(915)]*Uint32Array[n(486)])),this._bufferLength=a+1;for(let s=0;s<Q;s++)this[n(690)].push(new Float32Array(new SharedArrayBuffer(this[n(896)]*Float32Array[n(486)])))}static[g(548)](a){return Object[g(634)](a,C.prototype)}push(a,Q){const n=g,s=Atomics[n(829)](this[n(751)],I[n(641)]),B=Atomics[n(829)](this._state,I[n(373)]);if(this._getAvailableWrite(s,B)<Q)return!1;let E=B+Q;if(this[n(896)]<E){E-=this[n(896)];for(let d=0;d<this[n(457)];d++){const c=this._channelData[d][n(742)](B),h=this[n(690)][d][n(742)](0,E);c[n(676)](a[d][n(742)](0,c[n(915)])),h[n(676)](a[d][n(742)](c[n(915)]))}}else{for(let d=0;d<this[n(457)];d++)this[n(690)][d].subarray(B,E)[n(676)](a[d].subarray(0,Q));E===this[n(896)]&&(E=0)}return Atomics.store(this[n(751)],I.WRITE_INDEX,E),!0}pull(a,Q){const n=g,s=Atomics[n(829)](this._state,I[n(641)]),B=Atomics[n(829)](this[n(751)],I[n(373)]);if(this._getAvailableRead(s,B)<Q)return!1;let E=s+Q;if(this[n(896)]<E){E-=this._bufferLength;for(let d=0;d<this[n(457)];d++){const c=this[n(690)][d][n(742)](s),h=this[n(690)][d][n(742)](0,E);a[d].set(c),a[d].set(h,c[n(915)])}}else{for(let d=0;d<this._channelCount;++d)a[d][n(676)](this[n(690)][d][n(742)](s,E));E===this._bufferLength&&(E=0)}return Atomics[n(431)](this[n(751)],I[n(641)],E),!0}[g(708)](){const a=g,Q=Atomics[a(829)](this[a(751)],I[a(641)]),n=Atomics.load(this[a(751)],I[a(373)]);i[a(571)][a(695)](this,{availableRead:this[a(678)](Q,n),availableWrite:this[a(380)](Q,n)})}[g(724)](){const a=g,Q=Atomics.load(this._state,I.READ_INDEX),n=Atomics[a(829)](this[a(751)],I[a(373)]);return this[a(678)](Q,n)}[g(389)](a){return this[g(724)]()>=a}getBufferLength(){return this[g(896)]-1}[g(380)](a,Q){const n=g;return Q>=a?this[n(896)]-Q+a-1:a-Q-1}[g(678)](a,Q){return Q>=a?Q-a:Q+this._bufferLength-a}}A[g(673)]=C},333:(t,A)=>{const e=Se;Object.defineProperty(A,e(529),{value:!0}),A.sampleModelMap=void 0,A[e(750)]={8e3:e(854),16e3:e(348),24e3:e(452),32e3:e(452),44100:e(452),48e3:e(452),88200:e(452),96e3:"model32"}},862:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(572)]=A[g(891)]=void 0;const i=e(3),I=e(656);function C(o){const a=g;return window[a(919)][a(427)](new Blob([o],{type:a(696)}))}A.WORKLET_URL=C(i),A[g(572)]=C(I)},687:(t,A)=>{const e=Se;Object[e(815)](A,"__esModule",{value:!0}),A[e(729)]=A[e(653)]=A.blobToBase64=void 0,A[e(360)]=async function(g){return new Promise((i,I)=>{const C=Se,o=new FileReader;o[C(849)]=()=>i(o.result),o[C(409)](g)})},A[e(653)]=function(g,i){const I=e,C=window[I(919)][I(427)](i),o=document[I(709)]("a");o[I(460)]=C,o[I(892)]=g||I(684),o[I(948)]()},A[e(729)]=function(g,i){const I=e;if(!g[I(915)])return new Blob([],{type:I(914)});const C=g[0][I(915)],o=new Float32Array(C*g[I(915)]);g[I(909)]((Q,n)=>{o[I(676)](Q,n*C)});const a=function(Q,n){const s=I,B=n[s(556)]?Float32Array:Uint16Array,E=Q[s(422)]/B[s(486)],d=function(h){const r=s,f=h[r(682)],_=h[r(809)]||2,l=h[r(556)]?4:2,D=h[r(556)]?3:1,p=h.sampleRate,y=_*l,k=p*y,x=f*y,w=new ArrayBuffer(44),N=new DataView(w);let U=0;function K(H){const O=r;for(let z=0;z<H.length;z++)N.setUint8(U+z,H[O(555)](z));U+=H.length}function P(H){N[r(545)](U,H,!0),U+=4}function j(H){N[r(450)](U,H,!0),U+=2}return K(r(418)),P(x+36),K(r(399)),K(r(488)),P(16),j(D),j(_),P(p),P(k),j(y),j(8*l),K("data"),P(x),new Uint8Array(w)}(Object[s(879)]({},n,{numFrames:E})),c=new Uint8Array(d[s(915)]+Q[s(422)]);return c[s(676)](d,0),c[s(676)](new Uint8Array(Q),d.length),c}(o.buffer,{isFloat:!0,numChannels:1,sampleRate:i});return new Blob([a],{type:I(702)})}},479:(t,A)=>{const e=Se;Object.defineProperty(A,e(529),{value:!0}),A.isMobile=A.isSafari=void 0,A[e(958)]=function(){const g=e;return navigator[g(352)]&&navigator[g(352)][g(630)](g(656))>-1&&navigator[g(887)]&&navigator[g(887)][g(630)](g(820))==-1&&navigator[g(887)].indexOf("FxiOS")==-1},A[e(792)]=function(){const g=e,i=navigator[g(887)]||navigator[g(352)]||window.opera;return/iPhone|iPad|iPod|Android|IEMobile|Windows Phone|BlackBerry|webOS|Opera Mini|Nexus 7|Nexus 10|KFAPWI/i[g(845)](i)||/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(i)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i[g(845)](i[g(761)](0,4))}},406:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(806)]=A[g(504)]=void 0;const i=e(785),I=e(761);A[g(504)]={REQUEST_NOISE_CANCELLATION:0},A[g(806)]=function(C){const o=g,a=2*I.SDK_FRAME_DURATION_10MS*C.sampleRate/1e3*I[o(768)];return{inputRingBuffer:new i[o(673)](a,C[o(912)]||1),outputRingBuffer:new i[o(673)](a,C.channelCount||1),atomicState:new Int32Array(new SharedArrayBuffer(Object[o(881)](A[o(504)])[o(915)]*Int32Array.BYTES_PER_ELEMENT))}}},761:(t,A)=>{const e=Se;Object[e(815)](A,e(529),{value:!0}),A.BVC_BLOCKED_DEVICES=A[e(850)]=A.MIN_BVC_SUPPORT_SAMPLE_RATE=A[e(513)]=A[e(610)]=A[e(927)]=A[e(569)]=A[e(765)]=A[e(873)]=A[e(401)]=A[e(768)]=void 0,A.WEB_AUDIO_CHUNK_SIZE=128,A[e(401)]=e(800),A.BUFFER_DROP_SIZE_MS=500,A.BUFFER_DROP_KEEP_MS=40,A[e(569)]=200,A[e(927)]=10,A[e(610)]=[8e3,16e3,24e3,32e3,44100,48e3,88200,96e3],A.SUPPORTED_INBOUND_SAMPLE_RATES=[8e3],A[e(394)]=16e3,A[e(850)]=[],A[e(631)]=["macbook pro",e(704),e(918),e(405),e(882),e(705),e(629),e(497),e(464),e(847),e(515),e(632),"razer kiyo","streamcam",e(365),e(670),e(841),e(774),e(562),e(802),e(356),"hyperx quadcast",e(701),e(403),e(698),"gamedac",e(410),"axcs speaker","mateview",e(780),e(351),"pebble v3","jabra speak",e(727),"samson gomic",e(414),e(462),e(526),"amazonbasics desktop mini mic",e(931),e(428),e(712),e(546),"stf coloso",e(706),e(874),e(947),e(640),e(748),e(808),e(760),e(539),"edifier luna eclipse",e(804),e(397),e(439),e(657),e(782),e(785),e(798),"trio8800","edifier s3000 pro","eneby20",e(926),e(398),e(913),e(707),"thronmax mdrill","thronmax pulse",e(691),e(920),e(901),e(491),e(939),e(594),e(781),e(889),e(402),e(549),"razer base station v2 chroma",e(904),e(921),"audioengine",e(739),e(910),e(383),"anker soundcore",e(899),e(388),e(868),"pc-lm1e audio",e(485),e(433),"jabra panacast",e(801),"samsung slimfit cam",e(685),"usb mic",e(908),"teufel cinebar one",e(745),"soundtech",e(411),"speechmike iii",e(956),e(754),e(730),"simmons sd600",e(772),e(514),e(807),e(570),e(599),"inc2000",e(770),e(943),e(563),"lg-pk3","lgtg-210",e(694),"office node bt","iconf","ready elite",e(612),e(543),e(884),e(518),e(536),e(647),"bose sliii","soundlink","powerconf s3",e(907),e(949),e(811),"bss 4803",e(440),e(595),e(492),"bose solo","bugani m83","cambridge audio one","soundcore mini",e(890),e(929),e(639),"by-pm500",e(392),e(759),"edifier s880db",e(495),"fantech luminous c30","anker soundcore boost",e(527),e(911),"jbl pulse 4",e(436),e(790),"mi portable bluetooth speaker","sb-50",e(361),e(593),"soundcore 2","soundcore motion b",e(816),e(818),"ziisound d5",e(928),"presence",e(934),e(519),e(903),e(876),"ln01a",e(505),e(957),"monster s310","pyleusa","phonak compilot ii",e(481),e(390),e(756),e(393),e(606),"wireless controller","epson projector mpp audio",e(445),e(813),e(474),"at2020 usb",e(620),e(338),e(824),"hk onyx studio 4",e(601),e(406),e(689),e(345),"zv-1",e(758),e(870),"creative t60",e(687),e(386),e(498),e(421),e(953),"tonor tc-2030 audio device","wireless go ii rx","kandao meeting","klim talk",e(863),e(523),e(783),"verbatim 1080p mic",e(475),e(669),e(950),e(443),e(753),e(466),e(560),e(869),e(697),e(746),e(618),"infinity fuze 100",e(591),e(834),e(952),e(838),e(823),e(607),e(900),"m799b",e(573),"kz-dc4k audio","shure mv5",e(776),"room1 bluetooth",e(859),"creative live! mic m3",e(437),e(905),"edifier mp380",e(496),"bedroom speaker",e(507),"hk_allure_portable","megablast",e(762),"oppo wireless speaker",e(830),e(359),"oontz angle 3 plus",e(461),e(366),"redmi tv soundbar",e(465),e(456),"audiohub speaker",e(810),"ian layugan’s double chill speaker",e(520),e(672),e(871),e(855),e(805),"ndz-03-ga",e(644),e(454),e(935),e(925),"razer leviathan","s2025",e(852),"sdh-201",e(621),e(583),e(349),"spa4040b",e(866),e(779),e(597),"stone 1400 mini","at-csp5",e(827),e(835),e(419),e(893),e(844),e(382),e(585),e(703),e(652),"tcl ts5000",e(354),"[samsung] airtrack",e(668),e(743),e(611),e(339),e(757),e(577),e(734),"yu6 by kanto","yvc-330 yamaha",e(627),e(710),e(363),e(666),e(400),e(832),e(559),e(476),e(584),e(598),e(379),e(483),"crestron mercury",e(654),e(736),e(642),e(650),e(490),e(358),e(574),"razer seiren",e(344),e(509),e(812),e(624),e(674),e(343),e(733),"fifine k669 microphone",e(533),e(749),e(551),"aoni microphone",e(777),e(822),"fifine k690 microphone",e(951),e(836),e(894),e(658),e(897),e(655),e(501),"trust gxt 242 microphone",e(857),e(878),e(384),e(416),e(942),e(843),e(447),"polycom voxbox",e(469),"wireless microphone rx","poly sync",e(619),e(638),e(407),e(719),e(700),"fifine k670 microphone","obsbot meet 4k microphone","obsbot tiny 4k microphone",e(528),"gxt 244 microphone",e(872),e(547),e(412),e(525),e(423),e(906),e(645),e(933),"sony:srs-x2",e(534),e(576),e(362),e(728),e(763),e(500),"c2422he","emeet m2",e(494),e(613),e(851),"ht-s100f",e(937),e(766),e(617),e(683),"bw02-bt","hw01","soundcore mini 3 pro",e(381),"taotronics tt-sk023","tribit maxsound plus","anker powerconf s3(大会議室)",e(720),e(458),"wonderboom",e(699)]},608:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(723)]=A.validateModels=A[g(664)]=A[g(895)]=A[g(589)]=void 0;const i=e(967),I=e(333),C=e(761);function o(Q){return I[g(750)][Q]}function a(Q){const n=g;return/^https?\:\/\//i[n(845)](Q)||/^file\:\/\//i[n(845)](Q)||/^chrome-extension\:\/\//i.test(Q)||/^moz-extension\:\/\//i[n(845)](Q)?new URL(Q)[n(371)]():((Q==null?void 0:Q[0])!="/"&&(Q="/"+Q),new URL(window[n(941)].origin+Q)[n(371)]())}A[g(589)]=o,A[g(895)]=function(Q){const n=g;try{return Object.values(Q)[n(909)](s=>a(s)),!1}catch{return!0}},A[g(664)]=a,A.validateModels=function(Q){const n=g,s={},B={};try{for(let E in Q){const d=Q[E];if(n(420)==typeof d)s[E]=a(d);else{if(typeof d!="object")throw new Error(n(614));{const c=a(d.url);s[E]=c,d.preload&&(B[E]=c)}}}}catch(E){throw i.Logger.error(n(463),E),E}return[s,B]},A[g(723)]=function(Q,n){const s=g;let B=C.SUPPORTED_SAMPLE_RATES[s(630)](n);for(;B>=0;){const E=o(C[s(610)][B]);if(Q[E])return[E,a(Q[E])];B--}throw new Error("MODEL_NOT_FOUND")}}},Rr={};function Gr(t){const A=Se;var e=Rr[t];if(e!==void 0)return e[A(793)];var g=Rr[t]={exports:{}};return Vl[t](g,g[A(793)],Gr),g.exports}var SQ={};(()=>{const t=Se;var A=SQ;Object[t(815)](A,"X",{value:!0});const e=Gr(62);A.Z=e[t(615)]})(),SQ.X;var Mr=SQ.Z;const Je=no;(function(t,A){const e=no,g=t();for(;;)try{if(parseInt(e(298))/1*(parseInt(e(297))/2)+parseInt(e(247))/3+parseInt(e(269))/4+parseInt(e(233))/5*(parseInt(e(242))/6)+parseInt(e(288))/7*(parseInt(e(313))/8)+-parseInt(e(302))/9+parseInt(e(239))/10*(-parseInt(e(273))/11)===A)break;g.push(g.shift())}catch{g.push(g.shift())}})(so,562139);function no(t,A){const e=so();return no=function(g,i){return g=g-225,e[g]},no(t,A)}function so(){const t=["token","zed","vekit.io/i","settings","s/enc/v1","disconnect","lled after","dispose","Bearer ","iseCancell","startsWith","aStreamDes","restart","4496876BAOwLO","replace","http","model8","11tEJMMC","filter ena","connect","gin. setEn","eFilter","ation","authentica","abled can ","Authentica","Models are","ut connect","te. Server","enable plu","status","Could not ","4705316zCaWEW","model16","cannot res","livekit.cl","model32","only be ca",". Code 256"," enable an","oud","4656CdtJjY","233WCpNDI","isReady","https://li","json","989316uDaCiu","aStreamSou","ing first","ise filter","ntegration","host"," responded","tion Error","cate filte","rce","enable","8gCHxQG","statusText","bled"," missing","Server res","itialized","url","g the trac","Set noise ","disable","d authenti","audioConte","engine","tart witho","debug","endsWith","5MeNWcs","createNois"," enable no"," with stat","isInitiali","isEnabled","33077050iBqzFG","enhancedNo","attempt to","4834338fMChcj","isSupporte","stream","modelPaths","setEnabled","2505642eqXrbi","ponded wit","tination","h status "," publishin","createMedi","us ","init","SDK not in"];return so=function(){return t},so()}var yt,Dg,tC,wi,gi,ti,Fr,Ur,kQ,Lr,RQ,Kr;class GQ{constructor(){mt(this,kQ),mt(this,RQ),mt(this,yt,void 0),mt(this,Dg,void 0),mt(this,tC,!1),mt(this,wi,void 0),mt(this,gi,void 0),mt(this,ti,void 0),pt(this,Fr,!1),pt(this,Ur)}static[Je(243)+"d"](){return Mr[Je(243)+"d"]()}get[(Fr=Je(299),Ur=Je(228)+"xt",Je(237)+Je(257))](){return XA(this,tC)}async[Je(254)](){const A=Je,{model8:e,model16:g,model32:i}=await kr(this,RQ,Kr).call(this);if(!XA(this,yt)){if(!e||!g||!g)throw new Error(A(282)+A(316));Ng(this,yt,new Mr({params:{debugLogs:!1,logProcessStats:!1,useSharedArrayBuffer:!1,bufferOverflowMS:50,models:{model8:e,model16:g,model32:i}}}))}await XA(this,yt)[A(254)](),Ng(this,tC,!0)}[Je(263)](){var A,e,g;const i=Je;Ng(this,ti,void 0),(A=XA(this,Dg))==null||A[i(226)](),(e=XA(this,Dg))==null||e[i(263)](),(g=XA(this,yt))==null||g[i(263)](),Ng(this,yt,void 0),Ng(this,tC,!1),this[i(299)]=!1}async[Je(275)](A,e,g=!0){const i=Je;if(!XA(this,yt))throw new TypeError(i(255)+i(318));return Ng(this,Dg,await XA(this,yt)[i(234)+i(277)]({audioContext:A,stream:e},async()=>{const I=i;this[I(299)]=!0,XA(this,ti)&&g&&this[I(312)](XA(this,ti))},()=>{const I=i;this[I(299)]=!1})),this[i(228)+"xt"]=A,Ng(this,wi,this[i(228)+"xt"][i(252)+i(303)+i(311)](e)),XA(this,gi)??Ng(this,gi,this[i(228)+"xt"][i(252)+i(267)+i(249)]()),XA(this,wi)[i(275)](XA(this,Dg))[i(275)](XA(this,gi)),XA(this,gi)[i(244)]}async[Je(312)](A){var e,g;const i=Je;Ng(this,ti,A);let I=A[i(229)][i(319)];I[i(266)]("ws")&&(I=I[i(270)](/^(ws)/,i(271)));const C=A[i(229)][i(256)],o=await kr(this,kQ,Lr).call(this,I,C);this[i(299)]&&o?((e=XA(this,Dg))==null||e[i(312)](),console[i(231)](i(225)+i(274)+i(315),!0)):this[i(299)]&&!o&&(console[i(231)](i(225)+i(274)+i(315),!1),(g=XA(this,Dg))==null||g[i(226)]())}[Je(246)](A){var e;const g=Je;if(console[g(231)](g(241)+g(235)+g(305),A),A&&XA(this,ti))console[g(231)](g(241)+g(295)+g(227)+g(310)+"r"),this[g(312)](XA(this,ti));else if(!A)(e=XA(this,Dg))==null||e[g(226)]();else throw new Error(g(287)+g(285)+g(276)+g(280)+g(293)+g(262)+g(251)+g(320)+"k")}async[Je(268)](A){var e,g;const i=Je;if(!XA(this,Dg)||!XA(this,gi)||!XA(this,wi)||!this[i(228)+"xt"])throw Error(i(290)+i(230)+i(283)+i(304));const I=XA(this,Dg)[i(238)]();return XA(this,wi)[i(261)](),(e=XA(this,Dg))==null||e[i(261)](XA(this,gi)),(g=XA(this,Dg))==null||g[i(263)](),Ng(this,wi,void 0),this[i(275)](this[i(228)+"xt"],A,I)}}yt=new WeakMap,Dg=new WeakMap,tC=new WeakMap,wi=new WeakMap,gi=new WeakMap,ti=new WeakMap,kQ=new WeakSet,Lr=async function(t,A){const e=Je;if(!new URL(t)[e(307)][e(232)](e(291)+e(296)))throw new Error(e(281)+e(309)+e(294)+"83");const g=new URL(e(259),t),i=await fetch(g,{headers:{authorization:e(264)+A}});if(i.ok)return(await i[e(301)]())[e(240)+e(265)+e(278)]===!0;throw new Error(e(287)+e(279)+e(284)+e(308)+e(236)+e(253)+i[e(286)]+": "+i[e(314)])},RQ=new WeakSet,Kr=async function(){const t=Je,A=await fetch(t(300)+t(258)+t(306)+t(260));if(A.ok){const e=await A[t(301)]();return{model8:e[t(245)][t(272)],model16:e[t(245)][t(289)],model32:e[t(245)][t(292)]}}else throw new Error(t(317)+t(248)+t(250)+A[t(286)]+": "+A[t(314)])};var _g;class vr{constructor(A){pt(this,"name","livekit-noise-filter"),pt(this,"processedTrack"),pt(this,"trackSettings"),pt(this,"originalTrack"),mt(this,_g,void 0),pt(this,"init",async e=>{console.debug("initializing noise processor"),this.originalTrack=e.track,this.trackSettings=e.track.getSettings(),e.audioContext.sampleRate!==this.trackSettings.sampleRate&&console.debug("sample rate mismatch, reapplying"),await e.track.applyConstraints({...this.trackSettings,echoCancellation:!1,autoGainControl:!1,noiseSuppression:!1,sampleRate:e.audioContext.sampleRate}),XA(this,_g)||Ng(this,_g,new GQ),await XA(this,_g).init(),this.processedTrack=(await XA(this,_g).connect(e.audioContext,new MediaStream([e.track]))).getAudioTracks()[0]}),pt(this,"restart",async e=>{if(!XA(this,_g))throw Error("cannot restart without having initialized first");console.debug("restarting noise cancellation"),this.processedTrack=(await XA(this,_g).restart(new MediaStream([e.track]))).getAudioTracks()[0]}),pt(this,"destroy",async()=>{var e,g;(e=XA(this,_g))==null||e.dispose(),await((g=this.originalTrack)==null?void 0:g.applyConstraints(this.trackSettings))}),Ng(this,_g,new GQ)}static isSupported(){return GQ.isSupported()}async onPublish(A){await XA(this,_g).enable(A),await XA(this,_g).setEnabled(!0)}async setEnabled(A){await XA(this,_g).setEnabled(A)}}_g=new WeakMap;const jl=vr.isSupported,Wl=()=>new vr;class II{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return II.instance||(II.instance=new II),II.instance}async acquire(){if(this.refCount++,!this.audioContext)try{const A=window.AudioContext||window.webkitAudioContext;if(!A)return console.warn("[SharedAudioContext] Web Audio API not supported"),null;this.audioContext=new A,console.log("[SharedAudioContext] Created shared AudioContext")}catch(A){return console.warn("[SharedAudioContext] Failed to create AudioContext:",A),null}return await this.ensureResumed(),this.audioContext}release(){this.refCount=Math.max(0,this.refCount-1),this.refCount===0&&console.log("[SharedAudioContext] All references released, context kept alive for reuse")}forceClose(){if(this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null,this.refCount=0,console.log("[SharedAudioContext] Force closed")}}getContext(){return this.audioContext}async ensureResumed(){if(!this.audioContext)return!1;if(this.audioContext.state==="suspended"){this.resumePromise||(this.resumePromise=this.audioContext.resume().finally(()=>{this.resumePromise=null}));try{await this.resumePromise}catch{return!1}}return this.audioContext.state==="running"}isRunning(){return this.audioContext!==null&&this.audioContext.state==="running"}getState(){var A;return((A=this.audioContext)==null?void 0:A.state)??null}getSampleRate(){var A;return((A=this.audioContext)==null?void 0:A.sampleRate)??44100}getCurrentTime(){var A;return((A=this.audioContext)==null?void 0:A.currentTime)??0}getDestination(){var A;return((A=this.audioContext)==null?void 0:A.destination)??null}}const Ct=II.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{Ct.forceClose()});const Jr=jl()?Wl():null,Qg=class Qg 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,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.agentAudioElements=[],this.unmuteTimer=null,this.speakingHandler=null,this.fadeContext=null,this.fadeContextAcquired=!1,this.fadeGains=new Map,this.fadeSetupPromise=null,this.noiseFilterAttached=!1}static isAgentIdentity(A){return A.includes("agent")||A.includes("voice-assistant")||A.includes("AJ_")}set serviceUrl(A){this._serviceUrl=A}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(A){this.callStatus=A,this.dispatchEvent(new CustomEvent("status-changed",{detail:A}))}async makeCall({agentId:A,user_identity:e}){var g;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 i=new iI({webAudioMix:!1,dynacast:!0,adaptiveStream:!0});this.room=i,this.setupRoomEventListeners(i);const I=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{user_identity:e,agent_id:A,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})});if(!I.ok){const s=await I.text();throw new Error(`Failed to get room token: ${I.status} ${s}`)}const{token:C,url:o,room_name:a,user_identity:Q}=await I.json();this.roomName=a,this.userIdentity=Q;const n={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};await Promise.all([i.localParticipant.setMicrophoneEnabled(!0,n).then(()=>{this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),this.attachNoiseFilter(i)}).catch(s=>{console.warn("Could not enable microphone:",s),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}),i.connect(o,C)]),await new Promise(s=>{const B=setTimeout(()=>{i.off(tA.ParticipantConnected,E),s()},2e3),E=d=>{Qg.isAgentIdentity(d.identity)&&(clearTimeout(B),i.off(tA.ParticipantConnected,E),s())};for(const d of i.remoteParticipants.values())if(Qg.isAgentIdentity(d.identity)){clearTimeout(B),s();return}i.on(tA.ParticipantConnected,E)}),this.updateStatus("connected"),this.isReady=!0;for(const s of i.localParticipant.audioTrackPublications.values())(g=s.track)!=null&&g.mediaStreamTrack&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:s.track.mediaStreamTrack}));this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:a,identity:Q}}))}catch(i){this.error=`Connection failed: ${i instanceof Error?i.message:String(i)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(A){A.on(tA.Disconnected,()=>{this.callStatus!=="disconnected"&&this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.noiseFilterAttached=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(A.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.room=null,this.dispatchEvent(new CustomEvent("disconnected"))}),A.on(tA.ParticipantConnected,e=>{this.connectedParticipants=[...this.connectedParticipants,e.identity];const g=Qg.isAgentIdentity(e.identity);g&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:e.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:e.identity,isAgent:g}}))}),A.on(tA.ParticipantDisconnected,e=>{this.connectedParticipants=this.connectedParticipants.filter(i=>i!==e.identity);const g=Qg.isAgentIdentity(e.identity);g&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:e.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:e.identity,isAgent:g}}))}),A.on(tA.TrackSubscribed,(e,g,i)=>{if(e.kind==="audio"){const I=e.attach();document.body.appendChild(I),Qg.isAgentIdentity(i.identity)&&(this.agentAudioElements.push(I),this.setupAgentAudioFade(I)),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:i.identity,element:I}}));const C=e.mediaStreamTrack;C&&this.dispatchEvent(new CustomEvent("audio-track",{detail:C}))}}),A.on(tA.TrackUnsubscribed,(e,g,i)=>{const I=e.detach();for(const C of I){const o=this.fadeGains.get(C);if(o){try{o.source.disconnect()}catch{}try{o.gain.disconnect()}catch{}this.fadeGains.delete(C)}}this.agentAudioElements=this.agentAudioElements.filter(C=>!I.includes(C)),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:i.identity}}))}),A.on(tA.MediaDevicesError,e=>{this.error=`Media device error: ${e.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),A.on(tA.AudioPlaybackStatusChanged,async()=>{A.canPlaybackAudio||this.connectedParticipants.some(g=>Qg.isAgentIdentity(g))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:A.canPlaybackAudio}}))}),A.on(tA.DataReceived,(e,g)=>{try{const i=JSON.parse(new TextDecoder().decode(e));i.type==="transcript"?this.dispatchEvent(new CustomEvent("transcription",{detail:{speaker:i.speaker,text:i.text,timestamp:i.timestamp},bubbles:!0,composed:!0})):(!g||Qg.isAgentIdentity(g.identity))&&this.dispatchEvent(new CustomEvent("agent-command",{detail:i}))}catch{}}),this.speakingHandler=e=>{e?(this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.rampAgentGain(0,Qg.FADEOUT_TC)):this.unmuteTimer=setTimeout(()=>{this.unmuteTimer=null,this.rampAgentGain(1,Qg.FADEIN_TC)},Qg.UNMUTE_HOLDOVER_MS)},A.localParticipant.on("isSpeakingChanged",this.speakingHandler)}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.noiseFilterAttached=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),this.attachNoiseFilter(this.room))}catch(A){this.error=`Failed to toggle microphone: ${A instanceof Error?A.message:String(A)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}attachNoiseFilter(A){if(!Jr||this.noiseFilterAttached)return;const e=Array.from(A.localParticipant.audioTrackPublications.values()).find(i=>i.kind==="audio"),g=e==null?void 0:e.track;g&&g.setProcessor(Jr).then(()=>{this.noiseFilterAttached=!0,console.log("[NoiseFilter] ai-coustics Voice Focus attached")}).catch(i=>{console.warn("[NoiseFilter] Failed to attach, keeping native NS:",i)})}setupAgentAudioFade(A){const e=(async()=>{try{if(this.fadeContext)await Ct.ensureResumed();else{const I=await Ct.acquire();if(!I){console.warn("[CallManager] Could not acquire shared AudioContext for fade");return}this.fadeContext=I,this.fadeContextAcquired=!0}const g=this.fadeContext.createMediaElementSource(A),i=this.fadeContext.createGain();g.connect(i),i.connect(this.fadeContext.destination),this.fadeGains.set(A,{source:g,gain:i})}catch(g){console.warn("[CallManager] Audio fade setup failed:",g)}})();this.fadeSetupPromise=e,e.then(()=>{this.fadeSetupPromise=null})}rampAgentGain(A,e,g=!1){const i=this.fadeContext;if(i&&i.state==="running"&&this.fadeGains.size>0)for(const{gain:I}of this.fadeGains.values())I.gain.cancelScheduledValues(i.currentTime),I.gain.setValueAtTime(I.gain.value,i.currentTime),I.gain.setTargetAtTime(A,i.currentTime,e);else if(this.fadeSetupPromise)this.fadeSetupPromise.then(()=>this.rampAgentGain(A,e));else if(!g&&i&&i.state==="suspended"&&this.fadeGains.size>0)Ct.ensureResumed().then(I=>{if(I)this.rampAgentGain(A,e,!0);else for(const C of this.agentAudioElements)C.volume=A});else for(const I of this.agentAudioElements)I.volume=A}cleanupFadeContext(){this.agentAudioElements=[];for(const{source:A,gain:e}of this.fadeGains.values()){try{A.disconnect()}catch{}try{e.disconnect()}catch{}}this.fadeGains.clear(),this.fadeSetupPromise=null,this.fadeContextAcquired&&(Ct.release(),this.fadeContextAcquired=!1),this.fadeContext=null}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const A=JSON.stringify({type:"audio_enabled"}),g=new TextEncoder().encode(A);await this.room.localParticipant.publishData(g,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(A){this.error=`Failed to enable audio: ${A instanceof Error?A.message:String(A)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async sendDataToAgent(A){if(!this.room){console.warn("[LiveKitCallManager] Cannot send data: no room");return}const g=new TextEncoder().encode(JSON.stringify(A));await this.room.localParticipant.publishData(g,{reliable:!0})}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const A=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(A.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),requestAnimationFrame(()=>{setTimeout(async()=>{try{await A.disconnect()}catch(e){console.warn("Error during room disconnect:",e)}},0)})}};Qg.UNMUTE_HOLDOVER_MS=350,Qg.FADEOUT_TC=.045,Qg.FADEIN_TC=.03;let CI=Qg;/**
|
|
147
|
+
`;if(!this.logPort)return console[a(565)]("KrispSDK -",a(635),Q);this.logPort[a(732)](Q)}}},851:(t,A)=>{const e=Se;Object.defineProperty(A,"__esModule",{value:!0}),A[e(567)]=void 0,A[e(567)]=class{constructor(g={}){const i=e;this[i(554)]=g,this.dataCache={}}static async preload(g){const i=e,I=typeof g=="string"?g:g.url;return fetch(I,{cache:i(603)})}addPath(g,i){const I=e;this[I(554)][g]=i}removePath(g){const i=e;this[i(554)][g]&&(this.unloadModel(g),delete this[i(554)][g])}[e(831)](g){const i=e;if(!this[i(554)][g])throw new Error("Krisp SDK - Please add model path before loading");return this[i(517)][g]?this[i(517)][g]:new Promise((I,C)=>{const o=i;this[o(368)](this[o(554)][g],a=>{const Q=o;this[Q(517)][g]=a,I(a)},C)})}async[e(875)](g,i){const I=e;try{const C=await this.loadModel(i),o=new Uint8Array(C),a=g[I(688)](o[I(422)]);return g[I(865)][I(742)](a,a+o[I(422)])[I(676)](o),{bufferAddress:a,bufferLength:o[I(422)]}}catch(C){throw new Error(I(430)+C)}}[e(628)](g,i){g[e(480)](i)}[e(426)](g){this[e(517)][g]&&delete this.dataCache[g]}[e(368)](g,i,I){const C=e;var o=new XMLHttpRequest;o[C(726)]("GET",g,!0),o[C(817)]=C(858),o[C(633)]=function(){I("Network error during model loading")},o[C(731)]=function(){const a=C;o[a(434)]==200||o[a(434)]==304||o[a(434)]==206||o[a(434)]==0&&o[a(679)]?i(o[a(679)]):I(o.statusText+" : "+o[a(502)])},o[C(357)](null)}[e(799)](){const g=e;this.dataCache={},this[g(554)]={}}}},785:(t,A,e)=>{const g=Se;Object[g(815)](A,"__esModule",{value:!0}),A.SharedRingBuffer=void 0;const i=e(967),I={READ_INDEX:0,WRITE_INDEX:1};class C{constructor(a,Q=1){const n=g;this._channelData=[],this[n(457)]=Q,this[n(751)]=new Uint32Array(new SharedArrayBuffer(Object[n(881)](I)[n(915)]*Uint32Array[n(486)])),this._bufferLength=a+1;for(let s=0;s<Q;s++)this[n(690)].push(new Float32Array(new SharedArrayBuffer(this[n(896)]*Float32Array[n(486)])))}static[g(548)](a){return Object[g(634)](a,C.prototype)}push(a,Q){const n=g,s=Atomics[n(829)](this[n(751)],I[n(641)]),B=Atomics[n(829)](this._state,I[n(373)]);if(this._getAvailableWrite(s,B)<Q)return!1;let E=B+Q;if(this[n(896)]<E){E-=this[n(896)];for(let d=0;d<this[n(457)];d++){const c=this._channelData[d][n(742)](B),h=this[n(690)][d][n(742)](0,E);c[n(676)](a[d][n(742)](0,c[n(915)])),h[n(676)](a[d][n(742)](c[n(915)]))}}else{for(let d=0;d<this[n(457)];d++)this[n(690)][d].subarray(B,E)[n(676)](a[d].subarray(0,Q));E===this[n(896)]&&(E=0)}return Atomics.store(this[n(751)],I.WRITE_INDEX,E),!0}pull(a,Q){const n=g,s=Atomics[n(829)](this._state,I[n(641)]),B=Atomics[n(829)](this[n(751)],I[n(373)]);if(this._getAvailableRead(s,B)<Q)return!1;let E=s+Q;if(this[n(896)]<E){E-=this._bufferLength;for(let d=0;d<this[n(457)];d++){const c=this[n(690)][d][n(742)](s),h=this[n(690)][d][n(742)](0,E);a[d].set(c),a[d].set(h,c[n(915)])}}else{for(let d=0;d<this._channelCount;++d)a[d][n(676)](this[n(690)][d][n(742)](s,E));E===this._bufferLength&&(E=0)}return Atomics[n(431)](this[n(751)],I[n(641)],E),!0}[g(708)](){const a=g,Q=Atomics[a(829)](this[a(751)],I[a(641)]),n=Atomics.load(this[a(751)],I[a(373)]);i[a(571)][a(695)](this,{availableRead:this[a(678)](Q,n),availableWrite:this[a(380)](Q,n)})}[g(724)](){const a=g,Q=Atomics.load(this._state,I.READ_INDEX),n=Atomics[a(829)](this[a(751)],I[a(373)]);return this[a(678)](Q,n)}[g(389)](a){return this[g(724)]()>=a}getBufferLength(){return this[g(896)]-1}[g(380)](a,Q){const n=g;return Q>=a?this[n(896)]-Q+a-1:a-Q-1}[g(678)](a,Q){return Q>=a?Q-a:Q+this._bufferLength-a}}A[g(673)]=C},333:(t,A)=>{const e=Se;Object.defineProperty(A,e(529),{value:!0}),A.sampleModelMap=void 0,A[e(750)]={8e3:e(854),16e3:e(348),24e3:e(452),32e3:e(452),44100:e(452),48e3:e(452),88200:e(452),96e3:"model32"}},862:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(572)]=A[g(891)]=void 0;const i=e(3),I=e(656);function C(o){const a=g;return window[a(919)][a(427)](new Blob([o],{type:a(696)}))}A.WORKLET_URL=C(i),A[g(572)]=C(I)},687:(t,A)=>{const e=Se;Object[e(815)](A,"__esModule",{value:!0}),A[e(729)]=A[e(653)]=A.blobToBase64=void 0,A[e(360)]=async function(g){return new Promise((i,I)=>{const C=Se,o=new FileReader;o[C(849)]=()=>i(o.result),o[C(409)](g)})},A[e(653)]=function(g,i){const I=e,C=window[I(919)][I(427)](i),o=document[I(709)]("a");o[I(460)]=C,o[I(892)]=g||I(684),o[I(948)]()},A[e(729)]=function(g,i){const I=e;if(!g[I(915)])return new Blob([],{type:I(914)});const C=g[0][I(915)],o=new Float32Array(C*g[I(915)]);g[I(909)]((Q,n)=>{o[I(676)](Q,n*C)});const a=function(Q,n){const s=I,B=n[s(556)]?Float32Array:Uint16Array,E=Q[s(422)]/B[s(486)],d=function(h){const r=s,f=h[r(682)],_=h[r(809)]||2,l=h[r(556)]?4:2,D=h[r(556)]?3:1,p=h.sampleRate,y=_*l,k=p*y,x=f*y,w=new ArrayBuffer(44),N=new DataView(w);let U=0;function K(H){const O=r;for(let z=0;z<H.length;z++)N.setUint8(U+z,H[O(555)](z));U+=H.length}function P(H){N[r(545)](U,H,!0),U+=4}function j(H){N[r(450)](U,H,!0),U+=2}return K(r(418)),P(x+36),K(r(399)),K(r(488)),P(16),j(D),j(_),P(p),P(k),j(y),j(8*l),K("data"),P(x),new Uint8Array(w)}(Object[s(879)]({},n,{numFrames:E})),c=new Uint8Array(d[s(915)]+Q[s(422)]);return c[s(676)](d,0),c[s(676)](new Uint8Array(Q),d.length),c}(o.buffer,{isFloat:!0,numChannels:1,sampleRate:i});return new Blob([a],{type:I(702)})}},479:(t,A)=>{const e=Se;Object.defineProperty(A,e(529),{value:!0}),A.isMobile=A.isSafari=void 0,A[e(958)]=function(){const g=e;return navigator[g(352)]&&navigator[g(352)][g(630)](g(656))>-1&&navigator[g(887)]&&navigator[g(887)][g(630)](g(820))==-1&&navigator[g(887)].indexOf("FxiOS")==-1},A[e(792)]=function(){const g=e,i=navigator[g(887)]||navigator[g(352)]||window.opera;return/iPhone|iPad|iPod|Android|IEMobile|Windows Phone|BlackBerry|webOS|Opera Mini|Nexus 7|Nexus 10|KFAPWI/i[g(845)](i)||/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(i)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i[g(845)](i[g(761)](0,4))}},406:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(806)]=A[g(504)]=void 0;const i=e(785),I=e(761);A[g(504)]={REQUEST_NOISE_CANCELLATION:0},A[g(806)]=function(C){const o=g,a=2*I.SDK_FRAME_DURATION_10MS*C.sampleRate/1e3*I[o(768)];return{inputRingBuffer:new i[o(673)](a,C[o(912)]||1),outputRingBuffer:new i[o(673)](a,C.channelCount||1),atomicState:new Int32Array(new SharedArrayBuffer(Object[o(881)](A[o(504)])[o(915)]*Int32Array.BYTES_PER_ELEMENT))}}},761:(t,A)=>{const e=Se;Object[e(815)](A,e(529),{value:!0}),A.BVC_BLOCKED_DEVICES=A[e(850)]=A.MIN_BVC_SUPPORT_SAMPLE_RATE=A[e(513)]=A[e(610)]=A[e(927)]=A[e(569)]=A[e(765)]=A[e(873)]=A[e(401)]=A[e(768)]=void 0,A.WEB_AUDIO_CHUNK_SIZE=128,A[e(401)]=e(800),A.BUFFER_DROP_SIZE_MS=500,A.BUFFER_DROP_KEEP_MS=40,A[e(569)]=200,A[e(927)]=10,A[e(610)]=[8e3,16e3,24e3,32e3,44100,48e3,88200,96e3],A.SUPPORTED_INBOUND_SAMPLE_RATES=[8e3],A[e(394)]=16e3,A[e(850)]=[],A[e(631)]=["macbook pro",e(704),e(918),e(405),e(882),e(705),e(629),e(497),e(464),e(847),e(515),e(632),"razer kiyo","streamcam",e(365),e(670),e(841),e(774),e(562),e(802),e(356),"hyperx quadcast",e(701),e(403),e(698),"gamedac",e(410),"axcs speaker","mateview",e(780),e(351),"pebble v3","jabra speak",e(727),"samson gomic",e(414),e(462),e(526),"amazonbasics desktop mini mic",e(931),e(428),e(712),e(546),"stf coloso",e(706),e(874),e(947),e(640),e(748),e(808),e(760),e(539),"edifier luna eclipse",e(804),e(397),e(439),e(657),e(782),e(785),e(798),"trio8800","edifier s3000 pro","eneby20",e(926),e(398),e(913),e(707),"thronmax mdrill","thronmax pulse",e(691),e(920),e(901),e(491),e(939),e(594),e(781),e(889),e(402),e(549),"razer base station v2 chroma",e(904),e(921),"audioengine",e(739),e(910),e(383),"anker soundcore",e(899),e(388),e(868),"pc-lm1e audio",e(485),e(433),"jabra panacast",e(801),"samsung slimfit cam",e(685),"usb mic",e(908),"teufel cinebar one",e(745),"soundtech",e(411),"speechmike iii",e(956),e(754),e(730),"simmons sd600",e(772),e(514),e(807),e(570),e(599),"inc2000",e(770),e(943),e(563),"lg-pk3","lgtg-210",e(694),"office node bt","iconf","ready elite",e(612),e(543),e(884),e(518),e(536),e(647),"bose sliii","soundlink","powerconf s3",e(907),e(949),e(811),"bss 4803",e(440),e(595),e(492),"bose solo","bugani m83","cambridge audio one","soundcore mini",e(890),e(929),e(639),"by-pm500",e(392),e(759),"edifier s880db",e(495),"fantech luminous c30","anker soundcore boost",e(527),e(911),"jbl pulse 4",e(436),e(790),"mi portable bluetooth speaker","sb-50",e(361),e(593),"soundcore 2","soundcore motion b",e(816),e(818),"ziisound d5",e(928),"presence",e(934),e(519),e(903),e(876),"ln01a",e(505),e(957),"monster s310","pyleusa","phonak compilot ii",e(481),e(390),e(756),e(393),e(606),"wireless controller","epson projector mpp audio",e(445),e(813),e(474),"at2020 usb",e(620),e(338),e(824),"hk onyx studio 4",e(601),e(406),e(689),e(345),"zv-1",e(758),e(870),"creative t60",e(687),e(386),e(498),e(421),e(953),"tonor tc-2030 audio device","wireless go ii rx","kandao meeting","klim talk",e(863),e(523),e(783),"verbatim 1080p mic",e(475),e(669),e(950),e(443),e(753),e(466),e(560),e(869),e(697),e(746),e(618),"infinity fuze 100",e(591),e(834),e(952),e(838),e(823),e(607),e(900),"m799b",e(573),"kz-dc4k audio","shure mv5",e(776),"room1 bluetooth",e(859),"creative live! mic m3",e(437),e(905),"edifier mp380",e(496),"bedroom speaker",e(507),"hk_allure_portable","megablast",e(762),"oppo wireless speaker",e(830),e(359),"oontz angle 3 plus",e(461),e(366),"redmi tv soundbar",e(465),e(456),"audiohub speaker",e(810),"ian layugan’s double chill speaker",e(520),e(672),e(871),e(855),e(805),"ndz-03-ga",e(644),e(454),e(935),e(925),"razer leviathan","s2025",e(852),"sdh-201",e(621),e(583),e(349),"spa4040b",e(866),e(779),e(597),"stone 1400 mini","at-csp5",e(827),e(835),e(419),e(893),e(844),e(382),e(585),e(703),e(652),"tcl ts5000",e(354),"[samsung] airtrack",e(668),e(743),e(611),e(339),e(757),e(577),e(734),"yu6 by kanto","yvc-330 yamaha",e(627),e(710),e(363),e(666),e(400),e(832),e(559),e(476),e(584),e(598),e(379),e(483),"crestron mercury",e(654),e(736),e(642),e(650),e(490),e(358),e(574),"razer seiren",e(344),e(509),e(812),e(624),e(674),e(343),e(733),"fifine k669 microphone",e(533),e(749),e(551),"aoni microphone",e(777),e(822),"fifine k690 microphone",e(951),e(836),e(894),e(658),e(897),e(655),e(501),"trust gxt 242 microphone",e(857),e(878),e(384),e(416),e(942),e(843),e(447),"polycom voxbox",e(469),"wireless microphone rx","poly sync",e(619),e(638),e(407),e(719),e(700),"fifine k670 microphone","obsbot meet 4k microphone","obsbot tiny 4k microphone",e(528),"gxt 244 microphone",e(872),e(547),e(412),e(525),e(423),e(906),e(645),e(933),"sony:srs-x2",e(534),e(576),e(362),e(728),e(763),e(500),"c2422he","emeet m2",e(494),e(613),e(851),"ht-s100f",e(937),e(766),e(617),e(683),"bw02-bt","hw01","soundcore mini 3 pro",e(381),"taotronics tt-sk023","tribit maxsound plus","anker powerconf s3(大会議室)",e(720),e(458),"wonderboom",e(699)]},608:(t,A,e)=>{const g=Se;Object[g(815)](A,g(529),{value:!0}),A[g(723)]=A.validateModels=A[g(664)]=A[g(895)]=A[g(589)]=void 0;const i=e(967),I=e(333),C=e(761);function o(Q){return I[g(750)][Q]}function a(Q){const n=g;return/^https?\:\/\//i[n(845)](Q)||/^file\:\/\//i[n(845)](Q)||/^chrome-extension\:\/\//i.test(Q)||/^moz-extension\:\/\//i[n(845)](Q)?new URL(Q)[n(371)]():((Q==null?void 0:Q[0])!="/"&&(Q="/"+Q),new URL(window[n(941)].origin+Q)[n(371)]())}A[g(589)]=o,A[g(895)]=function(Q){const n=g;try{return Object.values(Q)[n(909)](s=>a(s)),!1}catch{return!0}},A[g(664)]=a,A.validateModels=function(Q){const n=g,s={},B={};try{for(let E in Q){const d=Q[E];if(n(420)==typeof d)s[E]=a(d);else{if(typeof d!="object")throw new Error(n(614));{const c=a(d.url);s[E]=c,d.preload&&(B[E]=c)}}}}catch(E){throw i.Logger.error(n(463),E),E}return[s,B]},A[g(723)]=function(Q,n){const s=g;let B=C.SUPPORTED_SAMPLE_RATES[s(630)](n);for(;B>=0;){const E=o(C[s(610)][B]);if(Q[E])return[E,a(Q[E])];B--}throw new Error("MODEL_NOT_FOUND")}}},Rr={};function Gr(t){const A=Se;var e=Rr[t];if(e!==void 0)return e[A(793)];var g=Rr[t]={exports:{}};return Vl[t](g,g[A(793)],Gr),g.exports}var SQ={};(()=>{const t=Se;var A=SQ;Object[t(815)](A,"X",{value:!0});const e=Gr(62);A.Z=e[t(615)]})(),SQ.X;var Mr=SQ.Z;const Je=no;(function(t,A){const e=no,g=t();for(;;)try{if(parseInt(e(298))/1*(parseInt(e(297))/2)+parseInt(e(247))/3+parseInt(e(269))/4+parseInt(e(233))/5*(parseInt(e(242))/6)+parseInt(e(288))/7*(parseInt(e(313))/8)+-parseInt(e(302))/9+parseInt(e(239))/10*(-parseInt(e(273))/11)===A)break;g.push(g.shift())}catch{g.push(g.shift())}})(so,562139);function no(t,A){const e=so();return no=function(g,i){return g=g-225,e[g]},no(t,A)}function so(){const t=["token","zed","vekit.io/i","settings","s/enc/v1","disconnect","lled after","dispose","Bearer ","iseCancell","startsWith","aStreamDes","restart","4496876BAOwLO","replace","http","model8","11tEJMMC","filter ena","connect","gin. setEn","eFilter","ation","authentica","abled can ","Authentica","Models are","ut connect","te. Server","enable plu","status","Could not ","4705316zCaWEW","model16","cannot res","livekit.cl","model32","only be ca",". Code 256"," enable an","oud","4656CdtJjY","233WCpNDI","isReady","https://li","json","989316uDaCiu","aStreamSou","ing first","ise filter","ntegration","host"," responded","tion Error","cate filte","rce","enable","8gCHxQG","statusText","bled"," missing","Server res","itialized","url","g the trac","Set noise ","disable","d authenti","audioConte","engine","tart witho","debug","endsWith","5MeNWcs","createNois"," enable no"," with stat","isInitiali","isEnabled","33077050iBqzFG","enhancedNo","attempt to","4834338fMChcj","isSupporte","stream","modelPaths","setEnabled","2505642eqXrbi","ponded wit","tination","h status "," publishin","createMedi","us ","init","SDK not in"];return so=function(){return t},so()}var yt,Dg,tC,wi,gi,ti,Fr,Ur,kQ,Lr,RQ,Kr;class GQ{constructor(){mt(this,kQ),mt(this,RQ),mt(this,yt,void 0),mt(this,Dg,void 0),mt(this,tC,!1),mt(this,wi,void 0),mt(this,gi,void 0),mt(this,ti,void 0),pt(this,Fr,!1),pt(this,Ur)}static[Je(243)+"d"](){return Mr[Je(243)+"d"]()}get[(Fr=Je(299),Ur=Je(228)+"xt",Je(237)+Je(257))](){return XA(this,tC)}async[Je(254)](){const A=Je,{model8:e,model16:g,model32:i}=await kr(this,RQ,Kr).call(this);if(!XA(this,yt)){if(!e||!g||!g)throw new Error(A(282)+A(316));Ng(this,yt,new Mr({params:{debugLogs:!1,logProcessStats:!1,useSharedArrayBuffer:!1,bufferOverflowMS:50,models:{model8:e,model16:g,model32:i}}}))}await XA(this,yt)[A(254)](),Ng(this,tC,!0)}[Je(263)](){var A,e,g;const i=Je;Ng(this,ti,void 0),(A=XA(this,Dg))==null||A[i(226)](),(e=XA(this,Dg))==null||e[i(263)](),(g=XA(this,yt))==null||g[i(263)](),Ng(this,yt,void 0),Ng(this,tC,!1),this[i(299)]=!1}async[Je(275)](A,e,g=!0){const i=Je;if(!XA(this,yt))throw new TypeError(i(255)+i(318));return Ng(this,Dg,await XA(this,yt)[i(234)+i(277)]({audioContext:A,stream:e},async()=>{const I=i;this[I(299)]=!0,XA(this,ti)&&g&&this[I(312)](XA(this,ti))},()=>{const I=i;this[I(299)]=!1})),this[i(228)+"xt"]=A,Ng(this,wi,this[i(228)+"xt"][i(252)+i(303)+i(311)](e)),XA(this,gi)??Ng(this,gi,this[i(228)+"xt"][i(252)+i(267)+i(249)]()),XA(this,wi)[i(275)](XA(this,Dg))[i(275)](XA(this,gi)),XA(this,gi)[i(244)]}async[Je(312)](A){var e,g;const i=Je;Ng(this,ti,A);let I=A[i(229)][i(319)];I[i(266)]("ws")&&(I=I[i(270)](/^(ws)/,i(271)));const C=A[i(229)][i(256)],o=await kr(this,kQ,Lr).call(this,I,C);this[i(299)]&&o?((e=XA(this,Dg))==null||e[i(312)](),console[i(231)](i(225)+i(274)+i(315),!0)):this[i(299)]&&!o&&(console[i(231)](i(225)+i(274)+i(315),!1),(g=XA(this,Dg))==null||g[i(226)]())}[Je(246)](A){var e;const g=Je;if(console[g(231)](g(241)+g(235)+g(305),A),A&&XA(this,ti))console[g(231)](g(241)+g(295)+g(227)+g(310)+"r"),this[g(312)](XA(this,ti));else if(!A)(e=XA(this,Dg))==null||e[g(226)]();else throw new Error(g(287)+g(285)+g(276)+g(280)+g(293)+g(262)+g(251)+g(320)+"k")}async[Je(268)](A){var e,g;const i=Je;if(!XA(this,Dg)||!XA(this,gi)||!XA(this,wi)||!this[i(228)+"xt"])throw Error(i(290)+i(230)+i(283)+i(304));const I=XA(this,Dg)[i(238)]();return XA(this,wi)[i(261)](),(e=XA(this,Dg))==null||e[i(261)](XA(this,gi)),(g=XA(this,Dg))==null||g[i(263)](),Ng(this,wi,void 0),this[i(275)](this[i(228)+"xt"],A,I)}}yt=new WeakMap,Dg=new WeakMap,tC=new WeakMap,wi=new WeakMap,gi=new WeakMap,ti=new WeakMap,kQ=new WeakSet,Lr=async function(t,A){const e=Je;if(!new URL(t)[e(307)][e(232)](e(291)+e(296)))throw new Error(e(281)+e(309)+e(294)+"83");const g=new URL(e(259),t),i=await fetch(g,{headers:{authorization:e(264)+A}});if(i.ok)return(await i[e(301)]())[e(240)+e(265)+e(278)]===!0;throw new Error(e(287)+e(279)+e(284)+e(308)+e(236)+e(253)+i[e(286)]+": "+i[e(314)])},RQ=new WeakSet,Kr=async function(){const t=Je,A=await fetch(t(300)+t(258)+t(306)+t(260));if(A.ok){const e=await A[t(301)]();return{model8:e[t(245)][t(272)],model16:e[t(245)][t(289)],model32:e[t(245)][t(292)]}}else throw new Error(t(317)+t(248)+t(250)+A[t(286)]+": "+A[t(314)])};var _g;class vr{constructor(A){pt(this,"name","livekit-noise-filter"),pt(this,"processedTrack"),pt(this,"trackSettings"),pt(this,"originalTrack"),mt(this,_g,void 0),pt(this,"init",async e=>{console.debug("initializing noise processor"),this.originalTrack=e.track,this.trackSettings=e.track.getSettings(),e.audioContext.sampleRate!==this.trackSettings.sampleRate&&console.debug("sample rate mismatch, reapplying"),await e.track.applyConstraints({...this.trackSettings,echoCancellation:!1,autoGainControl:!1,noiseSuppression:!1,sampleRate:e.audioContext.sampleRate}),XA(this,_g)||Ng(this,_g,new GQ),await XA(this,_g).init(),this.processedTrack=(await XA(this,_g).connect(e.audioContext,new MediaStream([e.track]))).getAudioTracks()[0]}),pt(this,"restart",async e=>{if(!XA(this,_g))throw Error("cannot restart without having initialized first");console.debug("restarting noise cancellation"),this.processedTrack=(await XA(this,_g).restart(new MediaStream([e.track]))).getAudioTracks()[0]}),pt(this,"destroy",async()=>{var e,g;(e=XA(this,_g))==null||e.dispose(),await((g=this.originalTrack)==null?void 0:g.applyConstraints(this.trackSettings))}),Ng(this,_g,new GQ)}static isSupported(){return GQ.isSupported()}async onPublish(A){await XA(this,_g).enable(A),await XA(this,_g).setEnabled(!0)}async setEnabled(A){await XA(this,_g).setEnabled(A)}}_g=new WeakMap;const jl=vr.isSupported,Wl=()=>new vr;class CI{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return CI.instance||(CI.instance=new CI),CI.instance}async acquire(){if(this.refCount++,!this.audioContext)try{const A=window.AudioContext||window.webkitAudioContext;if(!A)return console.warn("[SharedAudioContext] Web Audio API not supported"),null;this.audioContext=new A,console.log("[SharedAudioContext] Created shared AudioContext")}catch(A){return console.warn("[SharedAudioContext] Failed to create AudioContext:",A),null}return await this.ensureResumed(),this.audioContext}release(){this.refCount=Math.max(0,this.refCount-1),this.refCount===0&&console.log("[SharedAudioContext] All references released, context kept alive for reuse")}forceClose(){if(this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null,this.refCount=0,console.log("[SharedAudioContext] Force closed")}}getContext(){return this.audioContext}async ensureResumed(){if(!this.audioContext)return!1;if(this.audioContext.state==="suspended"){this.resumePromise||(this.resumePromise=this.audioContext.resume().finally(()=>{this.resumePromise=null}));try{await this.resumePromise}catch{return!1}}return this.audioContext.state==="running"}isRunning(){return this.audioContext!==null&&this.audioContext.state==="running"}getState(){var A;return((A=this.audioContext)==null?void 0:A.state)??null}getSampleRate(){var A;return((A=this.audioContext)==null?void 0:A.sampleRate)??44100}getCurrentTime(){var A;return((A=this.audioContext)==null?void 0:A.currentTime)??0}getDestination(){var A;return((A=this.audioContext)==null?void 0:A.destination)??null}}const Ct=CI.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{Ct.forceClose()});const Jr=jl()?Wl():null,Qg=class Qg 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,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.agentAudioElements=[],this.unmuteTimer=null,this.speakingHandler=null,this.fadeContext=null,this.fadeContextAcquired=!1,this.fadeGains=new Map,this.fadeSetupPromise=null,this.noiseFilterAttached=!1}static isAgentIdentity(A){return A.includes("agent")||A.includes("voice-assistant")||A.includes("AJ_")}set serviceUrl(A){this._serviceUrl=A}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(A){this.callStatus=A,this.dispatchEvent(new CustomEvent("status-changed",{detail:A}))}async makeCall({agentId:A,user_identity:e}){var g;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 i=new II({webAudioMix:!1,dynacast:!0,adaptiveStream:!0});this.room=i,this.setupRoomEventListeners(i);const I=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{user_identity:e,agent_id:A,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})});if(!I.ok){const s=await I.text(),B=new Error(`Failed to get room token: ${I.status} ${s}`);throw B.status=I.status,B}const{token:C,url:o,room_name:a,user_identity:Q}=await I.json();this.roomName=a,this.userIdentity=Q;const n={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};await Promise.all([i.localParticipant.setMicrophoneEnabled(!0,n).then(()=>{this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),this.attachNoiseFilter(i)}).catch(s=>{console.warn("Could not enable microphone:",s),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}),i.connect(o,C)]),await new Promise(s=>{const B=setTimeout(()=>{i.off(tA.ParticipantConnected,E),s()},2e3),E=d=>{Qg.isAgentIdentity(d.identity)&&(clearTimeout(B),i.off(tA.ParticipantConnected,E),s())};for(const d of i.remoteParticipants.values())if(Qg.isAgentIdentity(d.identity)){clearTimeout(B),s();return}i.on(tA.ParticipantConnected,E)}),this.updateStatus("connected"),this.isReady=!0;for(const s of i.localParticipant.audioTrackPublications.values())(g=s.track)!=null&&g.mediaStreamTrack&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:s.track.mediaStreamTrack}));this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:a,identity:Q}}))}catch(i){this.error=`Connection failed: ${i instanceof Error?i.message:String(i)}`,this.updateStatus("error"),this.isReady=!1,this.room=null;const I=typeof(i==null?void 0:i.status)=="number"?i.status:null;this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error,status:I}}))}}}setupRoomEventListeners(A){A.on(tA.Disconnected,()=>{this.callStatus!=="disconnected"&&this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.noiseFilterAttached=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(A.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.room=null,this.dispatchEvent(new CustomEvent("disconnected"))}),A.on(tA.ParticipantConnected,e=>{this.connectedParticipants=[...this.connectedParticipants,e.identity];const g=Qg.isAgentIdentity(e.identity);g&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:e.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:e.identity,isAgent:g}}))}),A.on(tA.ParticipantDisconnected,e=>{this.connectedParticipants=this.connectedParticipants.filter(i=>i!==e.identity);const g=Qg.isAgentIdentity(e.identity);g&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:e.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:e.identity,isAgent:g}}))}),A.on(tA.TrackSubscribed,(e,g,i)=>{if(e.kind==="audio"){const I=e.attach();document.body.appendChild(I),Qg.isAgentIdentity(i.identity)&&(this.agentAudioElements.push(I),this.setupAgentAudioFade(I)),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:i.identity,element:I}}));const C=e.mediaStreamTrack;C&&this.dispatchEvent(new CustomEvent("audio-track",{detail:C}))}}),A.on(tA.TrackUnsubscribed,(e,g,i)=>{const I=e.detach();for(const C of I){const o=this.fadeGains.get(C);if(o){try{o.source.disconnect()}catch{}try{o.gain.disconnect()}catch{}this.fadeGains.delete(C)}}this.agentAudioElements=this.agentAudioElements.filter(C=>!I.includes(C)),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:i.identity}}))}),A.on(tA.MediaDevicesError,e=>{this.error=`Media device error: ${e.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),A.on(tA.AudioPlaybackStatusChanged,async()=>{A.canPlaybackAudio||this.connectedParticipants.some(g=>Qg.isAgentIdentity(g))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:A.canPlaybackAudio}}))}),A.on(tA.DataReceived,(e,g)=>{try{const i=JSON.parse(new TextDecoder().decode(e));i.type==="transcript"?this.dispatchEvent(new CustomEvent("transcription",{detail:{speaker:i.speaker,text:i.text,timestamp:i.timestamp},bubbles:!0,composed:!0})):(!g||Qg.isAgentIdentity(g.identity))&&this.dispatchEvent(new CustomEvent("agent-command",{detail:i}))}catch{}}),this.speakingHandler=e=>{e?(this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.rampAgentGain(0,Qg.FADEOUT_TC)):this.unmuteTimer=setTimeout(()=>{this.unmuteTimer=null,this.rampAgentGain(1,Qg.FADEIN_TC)},Qg.UNMUTE_HOLDOVER_MS)},A.localParticipant.on("isSpeakingChanged",this.speakingHandler)}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.noiseFilterAttached=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),this.attachNoiseFilter(this.room))}catch(A){this.error=`Failed to toggle microphone: ${A instanceof Error?A.message:String(A)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}attachNoiseFilter(A){if(!Jr||this.noiseFilterAttached)return;const e=Array.from(A.localParticipant.audioTrackPublications.values()).find(i=>i.kind==="audio"),g=e==null?void 0:e.track;g&&g.setProcessor(Jr).then(()=>{this.noiseFilterAttached=!0,console.log("[NoiseFilter] ai-coustics Voice Focus attached")}).catch(i=>{console.warn("[NoiseFilter] Failed to attach, keeping native NS:",i)})}setupAgentAudioFade(A){const e=(async()=>{try{if(this.fadeContext)await Ct.ensureResumed();else{const I=await Ct.acquire();if(!I){console.warn("[CallManager] Could not acquire shared AudioContext for fade");return}this.fadeContext=I,this.fadeContextAcquired=!0}const g=this.fadeContext.createMediaElementSource(A),i=this.fadeContext.createGain();g.connect(i),i.connect(this.fadeContext.destination),this.fadeGains.set(A,{source:g,gain:i})}catch(g){console.warn("[CallManager] Audio fade setup failed:",g)}})();this.fadeSetupPromise=e,e.then(()=>{this.fadeSetupPromise=null})}rampAgentGain(A,e,g=!1){const i=this.fadeContext;if(i&&i.state==="running"&&this.fadeGains.size>0)for(const{gain:I}of this.fadeGains.values())I.gain.cancelScheduledValues(i.currentTime),I.gain.setValueAtTime(I.gain.value,i.currentTime),I.gain.setTargetAtTime(A,i.currentTime,e);else if(this.fadeSetupPromise)this.fadeSetupPromise.then(()=>this.rampAgentGain(A,e));else if(!g&&i&&i.state==="suspended"&&this.fadeGains.size>0)Ct.ensureResumed().then(I=>{if(I)this.rampAgentGain(A,e,!0);else for(const C of this.agentAudioElements)C.volume=A});else for(const I of this.agentAudioElements)I.volume=A}cleanupFadeContext(){this.agentAudioElements=[];for(const{source:A,gain:e}of this.fadeGains.values()){try{A.disconnect()}catch{}try{e.disconnect()}catch{}}this.fadeGains.clear(),this.fadeSetupPromise=null,this.fadeContextAcquired&&(Ct.release(),this.fadeContextAcquired=!1),this.fadeContext=null}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const A=JSON.stringify({type:"audio_enabled"}),g=new TextEncoder().encode(A);await this.room.localParticipant.publishData(g,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(A){this.error=`Failed to enable audio: ${A instanceof Error?A.message:String(A)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async sendDataToAgent(A){if(!this.room){console.warn("[LiveKitCallManager] Cannot send data: no room");return}const g=new TextEncoder().encode(JSON.stringify(A));await this.room.localParticipant.publishData(g,{reliable:!0})}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const A=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(A.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),A.removeAllListeners(),this.noiseFilterAttached=!1,requestAnimationFrame(()=>{setTimeout(async()=>{try{await A.disconnect()}catch(e){console.warn("Error during room disconnect:",e)}},0)})}};Qg.UNMUTE_HOLDOVER_MS=350,Qg.FADEOUT_TC=.045,Qg.FADEIN_TC=.03;let pi=Qg;/**
|
|
148
148
|
* @license
|
|
149
149
|
* Copyright 2010-2025 Three.js Authors
|
|
150
150
|
* SPDX-License-Identifier: MIT
|
|
151
|
-
*/const MQ="182",Xl=0,Yr=1,Zl=2,Bo=1,zl=2,iC=3,bt=0,tg=1,Nt=2,St=0,oI=1,FQ=2,Tr=3,qr=4,$l=5,pi=100,Af=101,ef=102,gf=103,tf=104,If=200,Cf=201,of=202,af=203,UQ=204,LQ=205,Qf=206,nf=207,sf=208,Bf=209,Ef=210,rf=211,cf=212,hf=213,df=214,KQ=0,vQ=1,JQ=2,aI=3,YQ=4,TQ=5,qQ=6,HQ=7,Hr=0,xf=1,lf=2,ot=0,Pr=1,Or=2,Vr=3,jr=4,Wr=5,Xr=6,Zr=7,zr=300,mi=301,QI=302,PQ=303,OQ=304,Eo=306,VQ=1e3,kt=1001,jQ=1002,$e=1003,ff=1004,ro=1005,Ag=1006,WQ=1007,yi=1008,Sg=1009,$r=1010,A0=1011,IC=1012,XQ=1013,at=1014,Qt=1015,Rt=1016,ZQ=1017,zQ=1018,CC=1020,e0=35902,g0=35899,t0=1021,i0=1022,Hg=1023,Gt=1026,bi=1027,I0=1028,$Q=1029,nI=1030,An=1031,en=1033,co=33776,ho=33777,xo=33778,lo=33779,gn=35840,tn=35841,In=35842,Cn=35843,on=36196,an=37492,Qn=37496,nn=37488,sn=37489,Bn=37490,En=37491,rn=37808,cn=37809,hn=37810,dn=37811,xn=37812,ln=37813,fn=37814,un=37815,Dn=37816,_n=37817,wn=37818,pn=37819,mn=37820,yn=37821,bn=36492,Nn=36494,Sn=36495,kn=36283,Rn=36284,Gn=36285,Mn=36286,uf=3200,Df=0,_f=1,ii="",kg="srgb",sI="srgb-linear",fo="linear",re="srgb",BI=7680,C0=519,wf=512,pf=513,mf=514,Fn=515,yf=516,bf=517,Un=518,Nf=519,o0=35044,a0="300 es",nt=2e3,uo=2001;function Q0(t){for(let A=t.length-1;A>=0;--A)if(t[A]>=65535)return!0;return!1}function Do(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Sf(){const t=Do("canvas");return t.style.display="block",t}const n0={};function s0(...t){const A="THREE."+t.shift();console.log(A,...t)}function LA(...t){const A="THREE."+t.shift();console.warn(A,...t)}function ae(...t){const A="THREE."+t.shift();console.error(A,...t)}function oC(...t){const A=t.join(" ");A in n0||(n0[A]=!0,LA(...t))}function kf(t,A,e){return new Promise(function(g,i){function I(){switch(t.clientWaitSync(A,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(I,e);break;default:g()}}setTimeout(I,e)})}class EI{addEventListener(A,e){this._listeners===void 0&&(this._listeners={});const g=this._listeners;g[A]===void 0&&(g[A]=[]),g[A].indexOf(e)===-1&&g[A].push(e)}hasEventListener(A,e){const g=this._listeners;return g===void 0?!1:g[A]!==void 0&&g[A].indexOf(e)!==-1}removeEventListener(A,e){const g=this._listeners;if(g===void 0)return;const i=g[A];if(i!==void 0){const I=i.indexOf(e);I!==-1&&i.splice(I,1)}}dispatchEvent(A){const e=this._listeners;if(e===void 0)return;const g=e[A.type];if(g!==void 0){A.target=this;const i=g.slice(0);for(let I=0,C=i.length;I<C;I++)i[I].call(this,A);A.target=null}}}const eg=["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"],Ln=Math.PI/180,Kn=180/Math.PI;function aC(){const t=Math.random()*4294967295|0,A=Math.random()*4294967295|0,e=Math.random()*4294967295|0,g=Math.random()*4294967295|0;return(eg[t&255]+eg[t>>8&255]+eg[t>>16&255]+eg[t>>24&255]+"-"+eg[A&255]+eg[A>>8&255]+"-"+eg[A>>16&15|64]+eg[A>>24&255]+"-"+eg[e&63|128]+eg[e>>8&255]+"-"+eg[e>>16&255]+eg[e>>24&255]+eg[g&255]+eg[g>>8&255]+eg[g>>16&255]+eg[g>>24&255]).toLowerCase()}function te(t,A,e){return Math.max(A,Math.min(e,t))}function Rf(t,A){return(t%A+A)%A}function vn(t,A,e){return(1-e)*t+e*A}function QC(t,A){switch(A.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function hg(t,A){switch(A.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}class Be{constructor(A=0,e=0){Be.prototype.isVector2=!0,this.x=A,this.y=e}get width(){return this.x}set width(A){this.x=A}get height(){return this.y}set height(A){this.y=A}set(A,e){return this.x=A,this.y=e,this}setScalar(A){return this.x=A,this.y=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y)}copy(A){return this.x=A.x,this.y=A.y,this}add(A){return this.x+=A.x,this.y+=A.y,this}addScalar(A){return this.x+=A,this.y+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this}subScalar(A){return this.x-=A,this.y-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this}multiply(A){return this.x*=A.x,this.y*=A.y,this}multiplyScalar(A){return this.x*=A,this.y*=A,this}divide(A){return this.x/=A.x,this.y/=A.y,this}divideScalar(A){return this.multiplyScalar(1/A)}applyMatrix3(A){const e=this.x,g=this.y,i=A.elements;return this.x=i[0]*e+i[3]*g+i[6],this.y=i[1]*e+i[4]*g+i[7],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y}cross(A){return this.x*A.y-this.y*A.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(A){const e=Math.sqrt(this.lengthSq()*A.lengthSq());if(e===0)return Math.PI/2;const g=this.dot(A)/e;return Math.acos(te(g,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const e=this.x-A.x,g=this.y-A.y;return e*e+g*g}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this}equals(A){return A.x===this.x&&A.y===this.y}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this}rotateAround(A,e){const g=Math.cos(e),i=Math.sin(e),I=this.x-A.x,C=this.y-A.y;return this.x=I*g-C*i+A.x,this.y=I*i+C*g+A.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class nC{constructor(A=0,e=0,g=0,i=1){this.isQuaternion=!0,this._x=A,this._y=e,this._z=g,this._w=i}static slerpFlat(A,e,g,i,I,C,o){let a=g[i+0],Q=g[i+1],n=g[i+2],s=g[i+3],B=I[C+0],E=I[C+1],d=I[C+2],c=I[C+3];if(o<=0){A[e+0]=a,A[e+1]=Q,A[e+2]=n,A[e+3]=s;return}if(o>=1){A[e+0]=B,A[e+1]=E,A[e+2]=d,A[e+3]=c;return}if(s!==c||a!==B||Q!==E||n!==d){let h=a*B+Q*E+n*d+s*c;h<0&&(B=-B,E=-E,d=-d,c=-c,h=-h);let r=1-o;if(h<.9995){const f=Math.acos(h),_=Math.sin(f);r=Math.sin(r*f)/_,o=Math.sin(o*f)/_,a=a*r+B*o,Q=Q*r+E*o,n=n*r+d*o,s=s*r+c*o}else{a=a*r+B*o,Q=Q*r+E*o,n=n*r+d*o,s=s*r+c*o;const f=1/Math.sqrt(a*a+Q*Q+n*n+s*s);a*=f,Q*=f,n*=f,s*=f}}A[e]=a,A[e+1]=Q,A[e+2]=n,A[e+3]=s}static multiplyQuaternionsFlat(A,e,g,i,I,C){const o=g[i],a=g[i+1],Q=g[i+2],n=g[i+3],s=I[C],B=I[C+1],E=I[C+2],d=I[C+3];return A[e]=o*d+n*s+a*E-Q*B,A[e+1]=a*d+n*B+Q*s-o*E,A[e+2]=Q*d+n*E+o*B-a*s,A[e+3]=n*d-o*s-a*B-Q*E,A}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get w(){return this._w}set w(A){this._w=A,this._onChangeCallback()}set(A,e,g,i){return this._x=A,this._y=e,this._z=g,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(A){return this._x=A.x,this._y=A.y,this._z=A.z,this._w=A.w,this._onChangeCallback(),this}setFromEuler(A,e=!0){const g=A._x,i=A._y,I=A._z,C=A._order,o=Math.cos,a=Math.sin,Q=o(g/2),n=o(i/2),s=o(I/2),B=a(g/2),E=a(i/2),d=a(I/2);switch(C){case"XYZ":this._x=B*n*s+Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s-B*E*d;break;case"YXZ":this._x=B*n*s+Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s+B*E*d;break;case"ZXY":this._x=B*n*s-Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s-B*E*d;break;case"ZYX":this._x=B*n*s-Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s+B*E*d;break;case"YZX":this._x=B*n*s+Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s-B*E*d;break;case"XZY":this._x=B*n*s-Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s+B*E*d;break;default:LA("Quaternion: .setFromEuler() encountered an unknown order: "+C)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(A,e){const g=e/2,i=Math.sin(g);return this._x=A.x*i,this._y=A.y*i,this._z=A.z*i,this._w=Math.cos(g),this._onChangeCallback(),this}setFromRotationMatrix(A){const e=A.elements,g=e[0],i=e[4],I=e[8],C=e[1],o=e[5],a=e[9],Q=e[2],n=e[6],s=e[10],B=g+o+s;if(B>0){const E=.5/Math.sqrt(B+1);this._w=.25/E,this._x=(n-a)*E,this._y=(I-Q)*E,this._z=(C-i)*E}else if(g>o&&g>s){const E=2*Math.sqrt(1+g-o-s);this._w=(n-a)/E,this._x=.25*E,this._y=(i+C)/E,this._z=(I+Q)/E}else if(o>s){const E=2*Math.sqrt(1+o-g-s);this._w=(I-Q)/E,this._x=(i+C)/E,this._y=.25*E,this._z=(a+n)/E}else{const E=2*Math.sqrt(1+s-g-o);this._w=(C-i)/E,this._x=(I+Q)/E,this._y=(a+n)/E,this._z=.25*E}return this._onChangeCallback(),this}setFromUnitVectors(A,e){let g=A.dot(e)+1;return g<1e-8?(g=0,Math.abs(A.x)>Math.abs(A.z)?(this._x=-A.y,this._y=A.x,this._z=0,this._w=g):(this._x=0,this._y=-A.z,this._z=A.y,this._w=g)):(this._x=A.y*e.z-A.z*e.y,this._y=A.z*e.x-A.x*e.z,this._z=A.x*e.y-A.y*e.x,this._w=g),this.normalize()}angleTo(A){return 2*Math.acos(Math.abs(te(this.dot(A),-1,1)))}rotateTowards(A,e){const g=this.angleTo(A);if(g===0)return this;const i=Math.min(1,e/g);return this.slerp(A,i),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(A){return this._x*A._x+this._y*A._y+this._z*A._z+this._w*A._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 A=this.length();return A===0?(this._x=0,this._y=0,this._z=0,this._w=1):(A=1/A,this._x=this._x*A,this._y=this._y*A,this._z=this._z*A,this._w=this._w*A),this._onChangeCallback(),this}multiply(A){return this.multiplyQuaternions(this,A)}premultiply(A){return this.multiplyQuaternions(A,this)}multiplyQuaternions(A,e){const g=A._x,i=A._y,I=A._z,C=A._w,o=e._x,a=e._y,Q=e._z,n=e._w;return this._x=g*n+C*o+i*Q-I*a,this._y=i*n+C*a+I*o-g*Q,this._z=I*n+C*Q+g*a-i*o,this._w=C*n-g*o-i*a-I*Q,this._onChangeCallback(),this}slerp(A,e){if(e<=0)return this;if(e>=1)return this.copy(A);let g=A._x,i=A._y,I=A._z,C=A._w,o=this.dot(A);o<0&&(g=-g,i=-i,I=-I,C=-C,o=-o);let a=1-e;if(o<.9995){const Q=Math.acos(o),n=Math.sin(Q);a=Math.sin(a*Q)/n,e=Math.sin(e*Q)/n,this._x=this._x*a+g*e,this._y=this._y*a+i*e,this._z=this._z*a+I*e,this._w=this._w*a+C*e,this._onChangeCallback()}else this._x=this._x*a+g*e,this._y=this._y*a+i*e,this._z=this._z*a+I*e,this._w=this._w*a+C*e,this.normalize();return this}slerpQuaternions(A,e,g){return this.copy(A).slerp(e,g)}random(){const A=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),g=Math.random(),i=Math.sqrt(1-g),I=Math.sqrt(g);return this.set(i*Math.sin(A),i*Math.cos(A),I*Math.sin(e),I*Math.cos(e))}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._w===this._w}fromArray(A,e=0){return this._x=A[e],this._y=A[e+1],this._z=A[e+2],this._w=A[e+3],this._onChangeCallback(),this}toArray(A=[],e=0){return A[e]=this._x,A[e+1]=this._y,A[e+2]=this._z,A[e+3]=this._w,A}fromBufferAttribute(A,e){return this._x=A.getX(e),this._y=A.getY(e),this._z=A.getZ(e),this._w=A.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class J{constructor(A=0,e=0,g=0){J.prototype.isVector3=!0,this.x=A,this.y=e,this.z=g}set(A,e,g){return g===void 0&&(g=this.z),this.x=A,this.y=e,this.z=g,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this.z=A.z+e.z,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this.z+=A.z*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this.z=A.z-e.z,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this}multiplyVectors(A,e){return this.x=A.x*e.x,this.y=A.y*e.y,this.z=A.z*e.z,this}applyEuler(A){return this.applyQuaternion(B0.setFromEuler(A))}applyAxisAngle(A,e){return this.applyQuaternion(B0.setFromAxisAngle(A,e))}applyMatrix3(A){const e=this.x,g=this.y,i=this.z,I=A.elements;return this.x=I[0]*e+I[3]*g+I[6]*i,this.y=I[1]*e+I[4]*g+I[7]*i,this.z=I[2]*e+I[5]*g+I[8]*i,this}applyNormalMatrix(A){return this.applyMatrix3(A).normalize()}applyMatrix4(A){const e=this.x,g=this.y,i=this.z,I=A.elements,C=1/(I[3]*e+I[7]*g+I[11]*i+I[15]);return this.x=(I[0]*e+I[4]*g+I[8]*i+I[12])*C,this.y=(I[1]*e+I[5]*g+I[9]*i+I[13])*C,this.z=(I[2]*e+I[6]*g+I[10]*i+I[14])*C,this}applyQuaternion(A){const e=this.x,g=this.y,i=this.z,I=A.x,C=A.y,o=A.z,a=A.w,Q=2*(C*i-o*g),n=2*(o*e-I*i),s=2*(I*g-C*e);return this.x=e+a*Q+C*s-o*n,this.y=g+a*n+o*Q-I*s,this.z=i+a*s+I*n-C*Q,this}project(A){return this.applyMatrix4(A.matrixWorldInverse).applyMatrix4(A.projectionMatrix)}unproject(A){return this.applyMatrix4(A.projectionMatrixInverse).applyMatrix4(A.matrixWorld)}transformDirection(A){const e=this.x,g=this.y,i=this.z,I=A.elements;return this.x=I[0]*e+I[4]*g+I[8]*i,this.y=I[1]*e+I[5]*g+I[9]*i,this.z=I[2]*e+I[6]*g+I[10]*i,this.normalize()}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this}divideScalar(A){return this.multiplyScalar(1/A)}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this.z=te(this.z,A.z,e.z),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this.z=te(this.z,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y+this.z*A.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(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this.z+=(A.z-this.z)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this.z=A.z+(e.z-A.z)*g,this}cross(A){return this.crossVectors(this,A)}crossVectors(A,e){const g=A.x,i=A.y,I=A.z,C=e.x,o=e.y,a=e.z;return this.x=i*a-I*o,this.y=I*C-g*a,this.z=g*o-i*C,this}projectOnVector(A){const e=A.lengthSq();if(e===0)return this.set(0,0,0);const g=A.dot(this)/e;return this.copy(A).multiplyScalar(g)}projectOnPlane(A){return Jn.copy(this).projectOnVector(A),this.sub(Jn)}reflect(A){return this.sub(Jn.copy(A).multiplyScalar(2*this.dot(A)))}angleTo(A){const e=Math.sqrt(this.lengthSq()*A.lengthSq());if(e===0)return Math.PI/2;const g=this.dot(A)/e;return Math.acos(te(g,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const e=this.x-A.x,g=this.y-A.y,i=this.z-A.z;return e*e+g*g+i*i}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)+Math.abs(this.z-A.z)}setFromSpherical(A){return this.setFromSphericalCoords(A.radius,A.phi,A.theta)}setFromSphericalCoords(A,e,g){const i=Math.sin(e)*A;return this.x=i*Math.sin(g),this.y=Math.cos(e)*A,this.z=i*Math.cos(g),this}setFromCylindrical(A){return this.setFromCylindricalCoords(A.radius,A.theta,A.y)}setFromCylindricalCoords(A,e,g){return this.x=A*Math.sin(e),this.y=g,this.z=A*Math.cos(e),this}setFromMatrixPosition(A){const e=A.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(A){const e=this.setFromMatrixColumn(A,0).length(),g=this.setFromMatrixColumn(A,1).length(),i=this.setFromMatrixColumn(A,2).length();return this.x=e,this.y=g,this.z=i,this}setFromMatrixColumn(A,e){return this.fromArray(A.elements,e*4)}setFromMatrix3Column(A,e){return this.fromArray(A.elements,e*3)}setFromEuler(A){return this.x=A._x,this.y=A._y,this.z=A._z,this}setFromColor(A){return this.x=A.r,this.y=A.g,this.z=A.b,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this.z=A[e+2],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A[e+2]=this.z,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this.z=A.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const A=Math.random()*Math.PI*2,e=Math.random()*2-1,g=Math.sqrt(1-e*e);return this.x=g*Math.cos(A),this.y=e,this.z=g*Math.sin(A),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Jn=new J,B0=new nC;class YA{constructor(A,e,g,i,I,C,o,a,Q){YA.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],A!==void 0&&this.set(A,e,g,i,I,C,o,a,Q)}set(A,e,g,i,I,C,o,a,Q){const n=this.elements;return n[0]=A,n[1]=i,n[2]=o,n[3]=e,n[4]=I,n[5]=a,n[6]=g,n[7]=C,n[8]=Q,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(A){const e=this.elements,g=A.elements;return e[0]=g[0],e[1]=g[1],e[2]=g[2],e[3]=g[3],e[4]=g[4],e[5]=g[5],e[6]=g[6],e[7]=g[7],e[8]=g[8],this}extractBasis(A,e,g){return A.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),g.setFromMatrix3Column(this,2),this}setFromMatrix4(A){const e=A.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,e){const g=A.elements,i=e.elements,I=this.elements,C=g[0],o=g[3],a=g[6],Q=g[1],n=g[4],s=g[7],B=g[2],E=g[5],d=g[8],c=i[0],h=i[3],r=i[6],f=i[1],_=i[4],l=i[7],D=i[2],p=i[5],y=i[8];return I[0]=C*c+o*f+a*D,I[3]=C*h+o*_+a*p,I[6]=C*r+o*l+a*y,I[1]=Q*c+n*f+s*D,I[4]=Q*h+n*_+s*p,I[7]=Q*r+n*l+s*y,I[2]=B*c+E*f+d*D,I[5]=B*h+E*_+d*p,I[8]=B*r+E*l+d*y,this}multiplyScalar(A){const e=this.elements;return e[0]*=A,e[3]*=A,e[6]*=A,e[1]*=A,e[4]*=A,e[7]*=A,e[2]*=A,e[5]*=A,e[8]*=A,this}determinant(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8];return e*C*n-e*o*Q-g*I*n+g*o*a+i*I*Q-i*C*a}invert(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8],s=n*C-o*Q,B=o*a-n*I,E=Q*I-C*a,d=e*s+g*B+i*E;if(d===0)return this.set(0,0,0,0,0,0,0,0,0);const c=1/d;return A[0]=s*c,A[1]=(i*Q-n*g)*c,A[2]=(o*g-i*C)*c,A[3]=B*c,A[4]=(n*e-i*a)*c,A[5]=(i*I-o*e)*c,A[6]=E*c,A[7]=(g*a-Q*e)*c,A[8]=(C*e-g*I)*c,this}transpose(){let A;const e=this.elements;return A=e[1],e[1]=e[3],e[3]=A,A=e[2],e[2]=e[6],e[6]=A,A=e[5],e[5]=e[7],e[7]=A,this}getNormalMatrix(A){return this.setFromMatrix4(A).invert().transpose()}transposeIntoArray(A){const e=this.elements;return A[0]=e[0],A[1]=e[3],A[2]=e[6],A[3]=e[1],A[4]=e[4],A[5]=e[7],A[6]=e[2],A[7]=e[5],A[8]=e[8],this}setUvTransform(A,e,g,i,I,C,o){const a=Math.cos(I),Q=Math.sin(I);return this.set(g*a,g*Q,-g*(a*C+Q*o)+C+A,-i*Q,i*a,-i*(-Q*C+a*o)+o+e,0,0,1),this}scale(A,e){return this.premultiply(Yn.makeScale(A,e)),this}rotate(A){return this.premultiply(Yn.makeRotation(-A)),this}translate(A,e){return this.premultiply(Yn.makeTranslation(A,e)),this}makeTranslation(A,e){return A.isVector2?this.set(1,0,A.x,0,1,A.y,0,0,1):this.set(1,0,A,0,1,e,0,0,1),this}makeRotation(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,-g,0,g,e,0,0,0,1),this}makeScale(A,e){return this.set(A,0,0,0,e,0,0,0,1),this}equals(A){const e=this.elements,g=A.elements;for(let i=0;i<9;i++)if(e[i]!==g[i])return!1;return!0}fromArray(A,e=0){for(let g=0;g<9;g++)this.elements[g]=A[g+e];return this}toArray(A=[],e=0){const g=this.elements;return A[e]=g[0],A[e+1]=g[1],A[e+2]=g[2],A[e+3]=g[3],A[e+4]=g[4],A[e+5]=g[5],A[e+6]=g[6],A[e+7]=g[7],A[e+8]=g[8],A}clone(){return new this.constructor().fromArray(this.elements)}}const Yn=new YA,E0=new YA().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),r0=new YA().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Gf(){const t={enabled:!0,workingColorSpace:sI,spaces:{},convert:function(i,I,C){return this.enabled===!1||I===C||!I||!C||(this.spaces[I].transfer===re&&(i.r=Mt(i.r),i.g=Mt(i.g),i.b=Mt(i.b)),this.spaces[I].primaries!==this.spaces[C].primaries&&(i.applyMatrix3(this.spaces[I].toXYZ),i.applyMatrix3(this.spaces[C].fromXYZ)),this.spaces[C].transfer===re&&(i.r=rI(i.r),i.g=rI(i.g),i.b=rI(i.b))),i},workingToColorSpace:function(i,I){return this.convert(i,this.workingColorSpace,I)},colorSpaceToWorking:function(i,I){return this.convert(i,I,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ii?fo:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,I=this.workingColorSpace){return i.fromArray(this.spaces[I].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,I,C){return i.copy(this.spaces[I].toXYZ).multiply(this.spaces[C].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,I){return oC("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(i,I)},toWorkingColorSpace:function(i,I){return oC("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(i,I)}},A=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],g=[.3127,.329];return t.define({[sI]:{primaries:A,whitePoint:g,transfer:fo,toXYZ:E0,fromXYZ:r0,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:kg},outputColorSpaceConfig:{drawingBufferColorSpace:kg}},[kg]:{primaries:A,whitePoint:g,transfer:re,toXYZ:E0,fromXYZ:r0,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:kg}}}),t}const Ce=Gf();function Mt(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function rI(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let cI;class Mf{static getDataURL(A,e="image/png"){if(/^data:/i.test(A.src)||typeof HTMLCanvasElement>"u")return A.src;let g;if(A instanceof HTMLCanvasElement)g=A;else{cI===void 0&&(cI=Do("canvas")),cI.width=A.width,cI.height=A.height;const i=cI.getContext("2d");A instanceof ImageData?i.putImageData(A,0,0):i.drawImage(A,0,0,A.width,A.height),g=cI}return g.toDataURL(e)}static sRGBToLinear(A){if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap){const e=Do("canvas");e.width=A.width,e.height=A.height;const g=e.getContext("2d");g.drawImage(A,0,0,A.width,A.height);const i=g.getImageData(0,0,A.width,A.height),I=i.data;for(let C=0;C<I.length;C++)I[C]=Mt(I[C]/255)*255;return g.putImageData(i,0,0),e}else if(A.data){const e=A.data.slice(0);for(let g=0;g<e.length;g++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[g]=Math.floor(Mt(e[g]/255)*255):e[g]=Mt(e[g]);return{data:e,width:A.width,height:A.height}}else return LA("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),A}}let Ff=0;class Tn{constructor(A=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ff++}),this.uuid=aC(),this.data=A,this.dataReady=!0,this.version=0}getSize(A){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?A.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?A.set(e.displayHeight,e.displayWidth,0):e!==null?A.set(e.width,e.height,e.depth||0):A.set(0,0,0),A}set needsUpdate(A){A===!0&&this.version++}toJSON(A){const e=A===void 0||typeof A=="string";if(!e&&A.images[this.uuid]!==void 0)return A.images[this.uuid];const g={uuid:this.uuid,url:""},i=this.data;if(i!==null){let I;if(Array.isArray(i)){I=[];for(let C=0,o=i.length;C<o;C++)i[C].isDataTexture?I.push(qn(i[C].image)):I.push(qn(i[C]))}else I=qn(i);g.url=I}return e||(A.images[this.uuid]=g),g}}function qn(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?Mf.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(LA("Texture: Unable to serialize Texture."),{})}let Uf=0;const Hn=new J;class ig extends EI{constructor(A=ig.DEFAULT_IMAGE,e=ig.DEFAULT_MAPPING,g=kt,i=kt,I=Ag,C=yi,o=Hg,a=Sg,Q=ig.DEFAULT_ANISOTROPY,n=ii){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Uf++}),this.uuid=aC(),this.name="",this.source=new Tn(A),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=g,this.wrapT=i,this.magFilter=I,this.minFilter=C,this.anisotropy=Q,this.format=o,this.internalFormat=null,this.type=a,this.offset=new Be(0,0),this.repeat=new Be(1,1),this.center=new Be(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new YA,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=n,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(A&&A.depth&&A.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Hn).x}get height(){return this.source.getSize(Hn).y}get depth(){return this.source.getSize(Hn).z}get image(){return this.source.data}set image(A=null){this.source.data=A}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(A,e){this.updateRanges.push({start:A,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(A){return this.name=A.name,this.source=A.source,this.mipmaps=A.mipmaps.slice(0),this.mapping=A.mapping,this.channel=A.channel,this.wrapS=A.wrapS,this.wrapT=A.wrapT,this.magFilter=A.magFilter,this.minFilter=A.minFilter,this.anisotropy=A.anisotropy,this.format=A.format,this.internalFormat=A.internalFormat,this.type=A.type,this.offset.copy(A.offset),this.repeat.copy(A.repeat),this.center.copy(A.center),this.rotation=A.rotation,this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrix.copy(A.matrix),this.generateMipmaps=A.generateMipmaps,this.premultiplyAlpha=A.premultiplyAlpha,this.flipY=A.flipY,this.unpackAlignment=A.unpackAlignment,this.colorSpace=A.colorSpace,this.renderTarget=A.renderTarget,this.isRenderTargetTexture=A.isRenderTargetTexture,this.isArrayTexture=A.isArrayTexture,this.userData=JSON.parse(JSON.stringify(A.userData)),this.needsUpdate=!0,this}setValues(A){for(const e in A){const g=A[e];if(g===void 0){LA(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){LA(`Texture.setValues(): property '${e}' does not exist.`);continue}i&&g&&i.isVector2&&g.isVector2||i&&g&&i.isVector3&&g.isVector3||i&&g&&i.isMatrix3&&g.isMatrix3?i.copy(g):this[e]=g}}toJSON(A){const e=A===void 0||typeof A=="string";if(!e&&A.textures[this.uuid]!==void 0)return A.textures[this.uuid];const g={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(A).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&&(g.userData=this.userData),e||(A.textures[this.uuid]=g),g}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(A){if(this.mapping!==zr)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case VQ:A.x=A.x-Math.floor(A.x);break;case kt:A.x=A.x<0?0:1;break;case jQ:Math.abs(Math.floor(A.x)%2)===1?A.x=Math.ceil(A.x)-A.x:A.x=A.x-Math.floor(A.x);break}if(A.y<0||A.y>1)switch(this.wrapT){case VQ:A.y=A.y-Math.floor(A.y);break;case kt:A.y=A.y<0?0:1;break;case jQ:Math.abs(Math.floor(A.y)%2)===1?A.y=Math.ceil(A.y)-A.y:A.y=A.y-Math.floor(A.y);break}return this.flipY&&(A.y=1-A.y),A}set needsUpdate(A){A===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(A){A===!0&&this.pmremVersion++}}ig.DEFAULT_IMAGE=null,ig.DEFAULT_MAPPING=zr,ig.DEFAULT_ANISOTROPY=1;class Ke{constructor(A=0,e=0,g=0,i=1){Ke.prototype.isVector4=!0,this.x=A,this.y=e,this.z=g,this.w=i}get width(){return this.z}set width(A){this.z=A}get height(){return this.w}set height(A){this.w=A}set(A,e,g,i){return this.x=A,this.y=e,this.z=g,this.w=i,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this.w=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setW(A){return this.w=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){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: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this.w=A.w!==void 0?A.w:1,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this.w+=A.w,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this.w+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this.z=A.z+e.z,this.w=A.w+e.w,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this.z+=A.z*e,this.w+=A.w*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this.w-=A.w,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this.w-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this.z=A.z-e.z,this.w=A.w-e.w,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this.w*=A.w,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this.w*=A,this}applyMatrix4(A){const e=this.x,g=this.y,i=this.z,I=this.w,C=A.elements;return this.x=C[0]*e+C[4]*g+C[8]*i+C[12]*I,this.y=C[1]*e+C[5]*g+C[9]*i+C[13]*I,this.z=C[2]*e+C[6]*g+C[10]*i+C[14]*I,this.w=C[3]*e+C[7]*g+C[11]*i+C[15]*I,this}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this.w/=A.w,this}divideScalar(A){return this.multiplyScalar(1/A)}setAxisAngleFromQuaternion(A){this.w=2*Math.acos(A.w);const e=Math.sqrt(1-A.w*A.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=A.x/e,this.y=A.y/e,this.z=A.z/e),this}setAxisAngleFromRotationMatrix(A){let e,g,i,I;const a=A.elements,Q=a[0],n=a[4],s=a[8],B=a[1],E=a[5],d=a[9],c=a[2],h=a[6],r=a[10];if(Math.abs(n-B)<.01&&Math.abs(s-c)<.01&&Math.abs(d-h)<.01){if(Math.abs(n+B)<.1&&Math.abs(s+c)<.1&&Math.abs(d+h)<.1&&Math.abs(Q+E+r-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const _=(Q+1)/2,l=(E+1)/2,D=(r+1)/2,p=(n+B)/4,y=(s+c)/4,k=(d+h)/4;return _>l&&_>D?_<.01?(g=0,i=.707106781,I=.707106781):(g=Math.sqrt(_),i=p/g,I=y/g):l>D?l<.01?(g=.707106781,i=0,I=.707106781):(i=Math.sqrt(l),g=p/i,I=k/i):D<.01?(g=.707106781,i=.707106781,I=0):(I=Math.sqrt(D),g=y/I,i=k/I),this.set(g,i,I,e),this}let f=Math.sqrt((h-d)*(h-d)+(s-c)*(s-c)+(B-n)*(B-n));return Math.abs(f)<.001&&(f=1),this.x=(h-d)/f,this.y=(s-c)/f,this.z=(B-n)/f,this.w=Math.acos((Q+E+r-1)/2),this}setFromMatrixPosition(A){const e=A.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this.w=Math.min(this.w,A.w),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this.w=Math.max(this.w,A.w),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this.z=te(this.z,A.z,e.z),this.w=te(this.w,A.w,e.w),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this.z=te(this.z,A,e),this.w=te(this.w,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y+this.z*A.z+this.w*A.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(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this.z+=(A.z-this.z)*e,this.w+=(A.w-this.w)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this.z=A.z+(e.z-A.z)*g,this.w=A.w+(e.w-A.w)*g,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z&&A.w===this.w}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this.z=A[e+2],this.w=A[e+3],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A[e+2]=this.z,A[e+3]=this.w,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this.z=A.getZ(e),this.w=A.getW(e),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 Lf extends EI{constructor(A=1,e=1,g={}){super(),g=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ag,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},g),this.isRenderTarget=!0,this.width=A,this.height=e,this.depth=g.depth,this.scissor=new Ke(0,0,A,e),this.scissorTest=!1,this.viewport=new Ke(0,0,A,e);const i={width:A,height:e,depth:g.depth},I=new ig(i);this.textures=[];const C=g.count;for(let o=0;o<C;o++)this.textures[o]=I.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(g),this.depthBuffer=g.depthBuffer,this.stencilBuffer=g.stencilBuffer,this.resolveDepthBuffer=g.resolveDepthBuffer,this.resolveStencilBuffer=g.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=g.depthTexture,this.samples=g.samples,this.multiview=g.multiview}_setTextureOptions(A={}){const e={minFilter:Ag,generateMipmaps:!1,flipY:!1,internalFormat:null};A.mapping!==void 0&&(e.mapping=A.mapping),A.wrapS!==void 0&&(e.wrapS=A.wrapS),A.wrapT!==void 0&&(e.wrapT=A.wrapT),A.wrapR!==void 0&&(e.wrapR=A.wrapR),A.magFilter!==void 0&&(e.magFilter=A.magFilter),A.minFilter!==void 0&&(e.minFilter=A.minFilter),A.format!==void 0&&(e.format=A.format),A.type!==void 0&&(e.type=A.type),A.anisotropy!==void 0&&(e.anisotropy=A.anisotropy),A.colorSpace!==void 0&&(e.colorSpace=A.colorSpace),A.flipY!==void 0&&(e.flipY=A.flipY),A.generateMipmaps!==void 0&&(e.generateMipmaps=A.generateMipmaps),A.internalFormat!==void 0&&(e.internalFormat=A.internalFormat);for(let g=0;g<this.textures.length;g++)this.textures[g].setValues(e)}get texture(){return this.textures[0]}set texture(A){this.textures[0]=A}set depthTexture(A){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),A!==null&&(A.renderTarget=this),this._depthTexture=A}get depthTexture(){return this._depthTexture}setSize(A,e,g=1){if(this.width!==A||this.height!==e||this.depth!==g){this.width=A,this.height=e,this.depth=g;for(let i=0,I=this.textures.length;i<I;i++)this.textures[i].image.width=A,this.textures[i].image.height=e,this.textures[i].image.depth=g,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,A,e),this.scissor.set(0,0,A,e)}clone(){return new this.constructor().copy(this)}copy(A){this.width=A.width,this.height=A.height,this.depth=A.depth,this.scissor.copy(A.scissor),this.scissorTest=A.scissorTest,this.viewport.copy(A.viewport),this.textures.length=0;for(let e=0,g=A.textures.length;e<g;e++){this.textures[e]=A.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const i=Object.assign({},A.textures[e].image);this.textures[e].source=new Tn(i)}return this.depthBuffer=A.depthBuffer,this.stencilBuffer=A.stencilBuffer,this.resolveDepthBuffer=A.resolveDepthBuffer,this.resolveStencilBuffer=A.resolveStencilBuffer,A.depthTexture!==null&&(this.depthTexture=A.depthTexture.clone()),this.samples=A.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class st extends Lf{constructor(A=1,e=1,g={}){super(A,e,g),this.isWebGLRenderTarget=!0}}class c0 extends ig{constructor(A=null,e=1,g=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:A,width:e,height:g,depth:i},this.magFilter=$e,this.minFilter=$e,this.wrapR=kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class Kf extends ig{constructor(A=null,e=1,g=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:A,width:e,height:g,depth:i},this.magFilter=$e,this.minFilter=$e,this.wrapR=kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class sC{constructor(A=new J(1/0,1/0,1/0),e=new J(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=A,this.max=e}set(A,e){return this.min.copy(A),this.max.copy(e),this}setFromArray(A){this.makeEmpty();for(let e=0,g=A.length;e<g;e+=3)this.expandByPoint(Pg.fromArray(A,e));return this}setFromBufferAttribute(A){this.makeEmpty();for(let e=0,g=A.count;e<g;e++)this.expandByPoint(Pg.fromBufferAttribute(A,e));return this}setFromPoints(A){this.makeEmpty();for(let e=0,g=A.length;e<g;e++)this.expandByPoint(A[e]);return this}setFromCenterAndSize(A,e){const g=Pg.copy(e).multiplyScalar(.5);return this.min.copy(A).sub(g),this.max.copy(A).add(g),this}setFromObject(A,e=!1){return this.makeEmpty(),this.expandByObject(A,e)}clone(){return new this.constructor().copy(this)}copy(A){return this.min.copy(A.min),this.max.copy(A.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(A){return this.isEmpty()?A.set(0,0,0):A.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(A){return this.isEmpty()?A.set(0,0,0):A.subVectors(this.max,this.min)}expandByPoint(A){return this.min.min(A),this.max.max(A),this}expandByVector(A){return this.min.sub(A),this.max.add(A),this}expandByScalar(A){return this.min.addScalar(-A),this.max.addScalar(A),this}expandByObject(A,e=!1){A.updateWorldMatrix(!1,!1);const g=A.geometry;if(g!==void 0){const I=g.getAttribute("position");if(e===!0&&I!==void 0&&A.isInstancedMesh!==!0)for(let C=0,o=I.count;C<o;C++)A.isMesh===!0?A.getVertexPosition(C,Pg):Pg.fromBufferAttribute(I,C),Pg.applyMatrix4(A.matrixWorld),this.expandByPoint(Pg);else A.boundingBox!==void 0?(A.boundingBox===null&&A.computeBoundingBox(),_o.copy(A.boundingBox)):(g.boundingBox===null&&g.computeBoundingBox(),_o.copy(g.boundingBox)),_o.applyMatrix4(A.matrixWorld),this.union(_o)}const i=A.children;for(let I=0,C=i.length;I<C;I++)this.expandByObject(i[I],e);return this}containsPoint(A){return A.x>=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y&&A.z>=this.min.z&&A.z<=this.max.z}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y&&this.min.z<=A.min.z&&A.max.z<=this.max.z}getParameter(A,e){return e.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y),(A.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y&&A.max.z>=this.min.z&&A.min.z<=this.max.z}intersectsSphere(A){return this.clampPoint(A.center,Pg),Pg.distanceToSquared(A.center)<=A.radius*A.radius}intersectsPlane(A){let e,g;return A.normal.x>0?(e=A.normal.x*this.min.x,g=A.normal.x*this.max.x):(e=A.normal.x*this.max.x,g=A.normal.x*this.min.x),A.normal.y>0?(e+=A.normal.y*this.min.y,g+=A.normal.y*this.max.y):(e+=A.normal.y*this.max.y,g+=A.normal.y*this.min.y),A.normal.z>0?(e+=A.normal.z*this.min.z,g+=A.normal.z*this.max.z):(e+=A.normal.z*this.max.z,g+=A.normal.z*this.min.z),e<=-A.constant&&g>=-A.constant}intersectsTriangle(A){if(this.isEmpty())return!1;this.getCenter(BC),wo.subVectors(this.max,BC),hI.subVectors(A.a,BC),dI.subVectors(A.b,BC),xI.subVectors(A.c,BC),Ii.subVectors(dI,hI),Ci.subVectors(xI,dI),Ni.subVectors(hI,xI);let e=[0,-Ii.z,Ii.y,0,-Ci.z,Ci.y,0,-Ni.z,Ni.y,Ii.z,0,-Ii.x,Ci.z,0,-Ci.x,Ni.z,0,-Ni.x,-Ii.y,Ii.x,0,-Ci.y,Ci.x,0,-Ni.y,Ni.x,0];return!Pn(e,hI,dI,xI,wo)||(e=[1,0,0,0,1,0,0,0,1],!Pn(e,hI,dI,xI,wo))?!1:(po.crossVectors(Ii,Ci),e=[po.x,po.y,po.z],Pn(e,hI,dI,xI,wo))}clampPoint(A,e){return e.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,Pg).distanceTo(A)}getBoundingSphere(A){return this.isEmpty()?A.makeEmpty():(this.getCenter(A.center),A.radius=this.getSize(Pg).length()*.5),A}intersect(A){return this.min.max(A.min),this.max.min(A.max),this.isEmpty()&&this.makeEmpty(),this}union(A){return this.min.min(A.min),this.max.max(A.max),this}applyMatrix4(A){return this.isEmpty()?this:(Ft[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),Ft[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),Ft[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),Ft[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),Ft[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),Ft[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),Ft[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),Ft[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(Ft),this)}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(A){return this.min.fromArray(A.min),this.max.fromArray(A.max),this}}const Ft=[new J,new J,new J,new J,new J,new J,new J,new J],Pg=new J,_o=new sC,hI=new J,dI=new J,xI=new J,Ii=new J,Ci=new J,Ni=new J,BC=new J,wo=new J,po=new J,Si=new J;function Pn(t,A,e,g,i){for(let I=0,C=t.length-3;I<=C;I+=3){Si.fromArray(t,I);const o=i.x*Math.abs(Si.x)+i.y*Math.abs(Si.y)+i.z*Math.abs(Si.z),a=A.dot(Si),Q=e.dot(Si),n=g.dot(Si);if(Math.max(-Math.max(a,Q,n),Math.min(a,Q,n))>o)return!1}return!0}const vf=new sC,EC=new J,On=new J;class Vn{constructor(A=new J,e=-1){this.isSphere=!0,this.center=A,this.radius=e}set(A,e){return this.center.copy(A),this.radius=e,this}setFromPoints(A,e){const g=this.center;e!==void 0?g.copy(e):vf.setFromPoints(A).getCenter(g);let i=0;for(let I=0,C=A.length;I<C;I++)i=Math.max(i,g.distanceToSquared(A[I]));return this.radius=Math.sqrt(i),this}copy(A){return this.center.copy(A.center),this.radius=A.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(A){return A.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(A){return A.distanceTo(this.center)-this.radius}intersectsSphere(A){const e=this.radius+A.radius;return A.center.distanceToSquared(this.center)<=e*e}intersectsBox(A){return A.intersectsSphere(this)}intersectsPlane(A){return Math.abs(A.distanceToPoint(this.center))<=this.radius}clampPoint(A,e){const g=this.center.distanceToSquared(A);return e.copy(A),g>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(A){return this.isEmpty()?(A.makeEmpty(),A):(A.set(this.center,this.center),A.expandByScalar(this.radius),A)}applyMatrix4(A){return this.center.applyMatrix4(A),this.radius=this.radius*A.getMaxScaleOnAxis(),this}translate(A){return this.center.add(A),this}expandByPoint(A){if(this.isEmpty())return this.center.copy(A),this.radius=0,this;EC.subVectors(A,this.center);const e=EC.lengthSq();if(e>this.radius*this.radius){const g=Math.sqrt(e),i=(g-this.radius)*.5;this.center.addScaledVector(EC,i/g),this.radius+=i}return this}union(A){return A.isEmpty()?this:this.isEmpty()?(this.copy(A),this):(this.center.equals(A.center)===!0?this.radius=Math.max(this.radius,A.radius):(On.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(EC.copy(A.center).add(On)),this.expandByPoint(EC.copy(A.center).sub(On))),this)}equals(A){return A.center.equals(this.center)&&A.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(A){return this.radius=A.radius,this.center.fromArray(A.center),this}}const Ut=new J,jn=new J,mo=new J,oi=new J,Wn=new J,yo=new J,Xn=new J;class Jf{constructor(A=new J,e=new J(0,0,-1)){this.origin=A,this.direction=e}set(A,e){return this.origin.copy(A),this.direction.copy(e),this}copy(A){return this.origin.copy(A.origin),this.direction.copy(A.direction),this}at(A,e){return e.copy(this.origin).addScaledVector(this.direction,A)}lookAt(A){return this.direction.copy(A).sub(this.origin).normalize(),this}recast(A){return this.origin.copy(this.at(A,Ut)),this}closestPointToPoint(A,e){e.subVectors(A,this.origin);const g=e.dot(this.direction);return g<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,g)}distanceToPoint(A){return Math.sqrt(this.distanceSqToPoint(A))}distanceSqToPoint(A){const e=Ut.subVectors(A,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(A):(Ut.copy(this.origin).addScaledVector(this.direction,e),Ut.distanceToSquared(A))}distanceSqToSegment(A,e,g,i){jn.copy(A).add(e).multiplyScalar(.5),mo.copy(e).sub(A).normalize(),oi.copy(this.origin).sub(jn);const I=A.distanceTo(e)*.5,C=-this.direction.dot(mo),o=oi.dot(this.direction),a=-oi.dot(mo),Q=oi.lengthSq(),n=Math.abs(1-C*C);let s,B,E,d;if(n>0)if(s=C*a-o,B=C*o-a,d=I*n,s>=0)if(B>=-d)if(B<=d){const c=1/n;s*=c,B*=c,E=s*(s+C*B+2*o)+B*(C*s+B+2*a)+Q}else B=I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;else B=-I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;else B<=-d?(s=Math.max(0,-(-C*I+o)),B=s>0?-I:Math.min(Math.max(-I,-a),I),E=-s*s+B*(B+2*a)+Q):B<=d?(s=0,B=Math.min(Math.max(-I,-a),I),E=B*(B+2*a)+Q):(s=Math.max(0,-(C*I+o)),B=s>0?I:Math.min(Math.max(-I,-a),I),E=-s*s+B*(B+2*a)+Q);else B=C>0?-I:I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;return g&&g.copy(this.origin).addScaledVector(this.direction,s),i&&i.copy(jn).addScaledVector(mo,B),E}intersectSphere(A,e){Ut.subVectors(A.center,this.origin);const g=Ut.dot(this.direction),i=Ut.dot(Ut)-g*g,I=A.radius*A.radius;if(i>I)return null;const C=Math.sqrt(I-i),o=g-C,a=g+C;return a<0?null:o<0?this.at(a,e):this.at(o,e)}intersectsSphere(A){return A.radius<0?!1:this.distanceSqToPoint(A.center)<=A.radius*A.radius}distanceToPlane(A){const e=A.normal.dot(this.direction);if(e===0)return A.distanceToPoint(this.origin)===0?0:null;const g=-(this.origin.dot(A.normal)+A.constant)/e;return g>=0?g:null}intersectPlane(A,e){const g=this.distanceToPlane(A);return g===null?null:this.at(g,e)}intersectsPlane(A){const e=A.distanceToPoint(this.origin);return e===0||A.normal.dot(this.direction)*e<0}intersectBox(A,e){let g,i,I,C,o,a;const Q=1/this.direction.x,n=1/this.direction.y,s=1/this.direction.z,B=this.origin;return Q>=0?(g=(A.min.x-B.x)*Q,i=(A.max.x-B.x)*Q):(g=(A.max.x-B.x)*Q,i=(A.min.x-B.x)*Q),n>=0?(I=(A.min.y-B.y)*n,C=(A.max.y-B.y)*n):(I=(A.max.y-B.y)*n,C=(A.min.y-B.y)*n),g>C||I>i||((I>g||isNaN(g))&&(g=I),(C<i||isNaN(i))&&(i=C),s>=0?(o=(A.min.z-B.z)*s,a=(A.max.z-B.z)*s):(o=(A.max.z-B.z)*s,a=(A.min.z-B.z)*s),g>a||o>i)||((o>g||g!==g)&&(g=o),(a<i||i!==i)&&(i=a),i<0)?null:this.at(g>=0?g:i,e)}intersectsBox(A){return this.intersectBox(A,Ut)!==null}intersectTriangle(A,e,g,i,I){Wn.subVectors(e,A),yo.subVectors(g,A),Xn.crossVectors(Wn,yo);let C=this.direction.dot(Xn),o;if(C>0){if(i)return null;o=1}else if(C<0)o=-1,C=-C;else return null;oi.subVectors(this.origin,A);const a=o*this.direction.dot(yo.crossVectors(oi,yo));if(a<0)return null;const Q=o*this.direction.dot(Wn.cross(oi));if(Q<0||a+Q>C)return null;const n=-o*oi.dot(Xn);return n<0?null:this.at(n/C,I)}applyMatrix4(A){return this.origin.applyMatrix4(A),this.direction.transformDirection(A),this}equals(A){return A.origin.equals(this.origin)&&A.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ye{constructor(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h){Ye.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A!==void 0&&this.set(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h)}set(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h){const r=this.elements;return r[0]=A,r[4]=e,r[8]=g,r[12]=i,r[1]=I,r[5]=C,r[9]=o,r[13]=a,r[2]=Q,r[6]=n,r[10]=s,r[14]=B,r[3]=E,r[7]=d,r[11]=c,r[15]=h,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 Ye().fromArray(this.elements)}copy(A){const e=this.elements,g=A.elements;return e[0]=g[0],e[1]=g[1],e[2]=g[2],e[3]=g[3],e[4]=g[4],e[5]=g[5],e[6]=g[6],e[7]=g[7],e[8]=g[8],e[9]=g[9],e[10]=g[10],e[11]=g[11],e[12]=g[12],e[13]=g[13],e[14]=g[14],e[15]=g[15],this}copyPosition(A){const e=this.elements,g=A.elements;return e[12]=g[12],e[13]=g[13],e[14]=g[14],this}setFromMatrix3(A){const e=A.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(A,e,g){return this.determinant()===0?(A.set(1,0,0),e.set(0,1,0),g.set(0,0,1),this):(A.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),g.setFromMatrixColumn(this,2),this)}makeBasis(A,e,g){return this.set(A.x,e.x,g.x,0,A.y,e.y,g.y,0,A.z,e.z,g.z,0,0,0,0,1),this}extractRotation(A){if(A.determinant()===0)return this.identity();const e=this.elements,g=A.elements,i=1/lI.setFromMatrixColumn(A,0).length(),I=1/lI.setFromMatrixColumn(A,1).length(),C=1/lI.setFromMatrixColumn(A,2).length();return e[0]=g[0]*i,e[1]=g[1]*i,e[2]=g[2]*i,e[3]=0,e[4]=g[4]*I,e[5]=g[5]*I,e[6]=g[6]*I,e[7]=0,e[8]=g[8]*C,e[9]=g[9]*C,e[10]=g[10]*C,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(A){const e=this.elements,g=A.x,i=A.y,I=A.z,C=Math.cos(g),o=Math.sin(g),a=Math.cos(i),Q=Math.sin(i),n=Math.cos(I),s=Math.sin(I);if(A.order==="XYZ"){const B=C*n,E=C*s,d=o*n,c=o*s;e[0]=a*n,e[4]=-a*s,e[8]=Q,e[1]=E+d*Q,e[5]=B-c*Q,e[9]=-o*a,e[2]=c-B*Q,e[6]=d+E*Q,e[10]=C*a}else if(A.order==="YXZ"){const B=a*n,E=a*s,d=Q*n,c=Q*s;e[0]=B+c*o,e[4]=d*o-E,e[8]=C*Q,e[1]=C*s,e[5]=C*n,e[9]=-o,e[2]=E*o-d,e[6]=c+B*o,e[10]=C*a}else if(A.order==="ZXY"){const B=a*n,E=a*s,d=Q*n,c=Q*s;e[0]=B-c*o,e[4]=-C*s,e[8]=d+E*o,e[1]=E+d*o,e[5]=C*n,e[9]=c-B*o,e[2]=-C*Q,e[6]=o,e[10]=C*a}else if(A.order==="ZYX"){const B=C*n,E=C*s,d=o*n,c=o*s;e[0]=a*n,e[4]=d*Q-E,e[8]=B*Q+c,e[1]=a*s,e[5]=c*Q+B,e[9]=E*Q-d,e[2]=-Q,e[6]=o*a,e[10]=C*a}else if(A.order==="YZX"){const B=C*a,E=C*Q,d=o*a,c=o*Q;e[0]=a*n,e[4]=c-B*s,e[8]=d*s+E,e[1]=s,e[5]=C*n,e[9]=-o*n,e[2]=-Q*n,e[6]=E*s+d,e[10]=B-c*s}else if(A.order==="XZY"){const B=C*a,E=C*Q,d=o*a,c=o*Q;e[0]=a*n,e[4]=-s,e[8]=Q*n,e[1]=B*s+c,e[5]=C*n,e[9]=E*s-d,e[2]=d*s-E,e[6]=o*n,e[10]=c*s+B}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(A){return this.compose(Yf,A,Tf)}lookAt(A,e,g){const i=this.elements;return wg.subVectors(A,e),wg.lengthSq()===0&&(wg.z=1),wg.normalize(),ai.crossVectors(g,wg),ai.lengthSq()===0&&(Math.abs(g.z)===1?wg.x+=1e-4:wg.z+=1e-4,wg.normalize(),ai.crossVectors(g,wg)),ai.normalize(),bo.crossVectors(wg,ai),i[0]=ai.x,i[4]=bo.x,i[8]=wg.x,i[1]=ai.y,i[5]=bo.y,i[9]=wg.y,i[2]=ai.z,i[6]=bo.z,i[10]=wg.z,this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,e){const g=A.elements,i=e.elements,I=this.elements,C=g[0],o=g[4],a=g[8],Q=g[12],n=g[1],s=g[5],B=g[9],E=g[13],d=g[2],c=g[6],h=g[10],r=g[14],f=g[3],_=g[7],l=g[11],D=g[15],p=i[0],y=i[4],k=i[8],x=i[12],w=i[1],N=i[5],U=i[9],K=i[13],P=i[2],j=i[6],H=i[10],O=i[14],z=i[3],xA=i[7],sA=i[11],fA=i[15];return I[0]=C*p+o*w+a*P+Q*z,I[4]=C*y+o*N+a*j+Q*xA,I[8]=C*k+o*U+a*H+Q*sA,I[12]=C*x+o*K+a*O+Q*fA,I[1]=n*p+s*w+B*P+E*z,I[5]=n*y+s*N+B*j+E*xA,I[9]=n*k+s*U+B*H+E*sA,I[13]=n*x+s*K+B*O+E*fA,I[2]=d*p+c*w+h*P+r*z,I[6]=d*y+c*N+h*j+r*xA,I[10]=d*k+c*U+h*H+r*sA,I[14]=d*x+c*K+h*O+r*fA,I[3]=f*p+_*w+l*P+D*z,I[7]=f*y+_*N+l*j+D*xA,I[11]=f*k+_*U+l*H+D*sA,I[15]=f*x+_*K+l*O+D*fA,this}multiplyScalar(A){const e=this.elements;return e[0]*=A,e[4]*=A,e[8]*=A,e[12]*=A,e[1]*=A,e[5]*=A,e[9]*=A,e[13]*=A,e[2]*=A,e[6]*=A,e[10]*=A,e[14]*=A,e[3]*=A,e[7]*=A,e[11]*=A,e[15]*=A,this}determinant(){const A=this.elements,e=A[0],g=A[4],i=A[8],I=A[12],C=A[1],o=A[5],a=A[9],Q=A[13],n=A[2],s=A[6],B=A[10],E=A[14],d=A[3],c=A[7],h=A[11],r=A[15],f=a*E-Q*B,_=o*E-Q*s,l=o*B-a*s,D=C*E-Q*n,p=C*B-a*n,y=C*s-o*n;return e*(c*f-h*_+r*l)-g*(d*f-h*D+r*p)+i*(d*_-c*D+r*y)-I*(d*l-c*p+h*y)}transpose(){const A=this.elements;let e;return e=A[1],A[1]=A[4],A[4]=e,e=A[2],A[2]=A[8],A[8]=e,e=A[6],A[6]=A[9],A[9]=e,e=A[3],A[3]=A[12],A[12]=e,e=A[7],A[7]=A[13],A[13]=e,e=A[11],A[11]=A[14],A[14]=e,this}setPosition(A,e,g){const i=this.elements;return A.isVector3?(i[12]=A.x,i[13]=A.y,i[14]=A.z):(i[12]=A,i[13]=e,i[14]=g),this}invert(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8],s=A[9],B=A[10],E=A[11],d=A[12],c=A[13],h=A[14],r=A[15],f=s*h*Q-c*B*Q+c*a*E-o*h*E-s*a*r+o*B*r,_=d*B*Q-n*h*Q-d*a*E+C*h*E+n*a*r-C*B*r,l=n*c*Q-d*s*Q+d*o*E-C*c*E-n*o*r+C*s*r,D=d*s*a-n*c*a-d*o*B+C*c*B+n*o*h-C*s*h,p=e*f+g*_+i*l+I*D;if(p===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const y=1/p;return A[0]=f*y,A[1]=(c*B*I-s*h*I-c*i*E+g*h*E+s*i*r-g*B*r)*y,A[2]=(o*h*I-c*a*I+c*i*Q-g*h*Q-o*i*r+g*a*r)*y,A[3]=(s*a*I-o*B*I-s*i*Q+g*B*Q+o*i*E-g*a*E)*y,A[4]=_*y,A[5]=(n*h*I-d*B*I+d*i*E-e*h*E-n*i*r+e*B*r)*y,A[6]=(d*a*I-C*h*I-d*i*Q+e*h*Q+C*i*r-e*a*r)*y,A[7]=(C*B*I-n*a*I+n*i*Q-e*B*Q-C*i*E+e*a*E)*y,A[8]=l*y,A[9]=(d*s*I-n*c*I-d*g*E+e*c*E+n*g*r-e*s*r)*y,A[10]=(C*c*I-d*o*I+d*g*Q-e*c*Q-C*g*r+e*o*r)*y,A[11]=(n*o*I-C*s*I-n*g*Q+e*s*Q+C*g*E-e*o*E)*y,A[12]=D*y,A[13]=(n*c*i-d*s*i+d*g*B-e*c*B-n*g*h+e*s*h)*y,A[14]=(d*o*i-C*c*i-d*g*a+e*c*a+C*g*h-e*o*h)*y,A[15]=(C*s*i-n*o*i+n*g*a-e*s*a-C*g*B+e*o*B)*y,this}scale(A){const e=this.elements,g=A.x,i=A.y,I=A.z;return e[0]*=g,e[4]*=i,e[8]*=I,e[1]*=g,e[5]*=i,e[9]*=I,e[2]*=g,e[6]*=i,e[10]*=I,e[3]*=g,e[7]*=i,e[11]*=I,this}getMaxScaleOnAxis(){const A=this.elements,e=A[0]*A[0]+A[1]*A[1]+A[2]*A[2],g=A[4]*A[4]+A[5]*A[5]+A[6]*A[6],i=A[8]*A[8]+A[9]*A[9]+A[10]*A[10];return Math.sqrt(Math.max(e,g,i))}makeTranslation(A,e,g){return A.isVector3?this.set(1,0,0,A.x,0,1,0,A.y,0,0,1,A.z,0,0,0,1):this.set(1,0,0,A,0,1,0,e,0,0,1,g,0,0,0,1),this}makeRotationX(A){const e=Math.cos(A),g=Math.sin(A);return this.set(1,0,0,0,0,e,-g,0,0,g,e,0,0,0,0,1),this}makeRotationY(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,0,g,0,0,1,0,0,-g,0,e,0,0,0,0,1),this}makeRotationZ(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,-g,0,0,g,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(A,e){const g=Math.cos(e),i=Math.sin(e),I=1-g,C=A.x,o=A.y,a=A.z,Q=I*C,n=I*o;return this.set(Q*C+g,Q*o-i*a,Q*a+i*o,0,Q*o+i*a,n*o+g,n*a-i*C,0,Q*a-i*o,n*a+i*C,I*a*a+g,0,0,0,0,1),this}makeScale(A,e,g){return this.set(A,0,0,0,0,e,0,0,0,0,g,0,0,0,0,1),this}makeShear(A,e,g,i,I,C){return this.set(1,g,I,0,A,1,C,0,e,i,1,0,0,0,0,1),this}compose(A,e,g){const i=this.elements,I=e._x,C=e._y,o=e._z,a=e._w,Q=I+I,n=C+C,s=o+o,B=I*Q,E=I*n,d=I*s,c=C*n,h=C*s,r=o*s,f=a*Q,_=a*n,l=a*s,D=g.x,p=g.y,y=g.z;return i[0]=(1-(c+r))*D,i[1]=(E+l)*D,i[2]=(d-_)*D,i[3]=0,i[4]=(E-l)*p,i[5]=(1-(B+r))*p,i[6]=(h+f)*p,i[7]=0,i[8]=(d+_)*y,i[9]=(h-f)*y,i[10]=(1-(B+c))*y,i[11]=0,i[12]=A.x,i[13]=A.y,i[14]=A.z,i[15]=1,this}decompose(A,e,g){const i=this.elements;if(A.x=i[12],A.y=i[13],A.z=i[14],this.determinant()===0)return g.set(1,1,1),e.identity(),this;let I=lI.set(i[0],i[1],i[2]).length();const C=lI.set(i[4],i[5],i[6]).length(),o=lI.set(i[8],i[9],i[10]).length();this.determinant()<0&&(I=-I),Og.copy(this);const Q=1/I,n=1/C,s=1/o;return Og.elements[0]*=Q,Og.elements[1]*=Q,Og.elements[2]*=Q,Og.elements[4]*=n,Og.elements[5]*=n,Og.elements[6]*=n,Og.elements[8]*=s,Og.elements[9]*=s,Og.elements[10]*=s,e.setFromRotationMatrix(Og),g.x=I,g.y=C,g.z=o,this}makePerspective(A,e,g,i,I,C,o=nt,a=!1){const Q=this.elements,n=2*I/(e-A),s=2*I/(g-i),B=(e+A)/(e-A),E=(g+i)/(g-i);let d,c;if(a)d=I/(C-I),c=C*I/(C-I);else if(o===nt)d=-(C+I)/(C-I),c=-2*C*I/(C-I);else if(o===uo)d=-C/(C-I),c=-C*I/(C-I);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return Q[0]=n,Q[4]=0,Q[8]=B,Q[12]=0,Q[1]=0,Q[5]=s,Q[9]=E,Q[13]=0,Q[2]=0,Q[6]=0,Q[10]=d,Q[14]=c,Q[3]=0,Q[7]=0,Q[11]=-1,Q[15]=0,this}makeOrthographic(A,e,g,i,I,C,o=nt,a=!1){const Q=this.elements,n=2/(e-A),s=2/(g-i),B=-(e+A)/(e-A),E=-(g+i)/(g-i);let d,c;if(a)d=1/(C-I),c=C/(C-I);else if(o===nt)d=-2/(C-I),c=-(C+I)/(C-I);else if(o===uo)d=-1/(C-I),c=-I/(C-I);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return Q[0]=n,Q[4]=0,Q[8]=0,Q[12]=B,Q[1]=0,Q[5]=s,Q[9]=0,Q[13]=E,Q[2]=0,Q[6]=0,Q[10]=d,Q[14]=c,Q[3]=0,Q[7]=0,Q[11]=0,Q[15]=1,this}equals(A){const e=this.elements,g=A.elements;for(let i=0;i<16;i++)if(e[i]!==g[i])return!1;return!0}fromArray(A,e=0){for(let g=0;g<16;g++)this.elements[g]=A[g+e];return this}toArray(A=[],e=0){const g=this.elements;return A[e]=g[0],A[e+1]=g[1],A[e+2]=g[2],A[e+3]=g[3],A[e+4]=g[4],A[e+5]=g[5],A[e+6]=g[6],A[e+7]=g[7],A[e+8]=g[8],A[e+9]=g[9],A[e+10]=g[10],A[e+11]=g[11],A[e+12]=g[12],A[e+13]=g[13],A[e+14]=g[14],A[e+15]=g[15],A}}const lI=new J,Og=new Ye,Yf=new J(0,0,0),Tf=new J(1,1,1),ai=new J,bo=new J,wg=new J,h0=new Ye,d0=new nC;class Lt{constructor(A=0,e=0,g=0,i=Lt.DEFAULT_ORDER){this.isEuler=!0,this._x=A,this._y=e,this._z=g,this._order=i}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get order(){return this._order}set order(A){this._order=A,this._onChangeCallback()}set(A,e,g,i=this._order){return this._x=A,this._y=e,this._z=g,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(A){return this._x=A._x,this._y=A._y,this._z=A._z,this._order=A._order,this._onChangeCallback(),this}setFromRotationMatrix(A,e=this._order,g=!0){const i=A.elements,I=i[0],C=i[4],o=i[8],a=i[1],Q=i[5],n=i[9],s=i[2],B=i[6],E=i[10];switch(e){case"XYZ":this._y=Math.asin(te(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-n,E),this._z=Math.atan2(-C,I)):(this._x=Math.atan2(B,Q),this._z=0);break;case"YXZ":this._x=Math.asin(-te(n,-1,1)),Math.abs(n)<.9999999?(this._y=Math.atan2(o,E),this._z=Math.atan2(a,Q)):(this._y=Math.atan2(-s,I),this._z=0);break;case"ZXY":this._x=Math.asin(te(B,-1,1)),Math.abs(B)<.9999999?(this._y=Math.atan2(-s,E),this._z=Math.atan2(-C,Q)):(this._y=0,this._z=Math.atan2(a,I));break;case"ZYX":this._y=Math.asin(-te(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(B,E),this._z=Math.atan2(a,I)):(this._x=0,this._z=Math.atan2(-C,Q));break;case"YZX":this._z=Math.asin(te(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-n,Q),this._y=Math.atan2(-s,I)):(this._x=0,this._y=Math.atan2(o,E));break;case"XZY":this._z=Math.asin(-te(C,-1,1)),Math.abs(C)<.9999999?(this._x=Math.atan2(B,Q),this._y=Math.atan2(o,I)):(this._x=Math.atan2(-n,E),this._y=0);break;default:LA("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,g===!0&&this._onChangeCallback(),this}setFromQuaternion(A,e,g){return h0.makeRotationFromQuaternion(A),this.setFromRotationMatrix(h0,e,g)}setFromVector3(A,e=this._order){return this.set(A.x,A.y,A.z,e)}reorder(A){return d0.setFromEuler(this),this.setFromQuaternion(d0,A)}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._order===this._order}fromArray(A){return this._x=A[0],this._y=A[1],this._z=A[2],A[3]!==void 0&&(this._order=A[3]),this._onChangeCallback(),this}toArray(A=[],e=0){return A[e]=this._x,A[e+1]=this._y,A[e+2]=this._z,A[e+3]=this._order,A}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Lt.DEFAULT_ORDER="XYZ";class x0{constructor(){this.mask=1}set(A){this.mask=(1<<A|0)>>>0}enable(A){this.mask|=1<<A|0}enableAll(){this.mask=-1}toggle(A){this.mask^=1<<A|0}disable(A){this.mask&=~(1<<A|0)}disableAll(){this.mask=0}test(A){return(this.mask&A.mask)!==0}isEnabled(A){return(this.mask&(1<<A|0))!==0}}let qf=0;const l0=new J,fI=new nC,Kt=new Ye,No=new J,rC=new J,Hf=new J,Pf=new nC,f0=new J(1,0,0),u0=new J(0,1,0),D0=new J(0,0,1),_0={type:"added"},Of={type:"removed"},uI={type:"childadded",child:null},Zn={type:"childremoved",child:null};class pg extends EI{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:qf++}),this.uuid=aC(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=pg.DEFAULT_UP.clone();const A=new J,e=new Lt,g=new nC,i=new J(1,1,1);function I(){g.setFromEuler(e,!1)}function C(){e.setFromQuaternion(g,void 0,!1)}e._onChange(I),g._onChange(C),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:A},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:g},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ye},normalMatrix:{value:new YA}}),this.matrix=new Ye,this.matrixWorld=new Ye,this.matrixAutoUpdate=pg.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=pg.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new x0,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(A){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(A),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(A){return this.quaternion.premultiply(A),this}setRotationFromAxisAngle(A,e){this.quaternion.setFromAxisAngle(A,e)}setRotationFromEuler(A){this.quaternion.setFromEuler(A,!0)}setRotationFromMatrix(A){this.quaternion.setFromRotationMatrix(A)}setRotationFromQuaternion(A){this.quaternion.copy(A)}rotateOnAxis(A,e){return fI.setFromAxisAngle(A,e),this.quaternion.multiply(fI),this}rotateOnWorldAxis(A,e){return fI.setFromAxisAngle(A,e),this.quaternion.premultiply(fI),this}rotateX(A){return this.rotateOnAxis(f0,A)}rotateY(A){return this.rotateOnAxis(u0,A)}rotateZ(A){return this.rotateOnAxis(D0,A)}translateOnAxis(A,e){return l0.copy(A).applyQuaternion(this.quaternion),this.position.add(l0.multiplyScalar(e)),this}translateX(A){return this.translateOnAxis(f0,A)}translateY(A){return this.translateOnAxis(u0,A)}translateZ(A){return this.translateOnAxis(D0,A)}localToWorld(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(this.matrixWorld)}worldToLocal(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(Kt.copy(this.matrixWorld).invert())}lookAt(A,e,g){A.isVector3?No.copy(A):No.set(A,e,g);const i=this.parent;this.updateWorldMatrix(!0,!1),rC.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Kt.lookAt(rC,No,this.up):Kt.lookAt(No,rC,this.up),this.quaternion.setFromRotationMatrix(Kt),i&&(Kt.extractRotation(i.matrixWorld),fI.setFromRotationMatrix(Kt),this.quaternion.premultiply(fI.invert()))}add(A){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return A===this?(ae("Object3D.add: object can't be added as a child of itself.",A),this):(A&&A.isObject3D?(A.removeFromParent(),A.parent=this,this.children.push(A),A.dispatchEvent(_0),uI.child=A,this.dispatchEvent(uI),uI.child=null):ae("Object3D.add: object not an instance of THREE.Object3D.",A),this)}remove(A){if(arguments.length>1){for(let g=0;g<arguments.length;g++)this.remove(arguments[g]);return this}const e=this.children.indexOf(A);return e!==-1&&(A.parent=null,this.children.splice(e,1),A.dispatchEvent(Of),Zn.child=A,this.dispatchEvent(Zn),Zn.child=null),this}removeFromParent(){const A=this.parent;return A!==null&&A.remove(this),this}clear(){return this.remove(...this.children)}attach(A){return this.updateWorldMatrix(!0,!1),Kt.copy(this.matrixWorld).invert(),A.parent!==null&&(A.parent.updateWorldMatrix(!0,!1),Kt.multiply(A.parent.matrixWorld)),A.applyMatrix4(Kt),A.removeFromParent(),A.parent=this,this.children.push(A),A.updateWorldMatrix(!1,!0),A.dispatchEvent(_0),uI.child=A,this.dispatchEvent(uI),uI.child=null,this}getObjectById(A){return this.getObjectByProperty("id",A)}getObjectByName(A){return this.getObjectByProperty("name",A)}getObjectByProperty(A,e){if(this[A]===e)return this;for(let g=0,i=this.children.length;g<i;g++){const C=this.children[g].getObjectByProperty(A,e);if(C!==void 0)return C}}getObjectsByProperty(A,e,g=[]){this[A]===e&&g.push(this);const i=this.children;for(let I=0,C=i.length;I<C;I++)i[I].getObjectsByProperty(A,e,g);return g}getWorldPosition(A){return this.updateWorldMatrix(!0,!1),A.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rC,A,Hf),A}getWorldScale(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rC,Pf,A),A}getWorldDirection(A){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return A.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(A){A(this);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].traverse(A)}traverseVisible(A){if(this.visible===!1)return;A(this);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].traverseVisible(A)}traverseAncestors(A){const e=this.parent;e!==null&&(A(e),e.traverseAncestors(A))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(A){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||A)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,A=!0);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].updateMatrixWorld(A)}updateWorldMatrix(A,e){const g=this.parent;if(A===!0&&g!==null&&g.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)),e===!0){const i=this.children;for(let I=0,C=i.length;I<C;I++)i[I].updateWorldMatrix(!1,!0)}}toJSON(A){const e=A===void 0||typeof A=="string",g={};e&&(A={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},g.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(A),i.indirectTexture=this._indirectTexture.toJSON(A),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(A)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function I(o,a){return o[a.uuid]===void 0&&(o[a.uuid]=a.toJSON(A)),a.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(A).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(A).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=I(A.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const a=o.shapes;if(Array.isArray(a))for(let Q=0,n=a.length;Q<n;Q++){const s=a[Q];I(A.shapes,s)}else I(A.shapes,a)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(I(A.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let a=0,Q=this.material.length;a<Q;a++)o.push(I(A.materials,this.material[a]));i.material=o}else i.material=I(A.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(A).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){const a=this.animations[o];i.animations.push(I(A.animations,a))}}if(e){const o=C(A.geometries),a=C(A.materials),Q=C(A.textures),n=C(A.images),s=C(A.shapes),B=C(A.skeletons),E=C(A.animations),d=C(A.nodes);o.length>0&&(g.geometries=o),a.length>0&&(g.materials=a),Q.length>0&&(g.textures=Q),n.length>0&&(g.images=n),s.length>0&&(g.shapes=s),B.length>0&&(g.skeletons=B),E.length>0&&(g.animations=E),d.length>0&&(g.nodes=d)}return g.object=i,g;function C(o){const a=[];for(const Q in o){const n=o[Q];delete n.metadata,a.push(n)}return a}}clone(A){return new this.constructor().copy(this,A)}copy(A,e=!0){if(this.name=A.name,this.up.copy(A.up),this.position.copy(A.position),this.rotation.order=A.rotation.order,this.quaternion.copy(A.quaternion),this.scale.copy(A.scale),this.matrix.copy(A.matrix),this.matrixWorld.copy(A.matrixWorld),this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrixWorldAutoUpdate=A.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=A.matrixWorldNeedsUpdate,this.layers.mask=A.layers.mask,this.visible=A.visible,this.castShadow=A.castShadow,this.receiveShadow=A.receiveShadow,this.frustumCulled=A.frustumCulled,this.renderOrder=A.renderOrder,this.animations=A.animations.slice(),this.userData=JSON.parse(JSON.stringify(A.userData)),e===!0)for(let g=0;g<A.children.length;g++){const i=A.children[g];this.add(i.clone())}return this}}pg.DEFAULT_UP=new J(0,1,0),pg.DEFAULT_MATRIX_AUTO_UPDATE=!0,pg.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Vg=new J,vt=new J,zn=new J,Jt=new J,DI=new J,_I=new J,w0=new J,$n=new J,As=new J,es=new J,gs=new Ke,ts=new Ke,is=new Ke;class jg{constructor(A=new J,e=new J,g=new J){this.a=A,this.b=e,this.c=g}static getNormal(A,e,g,i){i.subVectors(g,e),Vg.subVectors(A,e),i.cross(Vg);const I=i.lengthSq();return I>0?i.multiplyScalar(1/Math.sqrt(I)):i.set(0,0,0)}static getBarycoord(A,e,g,i,I){Vg.subVectors(i,e),vt.subVectors(g,e),zn.subVectors(A,e);const C=Vg.dot(Vg),o=Vg.dot(vt),a=Vg.dot(zn),Q=vt.dot(vt),n=vt.dot(zn),s=C*Q-o*o;if(s===0)return I.set(0,0,0),null;const B=1/s,E=(Q*a-o*n)*B,d=(C*n-o*a)*B;return I.set(1-E-d,d,E)}static containsPoint(A,e,g,i){return this.getBarycoord(A,e,g,i,Jt)===null?!1:Jt.x>=0&&Jt.y>=0&&Jt.x+Jt.y<=1}static getInterpolation(A,e,g,i,I,C,o,a){return this.getBarycoord(A,e,g,i,Jt)===null?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(I,Jt.x),a.addScaledVector(C,Jt.y),a.addScaledVector(o,Jt.z),a)}static getInterpolatedAttribute(A,e,g,i,I,C){return gs.setScalar(0),ts.setScalar(0),is.setScalar(0),gs.fromBufferAttribute(A,e),ts.fromBufferAttribute(A,g),is.fromBufferAttribute(A,i),C.setScalar(0),C.addScaledVector(gs,I.x),C.addScaledVector(ts,I.y),C.addScaledVector(is,I.z),C}static isFrontFacing(A,e,g,i){return Vg.subVectors(g,e),vt.subVectors(A,e),Vg.cross(vt).dot(i)<0}set(A,e,g){return this.a.copy(A),this.b.copy(e),this.c.copy(g),this}setFromPointsAndIndices(A,e,g,i){return this.a.copy(A[e]),this.b.copy(A[g]),this.c.copy(A[i]),this}setFromAttributeAndIndices(A,e,g,i){return this.a.fromBufferAttribute(A,e),this.b.fromBufferAttribute(A,g),this.c.fromBufferAttribute(A,i),this}clone(){return new this.constructor().copy(this)}copy(A){return this.a.copy(A.a),this.b.copy(A.b),this.c.copy(A.c),this}getArea(){return Vg.subVectors(this.c,this.b),vt.subVectors(this.a,this.b),Vg.cross(vt).length()*.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(A){return jg.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,e){return jg.getBarycoord(A,this.a,this.b,this.c,e)}getInterpolation(A,e,g,i,I){return jg.getInterpolation(A,this.a,this.b,this.c,e,g,i,I)}containsPoint(A){return jg.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return jg.isFrontFacing(this.a,this.b,this.c,A)}intersectsBox(A){return A.intersectsTriangle(this)}closestPointToPoint(A,e){const g=this.a,i=this.b,I=this.c;let C,o;DI.subVectors(i,g),_I.subVectors(I,g),$n.subVectors(A,g);const a=DI.dot($n),Q=_I.dot($n);if(a<=0&&Q<=0)return e.copy(g);As.subVectors(A,i);const n=DI.dot(As),s=_I.dot(As);if(n>=0&&s<=n)return e.copy(i);const B=a*s-n*Q;if(B<=0&&a>=0&&n<=0)return C=a/(a-n),e.copy(g).addScaledVector(DI,C);es.subVectors(A,I);const E=DI.dot(es),d=_I.dot(es);if(d>=0&&E<=d)return e.copy(I);const c=E*Q-a*d;if(c<=0&&Q>=0&&d<=0)return o=Q/(Q-d),e.copy(g).addScaledVector(_I,o);const h=n*d-E*s;if(h<=0&&s-n>=0&&E-d>=0)return w0.subVectors(I,i),o=(s-n)/(s-n+(E-d)),e.copy(i).addScaledVector(w0,o);const r=1/(h+c+B);return C=c*r,o=B*r,e.copy(g).addScaledVector(DI,C).addScaledVector(_I,o)}equals(A){return A.a.equals(this.a)&&A.b.equals(this.b)&&A.c.equals(this.c)}}const p0={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},Qi={h:0,s:0,l:0},So={h:0,s:0,l:0};function Is(t,A,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?t+(A-t)*6*e:e<1/2?A:e<2/3?t+(A-t)*6*(2/3-e):t}class Ie{constructor(A,e,g){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(A,e,g)}set(A,e,g){if(e===void 0&&g===void 0){const i=A;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(A,e,g);return this}setScalar(A){return this.r=A,this.g=A,this.b=A,this}setHex(A,e=kg){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,Ce.colorSpaceToWorking(this,e),this}setRGB(A,e,g,i=Ce.workingColorSpace){return this.r=A,this.g=e,this.b=g,Ce.colorSpaceToWorking(this,i),this}setHSL(A,e,g,i=Ce.workingColorSpace){if(A=Rf(A,1),e=te(e,0,1),g=te(g,0,1),e===0)this.r=this.g=this.b=g;else{const I=g<=.5?g*(1+e):g+e-g*e,C=2*g-I;this.r=Is(C,I,A+1/3),this.g=Is(C,I,A),this.b=Is(C,I,A-1/3)}return Ce.colorSpaceToWorking(this,i),this}setStyle(A,e=kg){function g(I){I!==void 0&&parseFloat(I)<1&&LA("Color: Alpha component of "+A+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(A)){let I;const C=i[1],o=i[2];switch(C){case"rgb":case"rgba":if(I=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setRGB(Math.min(255,parseInt(I[1],10))/255,Math.min(255,parseInt(I[2],10))/255,Math.min(255,parseInt(I[3],10))/255,e);if(I=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setRGB(Math.min(100,parseInt(I[1],10))/100,Math.min(100,parseInt(I[2],10))/100,Math.min(100,parseInt(I[3],10))/100,e);break;case"hsl":case"hsla":if(I=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setHSL(parseFloat(I[1])/360,parseFloat(I[2])/100,parseFloat(I[3])/100,e);break;default:LA("Color: Unknown color model "+A)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(A)){const I=i[1],C=I.length;if(C===3)return this.setRGB(parseInt(I.charAt(0),16)/15,parseInt(I.charAt(1),16)/15,parseInt(I.charAt(2),16)/15,e);if(C===6)return this.setHex(parseInt(I,16),e);LA("Color: Invalid hex color "+A)}else if(A&&A.length>0)return this.setColorName(A,e);return this}setColorName(A,e=kg){const g=p0[A.toLowerCase()];return g!==void 0?this.setHex(g,e):LA("Color: Unknown color "+A),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(A){return this.r=A.r,this.g=A.g,this.b=A.b,this}copySRGBToLinear(A){return this.r=Mt(A.r),this.g=Mt(A.g),this.b=Mt(A.b),this}copyLinearToSRGB(A){return this.r=rI(A.r),this.g=rI(A.g),this.b=rI(A.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(A=kg){return Ce.workingToColorSpace(gg.copy(this),A),Math.round(te(gg.r*255,0,255))*65536+Math.round(te(gg.g*255,0,255))*256+Math.round(te(gg.b*255,0,255))}getHexString(A=kg){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,e=Ce.workingColorSpace){Ce.workingToColorSpace(gg.copy(this),e);const g=gg.r,i=gg.g,I=gg.b,C=Math.max(g,i,I),o=Math.min(g,i,I);let a,Q;const n=(o+C)/2;if(o===C)a=0,Q=0;else{const s=C-o;switch(Q=n<=.5?s/(C+o):s/(2-C-o),C){case g:a=(i-I)/s+(i<I?6:0);break;case i:a=(I-g)/s+2;break;case I:a=(g-i)/s+4;break}a/=6}return A.h=a,A.s=Q,A.l=n,A}getRGB(A,e=Ce.workingColorSpace){return Ce.workingToColorSpace(gg.copy(this),e),A.r=gg.r,A.g=gg.g,A.b=gg.b,A}getStyle(A=kg){Ce.workingToColorSpace(gg.copy(this),A);const e=gg.r,g=gg.g,i=gg.b;return A!==kg?`color(${A} ${e.toFixed(3)} ${g.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(g*255)},${Math.round(i*255)})`}offsetHSL(A,e,g){return this.getHSL(Qi),this.setHSL(Qi.h+A,Qi.s+e,Qi.l+g)}add(A){return this.r+=A.r,this.g+=A.g,this.b+=A.b,this}addColors(A,e){return this.r=A.r+e.r,this.g=A.g+e.g,this.b=A.b+e.b,this}addScalar(A){return this.r+=A,this.g+=A,this.b+=A,this}sub(A){return this.r=Math.max(0,this.r-A.r),this.g=Math.max(0,this.g-A.g),this.b=Math.max(0,this.b-A.b),this}multiply(A){return this.r*=A.r,this.g*=A.g,this.b*=A.b,this}multiplyScalar(A){return this.r*=A,this.g*=A,this.b*=A,this}lerp(A,e){return this.r+=(A.r-this.r)*e,this.g+=(A.g-this.g)*e,this.b+=(A.b-this.b)*e,this}lerpColors(A,e,g){return this.r=A.r+(e.r-A.r)*g,this.g=A.g+(e.g-A.g)*g,this.b=A.b+(e.b-A.b)*g,this}lerpHSL(A,e){this.getHSL(Qi),A.getHSL(So);const g=vn(Qi.h,So.h,e),i=vn(Qi.s,So.s,e),I=vn(Qi.l,So.l,e);return this.setHSL(g,i,I),this}setFromVector3(A){return this.r=A.x,this.g=A.y,this.b=A.z,this}applyMatrix3(A){const e=this.r,g=this.g,i=this.b,I=A.elements;return this.r=I[0]*e+I[3]*g+I[6]*i,this.g=I[1]*e+I[4]*g+I[7]*i,this.b=I[2]*e+I[5]*g+I[8]*i,this}equals(A){return A.r===this.r&&A.g===this.g&&A.b===this.b}fromArray(A,e=0){return this.r=A[e],this.g=A[e+1],this.b=A[e+2],this}toArray(A=[],e=0){return A[e]=this.r,A[e+1]=this.g,A[e+2]=this.b,A}fromBufferAttribute(A,e){return this.r=A.getX(e),this.g=A.getY(e),this.b=A.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const gg=new Ie;Ie.NAMES=p0;let Vf=0;class ko extends EI{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Vf++}),this.uuid=aC(),this.name="",this.type="Material",this.blending=oI,this.side=bt,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=UQ,this.blendDst=LQ,this.blendEquation=pi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ie(0,0,0),this.blendAlpha=0,this.depthFunc=aI,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=C0,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=BI,this.stencilZFail=BI,this.stencilZPass=BI,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(A){this._alphaTest>0!=A>0&&this.version++,this._alphaTest=A}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(A){if(A!==void 0)for(const e in A){const g=A[e];if(g===void 0){LA(`Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){LA(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(g):i&&i.isVector3&&g&&g.isVector3?i.copy(g):this[e]=g}}toJSON(A){const e=A===void 0||typeof A=="string";e&&(A={textures:{},images:{}});const g={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};g.uuid=this.uuid,g.type=this.type,this.name!==""&&(g.name=this.name),this.color&&this.color.isColor&&(g.color=this.color.getHex()),this.roughness!==void 0&&(g.roughness=this.roughness),this.metalness!==void 0&&(g.metalness=this.metalness),this.sheen!==void 0&&(g.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(g.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(g.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(g.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(g.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(g.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(g.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(g.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(g.shininess=this.shininess),this.clearcoat!==void 0&&(g.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(g.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(g.clearcoatMap=this.clearcoatMap.toJSON(A).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(g.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(A).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(g.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(A).uuid,g.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(g.sheenColorMap=this.sheenColorMap.toJSON(A).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(g.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(A).uuid),this.dispersion!==void 0&&(g.dispersion=this.dispersion),this.iridescence!==void 0&&(g.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(g.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(g.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(g.iridescenceMap=this.iridescenceMap.toJSON(A).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(g.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(A).uuid),this.anisotropy!==void 0&&(g.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(g.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(g.anisotropyMap=this.anisotropyMap.toJSON(A).uuid),this.map&&this.map.isTexture&&(g.map=this.map.toJSON(A).uuid),this.matcap&&this.matcap.isTexture&&(g.matcap=this.matcap.toJSON(A).uuid),this.alphaMap&&this.alphaMap.isTexture&&(g.alphaMap=this.alphaMap.toJSON(A).uuid),this.lightMap&&this.lightMap.isTexture&&(g.lightMap=this.lightMap.toJSON(A).uuid,g.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(g.aoMap=this.aoMap.toJSON(A).uuid,g.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(g.bumpMap=this.bumpMap.toJSON(A).uuid,g.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(g.normalMap=this.normalMap.toJSON(A).uuid,g.normalMapType=this.normalMapType,g.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(g.displacementMap=this.displacementMap.toJSON(A).uuid,g.displacementScale=this.displacementScale,g.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(g.roughnessMap=this.roughnessMap.toJSON(A).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(g.metalnessMap=this.metalnessMap.toJSON(A).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(g.emissiveMap=this.emissiveMap.toJSON(A).uuid),this.specularMap&&this.specularMap.isTexture&&(g.specularMap=this.specularMap.toJSON(A).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(g.specularIntensityMap=this.specularIntensityMap.toJSON(A).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(g.specularColorMap=this.specularColorMap.toJSON(A).uuid),this.envMap&&this.envMap.isTexture&&(g.envMap=this.envMap.toJSON(A).uuid,this.combine!==void 0&&(g.combine=this.combine)),this.envMapRotation!==void 0&&(g.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(g.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(g.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(g.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(g.gradientMap=this.gradientMap.toJSON(A).uuid),this.transmission!==void 0&&(g.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(g.transmissionMap=this.transmissionMap.toJSON(A).uuid),this.thickness!==void 0&&(g.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(g.thicknessMap=this.thicknessMap.toJSON(A).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(g.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(g.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(g.size=this.size),this.shadowSide!==null&&(g.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(g.sizeAttenuation=this.sizeAttenuation),this.blending!==oI&&(g.blending=this.blending),this.side!==bt&&(g.side=this.side),this.vertexColors===!0&&(g.vertexColors=!0),this.opacity<1&&(g.opacity=this.opacity),this.transparent===!0&&(g.transparent=!0),this.blendSrc!==UQ&&(g.blendSrc=this.blendSrc),this.blendDst!==LQ&&(g.blendDst=this.blendDst),this.blendEquation!==pi&&(g.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(g.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(g.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(g.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(g.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(g.blendAlpha=this.blendAlpha),this.depthFunc!==aI&&(g.depthFunc=this.depthFunc),this.depthTest===!1&&(g.depthTest=this.depthTest),this.depthWrite===!1&&(g.depthWrite=this.depthWrite),this.colorWrite===!1&&(g.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(g.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==C0&&(g.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(g.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(g.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==BI&&(g.stencilFail=this.stencilFail),this.stencilZFail!==BI&&(g.stencilZFail=this.stencilZFail),this.stencilZPass!==BI&&(g.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(g.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(g.rotation=this.rotation),this.polygonOffset===!0&&(g.polygonOffset=!0),this.polygonOffsetFactor!==0&&(g.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(g.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(g.linewidth=this.linewidth),this.dashSize!==void 0&&(g.dashSize=this.dashSize),this.gapSize!==void 0&&(g.gapSize=this.gapSize),this.scale!==void 0&&(g.scale=this.scale),this.dithering===!0&&(g.dithering=!0),this.alphaTest>0&&(g.alphaTest=this.alphaTest),this.alphaHash===!0&&(g.alphaHash=!0),this.alphaToCoverage===!0&&(g.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(g.premultipliedAlpha=!0),this.forceSinglePass===!0&&(g.forceSinglePass=!0),this.allowOverride===!1&&(g.allowOverride=!1),this.wireframe===!0&&(g.wireframe=!0),this.wireframeLinewidth>1&&(g.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(g.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(g.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(g.flatShading=!0),this.visible===!1&&(g.visible=!1),this.toneMapped===!1&&(g.toneMapped=!1),this.fog===!1&&(g.fog=!1),Object.keys(this.userData).length>0&&(g.userData=this.userData);function i(I){const C=[];for(const o in I){const a=I[o];delete a.metadata,C.push(a)}return C}if(e){const I=i(A.textures),C=i(A.images);I.length>0&&(g.textures=I),C.length>0&&(g.images=C)}return g}clone(){return new this.constructor().copy(this)}copy(A){this.name=A.name,this.blending=A.blending,this.side=A.side,this.vertexColors=A.vertexColors,this.opacity=A.opacity,this.transparent=A.transparent,this.blendSrc=A.blendSrc,this.blendDst=A.blendDst,this.blendEquation=A.blendEquation,this.blendSrcAlpha=A.blendSrcAlpha,this.blendDstAlpha=A.blendDstAlpha,this.blendEquationAlpha=A.blendEquationAlpha,this.blendColor.copy(A.blendColor),this.blendAlpha=A.blendAlpha,this.depthFunc=A.depthFunc,this.depthTest=A.depthTest,this.depthWrite=A.depthWrite,this.stencilWriteMask=A.stencilWriteMask,this.stencilFunc=A.stencilFunc,this.stencilRef=A.stencilRef,this.stencilFuncMask=A.stencilFuncMask,this.stencilFail=A.stencilFail,this.stencilZFail=A.stencilZFail,this.stencilZPass=A.stencilZPass,this.stencilWrite=A.stencilWrite;const e=A.clippingPlanes;let g=null;if(e!==null){const i=e.length;g=new Array(i);for(let I=0;I!==i;++I)g[I]=e[I].clone()}return this.clippingPlanes=g,this.clipIntersection=A.clipIntersection,this.clipShadows=A.clipShadows,this.shadowSide=A.shadowSide,this.colorWrite=A.colorWrite,this.precision=A.precision,this.polygonOffset=A.polygonOffset,this.polygonOffsetFactor=A.polygonOffsetFactor,this.polygonOffsetUnits=A.polygonOffsetUnits,this.dithering=A.dithering,this.alphaTest=A.alphaTest,this.alphaHash=A.alphaHash,this.alphaToCoverage=A.alphaToCoverage,this.premultipliedAlpha=A.premultipliedAlpha,this.forceSinglePass=A.forceSinglePass,this.allowOverride=A.allowOverride,this.visible=A.visible,this.toneMapped=A.toneMapped,this.userData=JSON.parse(JSON.stringify(A.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(A){A===!0&&this.version++}}class m0 extends ko{constructor(A){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ie(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 Lt,this.combine=Hr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}const Te=new J,Ro=new Be;let jf=0;class Bt{constructor(A,e,g=!1){if(Array.isArray(A))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:jf++}),this.name="",this.array=A,this.itemSize=e,this.count=A!==void 0?A.length/e:0,this.normalized=g,this.usage=o0,this.updateRanges=[],this.gpuType=Qt,this.version=0}onUploadCallback(){}set needsUpdate(A){A===!0&&this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,e){this.updateRanges.push({start:A,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.name=A.name,this.array=new A.array.constructor(A.array),this.itemSize=A.itemSize,this.count=A.count,this.normalized=A.normalized,this.usage=A.usage,this.gpuType=A.gpuType,this}copyAt(A,e,g){A*=this.itemSize,g*=e.itemSize;for(let i=0,I=this.itemSize;i<I;i++)this.array[A+i]=e.array[g+i];return this}copyArray(A){return this.array.set(A),this}applyMatrix3(A){if(this.itemSize===2)for(let e=0,g=this.count;e<g;e++)Ro.fromBufferAttribute(this,e),Ro.applyMatrix3(A),this.setXY(e,Ro.x,Ro.y);else if(this.itemSize===3)for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix3(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyMatrix4(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix4(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyNormalMatrix(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyNormalMatrix(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}transformDirection(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.transformDirection(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}set(A,e=0){return this.array.set(A,e),this}getComponent(A,e){let g=this.array[A*this.itemSize+e];return this.normalized&&(g=QC(g,this.array)),g}setComponent(A,e,g){return this.normalized&&(g=hg(g,this.array)),this.array[A*this.itemSize+e]=g,this}getX(A){let e=this.array[A*this.itemSize];return this.normalized&&(e=QC(e,this.array)),e}setX(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize]=e,this}getY(A){let e=this.array[A*this.itemSize+1];return this.normalized&&(e=QC(e,this.array)),e}setY(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+1]=e,this}getZ(A){let e=this.array[A*this.itemSize+2];return this.normalized&&(e=QC(e,this.array)),e}setZ(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+2]=e,this}getW(A){let e=this.array[A*this.itemSize+3];return this.normalized&&(e=QC(e,this.array)),e}setW(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+3]=e,this}setXY(A,e,g){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array)),this.array[A+0]=e,this.array[A+1]=g,this}setXYZ(A,e,g,i){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array),i=hg(i,this.array)),this.array[A+0]=e,this.array[A+1]=g,this.array[A+2]=i,this}setXYZW(A,e,g,i,I){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array),i=hg(i,this.array),I=hg(I,this.array)),this.array[A+0]=e,this.array[A+1]=g,this.array[A+2]=i,this.array[A+3]=I,this}onUpload(A){return this.onUploadCallback=A,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const A={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(A.name=this.name),this.usage!==o0&&(A.usage=this.usage),A}}class y0 extends Bt{constructor(A,e,g){super(new Uint16Array(A),e,g)}}class b0 extends Bt{constructor(A,e,g){super(new Uint32Array(A),e,g)}}class Ig extends Bt{constructor(A,e,g){super(new Float32Array(A),e,g)}}let Wf=0;const Rg=new Ye,Cs=new pg,wI=new J,mg=new sC,cC=new sC,Xe=new J;class Wg extends EI{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Wf++}),this.uuid=aC(),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(A){return Array.isArray(A)?this.index=new(Q0(A)?b0:y0)(A,1):this.index=A,this}setIndirect(A,e=0){return this.indirect=A,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(A){return this.attributes[A]}setAttribute(A,e){return this.attributes[A]=e,this}deleteAttribute(A){return delete this.attributes[A],this}hasAttribute(A){return this.attributes[A]!==void 0}addGroup(A,e,g=0){this.groups.push({start:A,count:e,materialIndex:g})}clearGroups(){this.groups=[]}setDrawRange(A,e){this.drawRange.start=A,this.drawRange.count=e}applyMatrix4(A){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(A),e.needsUpdate=!0);const g=this.attributes.normal;if(g!==void 0){const I=new YA().getNormalMatrix(A);g.applyNormalMatrix(I),g.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(A),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(A){return Rg.makeRotationFromQuaternion(A),this.applyMatrix4(Rg),this}rotateX(A){return Rg.makeRotationX(A),this.applyMatrix4(Rg),this}rotateY(A){return Rg.makeRotationY(A),this.applyMatrix4(Rg),this}rotateZ(A){return Rg.makeRotationZ(A),this.applyMatrix4(Rg),this}translate(A,e,g){return Rg.makeTranslation(A,e,g),this.applyMatrix4(Rg),this}scale(A,e,g){return Rg.makeScale(A,e,g),this.applyMatrix4(Rg),this}lookAt(A){return Cs.lookAt(A),Cs.updateMatrix(),this.applyMatrix4(Cs.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(wI).negate(),this.translate(wI.x,wI.y,wI.z),this}setFromPoints(A){const e=this.getAttribute("position");if(e===void 0){const g=[];for(let i=0,I=A.length;i<I;i++){const C=A[i];g.push(C.x,C.y,C.z||0)}this.setAttribute("position",new Ig(g,3))}else{const g=Math.min(A.length,e.count);for(let i=0;i<g;i++){const I=A[i];e.setXYZ(i,I.x,I.y,I.z||0)}A.length>e.count&&LA("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new sC);const A=this.attributes.position,e=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){ae("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new J(-1/0,-1/0,-1/0),new J(1/0,1/0,1/0));return}if(A!==void 0){if(this.boundingBox.setFromBufferAttribute(A),e)for(let g=0,i=e.length;g<i;g++){const I=e[g];mg.setFromBufferAttribute(I),this.morphTargetsRelative?(Xe.addVectors(this.boundingBox.min,mg.min),this.boundingBox.expandByPoint(Xe),Xe.addVectors(this.boundingBox.max,mg.max),this.boundingBox.expandByPoint(Xe)):(this.boundingBox.expandByPoint(mg.min),this.boundingBox.expandByPoint(mg.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&ae('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 Vn);const A=this.attributes.position,e=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){ae("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new J,1/0);return}if(A){const g=this.boundingSphere.center;if(mg.setFromBufferAttribute(A),e)for(let I=0,C=e.length;I<C;I++){const o=e[I];cC.setFromBufferAttribute(o),this.morphTargetsRelative?(Xe.addVectors(mg.min,cC.min),mg.expandByPoint(Xe),Xe.addVectors(mg.max,cC.max),mg.expandByPoint(Xe)):(mg.expandByPoint(cC.min),mg.expandByPoint(cC.max))}mg.getCenter(g);let i=0;for(let I=0,C=A.count;I<C;I++)Xe.fromBufferAttribute(A,I),i=Math.max(i,g.distanceToSquared(Xe));if(e)for(let I=0,C=e.length;I<C;I++){const o=e[I],a=this.morphTargetsRelative;for(let Q=0,n=o.count;Q<n;Q++)Xe.fromBufferAttribute(o,Q),a&&(wI.fromBufferAttribute(A,Q),Xe.add(wI)),i=Math.max(i,g.distanceToSquared(Xe))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&ae('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const A=this.index,e=this.attributes;if(A===null||e.position===void 0||e.normal===void 0||e.uv===void 0){ae("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const g=e.position,i=e.normal,I=e.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Bt(new Float32Array(4*g.count),4));const C=this.getAttribute("tangent"),o=[],a=[];for(let k=0;k<g.count;k++)o[k]=new J,a[k]=new J;const Q=new J,n=new J,s=new J,B=new Be,E=new Be,d=new Be,c=new J,h=new J;function r(k,x,w){Q.fromBufferAttribute(g,k),n.fromBufferAttribute(g,x),s.fromBufferAttribute(g,w),B.fromBufferAttribute(I,k),E.fromBufferAttribute(I,x),d.fromBufferAttribute(I,w),n.sub(Q),s.sub(Q),E.sub(B),d.sub(B);const N=1/(E.x*d.y-d.x*E.y);isFinite(N)&&(c.copy(n).multiplyScalar(d.y).addScaledVector(s,-E.y).multiplyScalar(N),h.copy(s).multiplyScalar(E.x).addScaledVector(n,-d.x).multiplyScalar(N),o[k].add(c),o[x].add(c),o[w].add(c),a[k].add(h),a[x].add(h),a[w].add(h))}let f=this.groups;f.length===0&&(f=[{start:0,count:A.count}]);for(let k=0,x=f.length;k<x;++k){const w=f[k],N=w.start,U=w.count;for(let K=N,P=N+U;K<P;K+=3)r(A.getX(K+0),A.getX(K+1),A.getX(K+2))}const _=new J,l=new J,D=new J,p=new J;function y(k){D.fromBufferAttribute(i,k),p.copy(D);const x=o[k];_.copy(x),_.sub(D.multiplyScalar(D.dot(x))).normalize(),l.crossVectors(p,x);const N=l.dot(a[k])<0?-1:1;C.setXYZW(k,_.x,_.y,_.z,N)}for(let k=0,x=f.length;k<x;++k){const w=f[k],N=w.start,U=w.count;for(let K=N,P=N+U;K<P;K+=3)y(A.getX(K+0)),y(A.getX(K+1)),y(A.getX(K+2))}}computeVertexNormals(){const A=this.index,e=this.getAttribute("position");if(e!==void 0){let g=this.getAttribute("normal");if(g===void 0)g=new Bt(new Float32Array(e.count*3),3),this.setAttribute("normal",g);else for(let B=0,E=g.count;B<E;B++)g.setXYZ(B,0,0,0);const i=new J,I=new J,C=new J,o=new J,a=new J,Q=new J,n=new J,s=new J;if(A)for(let B=0,E=A.count;B<E;B+=3){const d=A.getX(B+0),c=A.getX(B+1),h=A.getX(B+2);i.fromBufferAttribute(e,d),I.fromBufferAttribute(e,c),C.fromBufferAttribute(e,h),n.subVectors(C,I),s.subVectors(i,I),n.cross(s),o.fromBufferAttribute(g,d),a.fromBufferAttribute(g,c),Q.fromBufferAttribute(g,h),o.add(n),a.add(n),Q.add(n),g.setXYZ(d,o.x,o.y,o.z),g.setXYZ(c,a.x,a.y,a.z),g.setXYZ(h,Q.x,Q.y,Q.z)}else for(let B=0,E=e.count;B<E;B+=3)i.fromBufferAttribute(e,B+0),I.fromBufferAttribute(e,B+1),C.fromBufferAttribute(e,B+2),n.subVectors(C,I),s.subVectors(i,I),n.cross(s),g.setXYZ(B+0,n.x,n.y,n.z),g.setXYZ(B+1,n.x,n.y,n.z),g.setXYZ(B+2,n.x,n.y,n.z);this.normalizeNormals(),g.needsUpdate=!0}}normalizeNormals(){const A=this.attributes.normal;for(let e=0,g=A.count;e<g;e++)Xe.fromBufferAttribute(A,e),Xe.normalize(),A.setXYZ(e,Xe.x,Xe.y,Xe.z)}toNonIndexed(){function A(o,a){const Q=o.array,n=o.itemSize,s=o.normalized,B=new Q.constructor(a.length*n);let E=0,d=0;for(let c=0,h=a.length;c<h;c++){o.isInterleavedBufferAttribute?E=a[c]*o.data.stride+o.offset:E=a[c]*n;for(let r=0;r<n;r++)B[d++]=Q[E++]}return new Bt(B,n,s)}if(this.index===null)return LA("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new Wg,g=this.index.array,i=this.attributes;for(const o in i){const a=i[o],Q=A(a,g);e.setAttribute(o,Q)}const I=this.morphAttributes;for(const o in I){const a=[],Q=I[o];for(let n=0,s=Q.length;n<s;n++){const B=Q[n],E=A(B,g);a.push(E)}e.morphAttributes[o]=a}e.morphTargetsRelative=this.morphTargetsRelative;const C=this.groups;for(let o=0,a=C.length;o<a;o++){const Q=C[o];e.addGroup(Q.start,Q.count,Q.materialIndex)}return e}toJSON(){const A={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(A.uuid=this.uuid,A.type=this.type,this.name!==""&&(A.name=this.name),Object.keys(this.userData).length>0&&(A.userData=this.userData),this.parameters!==void 0){const a=this.parameters;for(const Q in a)a[Q]!==void 0&&(A[Q]=a[Q]);return A}A.data={attributes:{}};const e=this.index;e!==null&&(A.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const g=this.attributes;for(const a in g){const Q=g[a];A.data.attributes[a]=Q.toJSON(A.data)}const i={};let I=!1;for(const a in this.morphAttributes){const Q=this.morphAttributes[a],n=[];for(let s=0,B=Q.length;s<B;s++){const E=Q[s];n.push(E.toJSON(A.data))}n.length>0&&(i[a]=n,I=!0)}I&&(A.data.morphAttributes=i,A.data.morphTargetsRelative=this.morphTargetsRelative);const C=this.groups;C.length>0&&(A.data.groups=JSON.parse(JSON.stringify(C)));const o=this.boundingSphere;return o!==null&&(A.data.boundingSphere=o.toJSON()),A}clone(){return new this.constructor().copy(this)}copy(A){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=A.name;const g=A.index;g!==null&&this.setIndex(g.clone());const i=A.attributes;for(const Q in i){const n=i[Q];this.setAttribute(Q,n.clone(e))}const I=A.morphAttributes;for(const Q in I){const n=[],s=I[Q];for(let B=0,E=s.length;B<E;B++)n.push(s[B].clone(e));this.morphAttributes[Q]=n}this.morphTargetsRelative=A.morphTargetsRelative;const C=A.groups;for(let Q=0,n=C.length;Q<n;Q++){const s=C[Q];this.addGroup(s.start,s.count,s.materialIndex)}const o=A.boundingBox;o!==null&&(this.boundingBox=o.clone());const a=A.boundingSphere;return a!==null&&(this.boundingSphere=a.clone()),this.drawRange.start=A.drawRange.start,this.drawRange.count=A.drawRange.count,this.userData=A.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const N0=new Ye,ki=new Jf,Go=new Vn,S0=new J,Mo=new J,Fo=new J,Uo=new J,os=new J,Lo=new J,k0=new J,Ko=new J;class Xg extends pg{constructor(A=new Wg,e=new m0){super(),this.isMesh=!0,this.type="Mesh",this.geometry=A,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(A,e){return super.copy(A,e),A.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=A.morphTargetInfluences.slice()),A.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},A.morphTargetDictionary)),this.material=Array.isArray(A.material)?A.material.slice():A.material,this.geometry=A.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,g=Object.keys(e);if(g.length>0){const i=e[g[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let I=0,C=i.length;I<C;I++){const o=i[I].name||String(I);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=I}}}}getVertexPosition(A,e){const g=this.geometry,i=g.attributes.position,I=g.morphAttributes.position,C=g.morphTargetsRelative;e.fromBufferAttribute(i,A);const o=this.morphTargetInfluences;if(I&&o){Lo.set(0,0,0);for(let a=0,Q=I.length;a<Q;a++){const n=o[a],s=I[a];n!==0&&(os.fromBufferAttribute(s,A),C?Lo.addScaledVector(os,n):Lo.addScaledVector(os.sub(e),n))}e.add(Lo)}return e}raycast(A,e){const g=this.geometry,i=this.material,I=this.matrixWorld;i!==void 0&&(g.boundingSphere===null&&g.computeBoundingSphere(),Go.copy(g.boundingSphere),Go.applyMatrix4(I),ki.copy(A.ray).recast(A.near),!(Go.containsPoint(ki.origin)===!1&&(ki.intersectSphere(Go,S0)===null||ki.origin.distanceToSquared(S0)>(A.far-A.near)**2))&&(N0.copy(I).invert(),ki.copy(A.ray).applyMatrix4(N0),!(g.boundingBox!==null&&ki.intersectsBox(g.boundingBox)===!1)&&this._computeIntersections(A,e,ki)))}_computeIntersections(A,e,g){let i;const I=this.geometry,C=this.material,o=I.index,a=I.attributes.position,Q=I.attributes.uv,n=I.attributes.uv1,s=I.attributes.normal,B=I.groups,E=I.drawRange;if(o!==null)if(Array.isArray(C))for(let d=0,c=B.length;d<c;d++){const h=B[d],r=C[h.materialIndex],f=Math.max(h.start,E.start),_=Math.min(o.count,Math.min(h.start+h.count,E.start+E.count));for(let l=f,D=_;l<D;l+=3){const p=o.getX(l),y=o.getX(l+1),k=o.getX(l+2);i=vo(this,r,A,g,Q,n,s,p,y,k),i&&(i.faceIndex=Math.floor(l/3),i.face.materialIndex=h.materialIndex,e.push(i))}}else{const d=Math.max(0,E.start),c=Math.min(o.count,E.start+E.count);for(let h=d,r=c;h<r;h+=3){const f=o.getX(h),_=o.getX(h+1),l=o.getX(h+2);i=vo(this,C,A,g,Q,n,s,f,_,l),i&&(i.faceIndex=Math.floor(h/3),e.push(i))}}else if(a!==void 0)if(Array.isArray(C))for(let d=0,c=B.length;d<c;d++){const h=B[d],r=C[h.materialIndex],f=Math.max(h.start,E.start),_=Math.min(a.count,Math.min(h.start+h.count,E.start+E.count));for(let l=f,D=_;l<D;l+=3){const p=l,y=l+1,k=l+2;i=vo(this,r,A,g,Q,n,s,p,y,k),i&&(i.faceIndex=Math.floor(l/3),i.face.materialIndex=h.materialIndex,e.push(i))}}else{const d=Math.max(0,E.start),c=Math.min(a.count,E.start+E.count);for(let h=d,r=c;h<r;h+=3){const f=h,_=h+1,l=h+2;i=vo(this,C,A,g,Q,n,s,f,_,l),i&&(i.faceIndex=Math.floor(h/3),e.push(i))}}}}function Xf(t,A,e,g,i,I,C,o){let a;if(A.side===tg?a=g.intersectTriangle(C,I,i,!0,o):a=g.intersectTriangle(i,I,C,A.side===bt,o),a===null)return null;Ko.copy(o),Ko.applyMatrix4(t.matrixWorld);const Q=e.ray.origin.distanceTo(Ko);return Q<e.near||Q>e.far?null:{distance:Q,point:Ko.clone(),object:t}}function vo(t,A,e,g,i,I,C,o,a,Q){t.getVertexPosition(o,Mo),t.getVertexPosition(a,Fo),t.getVertexPosition(Q,Uo);const n=Xf(t,A,e,g,Mo,Fo,Uo,k0);if(n){const s=new J;jg.getBarycoord(k0,Mo,Fo,Uo,s),i&&(n.uv=jg.getInterpolatedAttribute(i,o,a,Q,s,new Be)),I&&(n.uv1=jg.getInterpolatedAttribute(I,o,a,Q,s,new Be)),C&&(n.normal=jg.getInterpolatedAttribute(C,o,a,Q,s,new J),n.normal.dot(g.direction)>0&&n.normal.multiplyScalar(-1));const B={a:o,b:a,c:Q,normal:new J,materialIndex:0};jg.getNormal(Mo,Fo,Uo,B.normal),n.face=B,n.barycoord=s}return n}class hC extends Wg{constructor(A=1,e=1,g=1,i=1,I=1,C=1){super(),this.type="BoxGeometry",this.parameters={width:A,height:e,depth:g,widthSegments:i,heightSegments:I,depthSegments:C};const o=this;i=Math.floor(i),I=Math.floor(I),C=Math.floor(C);const a=[],Q=[],n=[],s=[];let B=0,E=0;d("z","y","x",-1,-1,g,e,A,C,I,0),d("z","y","x",1,-1,g,e,-A,C,I,1),d("x","z","y",1,1,A,g,e,i,C,2),d("x","z","y",1,-1,A,g,-e,i,C,3),d("x","y","z",1,-1,A,e,g,i,I,4),d("x","y","z",-1,-1,A,e,-g,i,I,5),this.setIndex(a),this.setAttribute("position",new Ig(Q,3)),this.setAttribute("normal",new Ig(n,3)),this.setAttribute("uv",new Ig(s,2));function d(c,h,r,f,_,l,D,p,y,k,x){const w=l/y,N=D/k,U=l/2,K=D/2,P=p/2,j=y+1,H=k+1;let O=0,z=0;const xA=new J;for(let sA=0;sA<H;sA++){const fA=sA*N-K;for(let JA=0;JA<j;JA++){const vA=JA*w-U;xA[c]=vA*f,xA[h]=fA*_,xA[r]=P,Q.push(xA.x,xA.y,xA.z),xA[c]=0,xA[h]=0,xA[r]=p>0?1:-1,n.push(xA.x,xA.y,xA.z),s.push(JA/y),s.push(1-sA/k),O+=1}}for(let sA=0;sA<k;sA++)for(let fA=0;fA<y;fA++){const JA=B+fA+j*sA,vA=B+fA+j*(sA+1),be=B+(fA+1)+j*(sA+1),le=B+(fA+1)+j*sA;a.push(JA,vA,le),a.push(vA,be,le),z+=6}o.addGroup(E,z,x),E+=z,B+=O}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new hC(A.width,A.height,A.depth,A.widthSegments,A.heightSegments,A.depthSegments)}}function pI(t){const A={};for(const e in t){A[e]={};for(const g in t[e]){const i=t[e][g];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(LA("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),A[e][g]=null):A[e][g]=i.clone():Array.isArray(i)?A[e][g]=i.slice():A[e][g]=i}}return A}function Cg(t){const A={};for(let e=0;e<t.length;e++){const g=pI(t[e]);for(const i in g)A[i]=g[i]}return A}function Zf(t){const A=[];for(let e=0;e<t.length;e++)A.push(t[e].clone());return A}function R0(t){const A=t.getRenderTarget();return A===null?t.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ce.workingColorSpace}const zf={clone:pI,merge:Cg};var $f=`void main() {
|
|
151
|
+
*/const MQ="182",Xl=0,Yr=1,Zl=2,Bo=1,zl=2,iC=3,bt=0,tg=1,Nt=2,St=0,oI=1,FQ=2,Tr=3,qr=4,$l=5,mi=100,Af=101,ef=102,gf=103,tf=104,If=200,Cf=201,of=202,af=203,UQ=204,LQ=205,Qf=206,nf=207,sf=208,Bf=209,Ef=210,rf=211,cf=212,hf=213,df=214,KQ=0,vQ=1,JQ=2,aI=3,YQ=4,TQ=5,qQ=6,HQ=7,Hr=0,xf=1,lf=2,ot=0,Pr=1,Or=2,Vr=3,jr=4,Wr=5,Xr=6,Zr=7,zr=300,yi=301,QI=302,PQ=303,OQ=304,Eo=306,VQ=1e3,kt=1001,jQ=1002,$e=1003,ff=1004,ro=1005,Ag=1006,WQ=1007,bi=1008,Sg=1009,$r=1010,A0=1011,IC=1012,XQ=1013,at=1014,Qt=1015,Rt=1016,ZQ=1017,zQ=1018,CC=1020,e0=35902,g0=35899,t0=1021,i0=1022,Hg=1023,Gt=1026,Ni=1027,I0=1028,$Q=1029,nI=1030,An=1031,en=1033,co=33776,ho=33777,xo=33778,lo=33779,gn=35840,tn=35841,In=35842,Cn=35843,on=36196,an=37492,Qn=37496,nn=37488,sn=37489,Bn=37490,En=37491,rn=37808,cn=37809,hn=37810,dn=37811,xn=37812,ln=37813,fn=37814,un=37815,Dn=37816,_n=37817,wn=37818,pn=37819,mn=37820,yn=37821,bn=36492,Nn=36494,Sn=36495,kn=36283,Rn=36284,Gn=36285,Mn=36286,uf=3200,Df=0,_f=1,ii="",kg="srgb",sI="srgb-linear",fo="linear",re="srgb",BI=7680,C0=519,wf=512,pf=513,mf=514,Fn=515,yf=516,bf=517,Un=518,Nf=519,o0=35044,a0="300 es",nt=2e3,uo=2001;function Q0(t){for(let A=t.length-1;A>=0;--A)if(t[A]>=65535)return!0;return!1}function Do(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Sf(){const t=Do("canvas");return t.style.display="block",t}const n0={};function s0(...t){const A="THREE."+t.shift();console.log(A,...t)}function LA(...t){const A="THREE."+t.shift();console.warn(A,...t)}function ae(...t){const A="THREE."+t.shift();console.error(A,...t)}function oC(...t){const A=t.join(" ");A in n0||(n0[A]=!0,LA(...t))}function kf(t,A,e){return new Promise(function(g,i){function I(){switch(t.clientWaitSync(A,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(I,e);break;default:g()}}setTimeout(I,e)})}class EI{addEventListener(A,e){this._listeners===void 0&&(this._listeners={});const g=this._listeners;g[A]===void 0&&(g[A]=[]),g[A].indexOf(e)===-1&&g[A].push(e)}hasEventListener(A,e){const g=this._listeners;return g===void 0?!1:g[A]!==void 0&&g[A].indexOf(e)!==-1}removeEventListener(A,e){const g=this._listeners;if(g===void 0)return;const i=g[A];if(i!==void 0){const I=i.indexOf(e);I!==-1&&i.splice(I,1)}}dispatchEvent(A){const e=this._listeners;if(e===void 0)return;const g=e[A.type];if(g!==void 0){A.target=this;const i=g.slice(0);for(let I=0,C=i.length;I<C;I++)i[I].call(this,A);A.target=null}}}const eg=["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"],Ln=Math.PI/180,Kn=180/Math.PI;function aC(){const t=Math.random()*4294967295|0,A=Math.random()*4294967295|0,e=Math.random()*4294967295|0,g=Math.random()*4294967295|0;return(eg[t&255]+eg[t>>8&255]+eg[t>>16&255]+eg[t>>24&255]+"-"+eg[A&255]+eg[A>>8&255]+"-"+eg[A>>16&15|64]+eg[A>>24&255]+"-"+eg[e&63|128]+eg[e>>8&255]+"-"+eg[e>>16&255]+eg[e>>24&255]+eg[g&255]+eg[g>>8&255]+eg[g>>16&255]+eg[g>>24&255]).toLowerCase()}function te(t,A,e){return Math.max(A,Math.min(e,t))}function Rf(t,A){return(t%A+A)%A}function vn(t,A,e){return(1-e)*t+e*A}function QC(t,A){switch(A.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function hg(t,A){switch(A.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}class Be{constructor(A=0,e=0){Be.prototype.isVector2=!0,this.x=A,this.y=e}get width(){return this.x}set width(A){this.x=A}get height(){return this.y}set height(A){this.y=A}set(A,e){return this.x=A,this.y=e,this}setScalar(A){return this.x=A,this.y=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y)}copy(A){return this.x=A.x,this.y=A.y,this}add(A){return this.x+=A.x,this.y+=A.y,this}addScalar(A){return this.x+=A,this.y+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this}subScalar(A){return this.x-=A,this.y-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this}multiply(A){return this.x*=A.x,this.y*=A.y,this}multiplyScalar(A){return this.x*=A,this.y*=A,this}divide(A){return this.x/=A.x,this.y/=A.y,this}divideScalar(A){return this.multiplyScalar(1/A)}applyMatrix3(A){const e=this.x,g=this.y,i=A.elements;return this.x=i[0]*e+i[3]*g+i[6],this.y=i[1]*e+i[4]*g+i[7],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y}cross(A){return this.x*A.y-this.y*A.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(A){const e=Math.sqrt(this.lengthSq()*A.lengthSq());if(e===0)return Math.PI/2;const g=this.dot(A)/e;return Math.acos(te(g,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const e=this.x-A.x,g=this.y-A.y;return e*e+g*g}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this}equals(A){return A.x===this.x&&A.y===this.y}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this}rotateAround(A,e){const g=Math.cos(e),i=Math.sin(e),I=this.x-A.x,C=this.y-A.y;return this.x=I*g-C*i+A.x,this.y=I*i+C*g+A.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class nC{constructor(A=0,e=0,g=0,i=1){this.isQuaternion=!0,this._x=A,this._y=e,this._z=g,this._w=i}static slerpFlat(A,e,g,i,I,C,o){let a=g[i+0],Q=g[i+1],n=g[i+2],s=g[i+3],B=I[C+0],E=I[C+1],d=I[C+2],c=I[C+3];if(o<=0){A[e+0]=a,A[e+1]=Q,A[e+2]=n,A[e+3]=s;return}if(o>=1){A[e+0]=B,A[e+1]=E,A[e+2]=d,A[e+3]=c;return}if(s!==c||a!==B||Q!==E||n!==d){let h=a*B+Q*E+n*d+s*c;h<0&&(B=-B,E=-E,d=-d,c=-c,h=-h);let r=1-o;if(h<.9995){const f=Math.acos(h),_=Math.sin(f);r=Math.sin(r*f)/_,o=Math.sin(o*f)/_,a=a*r+B*o,Q=Q*r+E*o,n=n*r+d*o,s=s*r+c*o}else{a=a*r+B*o,Q=Q*r+E*o,n=n*r+d*o,s=s*r+c*o;const f=1/Math.sqrt(a*a+Q*Q+n*n+s*s);a*=f,Q*=f,n*=f,s*=f}}A[e]=a,A[e+1]=Q,A[e+2]=n,A[e+3]=s}static multiplyQuaternionsFlat(A,e,g,i,I,C){const o=g[i],a=g[i+1],Q=g[i+2],n=g[i+3],s=I[C],B=I[C+1],E=I[C+2],d=I[C+3];return A[e]=o*d+n*s+a*E-Q*B,A[e+1]=a*d+n*B+Q*s-o*E,A[e+2]=Q*d+n*E+o*B-a*s,A[e+3]=n*d-o*s-a*B-Q*E,A}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get w(){return this._w}set w(A){this._w=A,this._onChangeCallback()}set(A,e,g,i){return this._x=A,this._y=e,this._z=g,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(A){return this._x=A.x,this._y=A.y,this._z=A.z,this._w=A.w,this._onChangeCallback(),this}setFromEuler(A,e=!0){const g=A._x,i=A._y,I=A._z,C=A._order,o=Math.cos,a=Math.sin,Q=o(g/2),n=o(i/2),s=o(I/2),B=a(g/2),E=a(i/2),d=a(I/2);switch(C){case"XYZ":this._x=B*n*s+Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s-B*E*d;break;case"YXZ":this._x=B*n*s+Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s+B*E*d;break;case"ZXY":this._x=B*n*s-Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s-B*E*d;break;case"ZYX":this._x=B*n*s-Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s+B*E*d;break;case"YZX":this._x=B*n*s+Q*E*d,this._y=Q*E*s+B*n*d,this._z=Q*n*d-B*E*s,this._w=Q*n*s-B*E*d;break;case"XZY":this._x=B*n*s-Q*E*d,this._y=Q*E*s-B*n*d,this._z=Q*n*d+B*E*s,this._w=Q*n*s+B*E*d;break;default:LA("Quaternion: .setFromEuler() encountered an unknown order: "+C)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(A,e){const g=e/2,i=Math.sin(g);return this._x=A.x*i,this._y=A.y*i,this._z=A.z*i,this._w=Math.cos(g),this._onChangeCallback(),this}setFromRotationMatrix(A){const e=A.elements,g=e[0],i=e[4],I=e[8],C=e[1],o=e[5],a=e[9],Q=e[2],n=e[6],s=e[10],B=g+o+s;if(B>0){const E=.5/Math.sqrt(B+1);this._w=.25/E,this._x=(n-a)*E,this._y=(I-Q)*E,this._z=(C-i)*E}else if(g>o&&g>s){const E=2*Math.sqrt(1+g-o-s);this._w=(n-a)/E,this._x=.25*E,this._y=(i+C)/E,this._z=(I+Q)/E}else if(o>s){const E=2*Math.sqrt(1+o-g-s);this._w=(I-Q)/E,this._x=(i+C)/E,this._y=.25*E,this._z=(a+n)/E}else{const E=2*Math.sqrt(1+s-g-o);this._w=(C-i)/E,this._x=(I+Q)/E,this._y=(a+n)/E,this._z=.25*E}return this._onChangeCallback(),this}setFromUnitVectors(A,e){let g=A.dot(e)+1;return g<1e-8?(g=0,Math.abs(A.x)>Math.abs(A.z)?(this._x=-A.y,this._y=A.x,this._z=0,this._w=g):(this._x=0,this._y=-A.z,this._z=A.y,this._w=g)):(this._x=A.y*e.z-A.z*e.y,this._y=A.z*e.x-A.x*e.z,this._z=A.x*e.y-A.y*e.x,this._w=g),this.normalize()}angleTo(A){return 2*Math.acos(Math.abs(te(this.dot(A),-1,1)))}rotateTowards(A,e){const g=this.angleTo(A);if(g===0)return this;const i=Math.min(1,e/g);return this.slerp(A,i),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(A){return this._x*A._x+this._y*A._y+this._z*A._z+this._w*A._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 A=this.length();return A===0?(this._x=0,this._y=0,this._z=0,this._w=1):(A=1/A,this._x=this._x*A,this._y=this._y*A,this._z=this._z*A,this._w=this._w*A),this._onChangeCallback(),this}multiply(A){return this.multiplyQuaternions(this,A)}premultiply(A){return this.multiplyQuaternions(A,this)}multiplyQuaternions(A,e){const g=A._x,i=A._y,I=A._z,C=A._w,o=e._x,a=e._y,Q=e._z,n=e._w;return this._x=g*n+C*o+i*Q-I*a,this._y=i*n+C*a+I*o-g*Q,this._z=I*n+C*Q+g*a-i*o,this._w=C*n-g*o-i*a-I*Q,this._onChangeCallback(),this}slerp(A,e){if(e<=0)return this;if(e>=1)return this.copy(A);let g=A._x,i=A._y,I=A._z,C=A._w,o=this.dot(A);o<0&&(g=-g,i=-i,I=-I,C=-C,o=-o);let a=1-e;if(o<.9995){const Q=Math.acos(o),n=Math.sin(Q);a=Math.sin(a*Q)/n,e=Math.sin(e*Q)/n,this._x=this._x*a+g*e,this._y=this._y*a+i*e,this._z=this._z*a+I*e,this._w=this._w*a+C*e,this._onChangeCallback()}else this._x=this._x*a+g*e,this._y=this._y*a+i*e,this._z=this._z*a+I*e,this._w=this._w*a+C*e,this.normalize();return this}slerpQuaternions(A,e,g){return this.copy(A).slerp(e,g)}random(){const A=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),g=Math.random(),i=Math.sqrt(1-g),I=Math.sqrt(g);return this.set(i*Math.sin(A),i*Math.cos(A),I*Math.sin(e),I*Math.cos(e))}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._w===this._w}fromArray(A,e=0){return this._x=A[e],this._y=A[e+1],this._z=A[e+2],this._w=A[e+3],this._onChangeCallback(),this}toArray(A=[],e=0){return A[e]=this._x,A[e+1]=this._y,A[e+2]=this._z,A[e+3]=this._w,A}fromBufferAttribute(A,e){return this._x=A.getX(e),this._y=A.getY(e),this._z=A.getZ(e),this._w=A.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class J{constructor(A=0,e=0,g=0){J.prototype.isVector3=!0,this.x=A,this.y=e,this.z=g}set(A,e,g){return g===void 0&&(g=this.z),this.x=A,this.y=e,this.z=g,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this.z=A.z+e.z,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this.z+=A.z*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this.z=A.z-e.z,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this}multiplyVectors(A,e){return this.x=A.x*e.x,this.y=A.y*e.y,this.z=A.z*e.z,this}applyEuler(A){return this.applyQuaternion(B0.setFromEuler(A))}applyAxisAngle(A,e){return this.applyQuaternion(B0.setFromAxisAngle(A,e))}applyMatrix3(A){const e=this.x,g=this.y,i=this.z,I=A.elements;return this.x=I[0]*e+I[3]*g+I[6]*i,this.y=I[1]*e+I[4]*g+I[7]*i,this.z=I[2]*e+I[5]*g+I[8]*i,this}applyNormalMatrix(A){return this.applyMatrix3(A).normalize()}applyMatrix4(A){const e=this.x,g=this.y,i=this.z,I=A.elements,C=1/(I[3]*e+I[7]*g+I[11]*i+I[15]);return this.x=(I[0]*e+I[4]*g+I[8]*i+I[12])*C,this.y=(I[1]*e+I[5]*g+I[9]*i+I[13])*C,this.z=(I[2]*e+I[6]*g+I[10]*i+I[14])*C,this}applyQuaternion(A){const e=this.x,g=this.y,i=this.z,I=A.x,C=A.y,o=A.z,a=A.w,Q=2*(C*i-o*g),n=2*(o*e-I*i),s=2*(I*g-C*e);return this.x=e+a*Q+C*s-o*n,this.y=g+a*n+o*Q-I*s,this.z=i+a*s+I*n-C*Q,this}project(A){return this.applyMatrix4(A.matrixWorldInverse).applyMatrix4(A.projectionMatrix)}unproject(A){return this.applyMatrix4(A.projectionMatrixInverse).applyMatrix4(A.matrixWorld)}transformDirection(A){const e=this.x,g=this.y,i=this.z,I=A.elements;return this.x=I[0]*e+I[4]*g+I[8]*i,this.y=I[1]*e+I[5]*g+I[9]*i,this.z=I[2]*e+I[6]*g+I[10]*i,this.normalize()}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this}divideScalar(A){return this.multiplyScalar(1/A)}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this.z=te(this.z,A.z,e.z),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this.z=te(this.z,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y+this.z*A.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(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this.z+=(A.z-this.z)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this.z=A.z+(e.z-A.z)*g,this}cross(A){return this.crossVectors(this,A)}crossVectors(A,e){const g=A.x,i=A.y,I=A.z,C=e.x,o=e.y,a=e.z;return this.x=i*a-I*o,this.y=I*C-g*a,this.z=g*o-i*C,this}projectOnVector(A){const e=A.lengthSq();if(e===0)return this.set(0,0,0);const g=A.dot(this)/e;return this.copy(A).multiplyScalar(g)}projectOnPlane(A){return Jn.copy(this).projectOnVector(A),this.sub(Jn)}reflect(A){return this.sub(Jn.copy(A).multiplyScalar(2*this.dot(A)))}angleTo(A){const e=Math.sqrt(this.lengthSq()*A.lengthSq());if(e===0)return Math.PI/2;const g=this.dot(A)/e;return Math.acos(te(g,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){const e=this.x-A.x,g=this.y-A.y,i=this.z-A.z;return e*e+g*g+i*i}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)+Math.abs(this.z-A.z)}setFromSpherical(A){return this.setFromSphericalCoords(A.radius,A.phi,A.theta)}setFromSphericalCoords(A,e,g){const i=Math.sin(e)*A;return this.x=i*Math.sin(g),this.y=Math.cos(e)*A,this.z=i*Math.cos(g),this}setFromCylindrical(A){return this.setFromCylindricalCoords(A.radius,A.theta,A.y)}setFromCylindricalCoords(A,e,g){return this.x=A*Math.sin(e),this.y=g,this.z=A*Math.cos(e),this}setFromMatrixPosition(A){const e=A.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(A){const e=this.setFromMatrixColumn(A,0).length(),g=this.setFromMatrixColumn(A,1).length(),i=this.setFromMatrixColumn(A,2).length();return this.x=e,this.y=g,this.z=i,this}setFromMatrixColumn(A,e){return this.fromArray(A.elements,e*4)}setFromMatrix3Column(A,e){return this.fromArray(A.elements,e*3)}setFromEuler(A){return this.x=A._x,this.y=A._y,this.z=A._z,this}setFromColor(A){return this.x=A.r,this.y=A.g,this.z=A.b,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this.z=A[e+2],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A[e+2]=this.z,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this.z=A.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const A=Math.random()*Math.PI*2,e=Math.random()*2-1,g=Math.sqrt(1-e*e);return this.x=g*Math.cos(A),this.y=e,this.z=g*Math.sin(A),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Jn=new J,B0=new nC;class YA{constructor(A,e,g,i,I,C,o,a,Q){YA.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],A!==void 0&&this.set(A,e,g,i,I,C,o,a,Q)}set(A,e,g,i,I,C,o,a,Q){const n=this.elements;return n[0]=A,n[1]=i,n[2]=o,n[3]=e,n[4]=I,n[5]=a,n[6]=g,n[7]=C,n[8]=Q,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(A){const e=this.elements,g=A.elements;return e[0]=g[0],e[1]=g[1],e[2]=g[2],e[3]=g[3],e[4]=g[4],e[5]=g[5],e[6]=g[6],e[7]=g[7],e[8]=g[8],this}extractBasis(A,e,g){return A.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),g.setFromMatrix3Column(this,2),this}setFromMatrix4(A){const e=A.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,e){const g=A.elements,i=e.elements,I=this.elements,C=g[0],o=g[3],a=g[6],Q=g[1],n=g[4],s=g[7],B=g[2],E=g[5],d=g[8],c=i[0],h=i[3],r=i[6],f=i[1],_=i[4],l=i[7],D=i[2],p=i[5],y=i[8];return I[0]=C*c+o*f+a*D,I[3]=C*h+o*_+a*p,I[6]=C*r+o*l+a*y,I[1]=Q*c+n*f+s*D,I[4]=Q*h+n*_+s*p,I[7]=Q*r+n*l+s*y,I[2]=B*c+E*f+d*D,I[5]=B*h+E*_+d*p,I[8]=B*r+E*l+d*y,this}multiplyScalar(A){const e=this.elements;return e[0]*=A,e[3]*=A,e[6]*=A,e[1]*=A,e[4]*=A,e[7]*=A,e[2]*=A,e[5]*=A,e[8]*=A,this}determinant(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8];return e*C*n-e*o*Q-g*I*n+g*o*a+i*I*Q-i*C*a}invert(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8],s=n*C-o*Q,B=o*a-n*I,E=Q*I-C*a,d=e*s+g*B+i*E;if(d===0)return this.set(0,0,0,0,0,0,0,0,0);const c=1/d;return A[0]=s*c,A[1]=(i*Q-n*g)*c,A[2]=(o*g-i*C)*c,A[3]=B*c,A[4]=(n*e-i*a)*c,A[5]=(i*I-o*e)*c,A[6]=E*c,A[7]=(g*a-Q*e)*c,A[8]=(C*e-g*I)*c,this}transpose(){let A;const e=this.elements;return A=e[1],e[1]=e[3],e[3]=A,A=e[2],e[2]=e[6],e[6]=A,A=e[5],e[5]=e[7],e[7]=A,this}getNormalMatrix(A){return this.setFromMatrix4(A).invert().transpose()}transposeIntoArray(A){const e=this.elements;return A[0]=e[0],A[1]=e[3],A[2]=e[6],A[3]=e[1],A[4]=e[4],A[5]=e[7],A[6]=e[2],A[7]=e[5],A[8]=e[8],this}setUvTransform(A,e,g,i,I,C,o){const a=Math.cos(I),Q=Math.sin(I);return this.set(g*a,g*Q,-g*(a*C+Q*o)+C+A,-i*Q,i*a,-i*(-Q*C+a*o)+o+e,0,0,1),this}scale(A,e){return this.premultiply(Yn.makeScale(A,e)),this}rotate(A){return this.premultiply(Yn.makeRotation(-A)),this}translate(A,e){return this.premultiply(Yn.makeTranslation(A,e)),this}makeTranslation(A,e){return A.isVector2?this.set(1,0,A.x,0,1,A.y,0,0,1):this.set(1,0,A,0,1,e,0,0,1),this}makeRotation(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,-g,0,g,e,0,0,0,1),this}makeScale(A,e){return this.set(A,0,0,0,e,0,0,0,1),this}equals(A){const e=this.elements,g=A.elements;for(let i=0;i<9;i++)if(e[i]!==g[i])return!1;return!0}fromArray(A,e=0){for(let g=0;g<9;g++)this.elements[g]=A[g+e];return this}toArray(A=[],e=0){const g=this.elements;return A[e]=g[0],A[e+1]=g[1],A[e+2]=g[2],A[e+3]=g[3],A[e+4]=g[4],A[e+5]=g[5],A[e+6]=g[6],A[e+7]=g[7],A[e+8]=g[8],A}clone(){return new this.constructor().fromArray(this.elements)}}const Yn=new YA,E0=new YA().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),r0=new YA().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Gf(){const t={enabled:!0,workingColorSpace:sI,spaces:{},convert:function(i,I,C){return this.enabled===!1||I===C||!I||!C||(this.spaces[I].transfer===re&&(i.r=Mt(i.r),i.g=Mt(i.g),i.b=Mt(i.b)),this.spaces[I].primaries!==this.spaces[C].primaries&&(i.applyMatrix3(this.spaces[I].toXYZ),i.applyMatrix3(this.spaces[C].fromXYZ)),this.spaces[C].transfer===re&&(i.r=rI(i.r),i.g=rI(i.g),i.b=rI(i.b))),i},workingToColorSpace:function(i,I){return this.convert(i,this.workingColorSpace,I)},colorSpaceToWorking:function(i,I){return this.convert(i,I,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ii?fo:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,I=this.workingColorSpace){return i.fromArray(this.spaces[I].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,I,C){return i.copy(this.spaces[I].toXYZ).multiply(this.spaces[C].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,I){return oC("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(i,I)},toWorkingColorSpace:function(i,I){return oC("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(i,I)}},A=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],g=[.3127,.329];return t.define({[sI]:{primaries:A,whitePoint:g,transfer:fo,toXYZ:E0,fromXYZ:r0,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:kg},outputColorSpaceConfig:{drawingBufferColorSpace:kg}},[kg]:{primaries:A,whitePoint:g,transfer:re,toXYZ:E0,fromXYZ:r0,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:kg}}}),t}const Ce=Gf();function Mt(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function rI(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let cI;class Mf{static getDataURL(A,e="image/png"){if(/^data:/i.test(A.src)||typeof HTMLCanvasElement>"u")return A.src;let g;if(A instanceof HTMLCanvasElement)g=A;else{cI===void 0&&(cI=Do("canvas")),cI.width=A.width,cI.height=A.height;const i=cI.getContext("2d");A instanceof ImageData?i.putImageData(A,0,0):i.drawImage(A,0,0,A.width,A.height),g=cI}return g.toDataURL(e)}static sRGBToLinear(A){if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap){const e=Do("canvas");e.width=A.width,e.height=A.height;const g=e.getContext("2d");g.drawImage(A,0,0,A.width,A.height);const i=g.getImageData(0,0,A.width,A.height),I=i.data;for(let C=0;C<I.length;C++)I[C]=Mt(I[C]/255)*255;return g.putImageData(i,0,0),e}else if(A.data){const e=A.data.slice(0);for(let g=0;g<e.length;g++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[g]=Math.floor(Mt(e[g]/255)*255):e[g]=Mt(e[g]);return{data:e,width:A.width,height:A.height}}else return LA("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),A}}let Ff=0;class Tn{constructor(A=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ff++}),this.uuid=aC(),this.data=A,this.dataReady=!0,this.version=0}getSize(A){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?A.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?A.set(e.displayHeight,e.displayWidth,0):e!==null?A.set(e.width,e.height,e.depth||0):A.set(0,0,0),A}set needsUpdate(A){A===!0&&this.version++}toJSON(A){const e=A===void 0||typeof A=="string";if(!e&&A.images[this.uuid]!==void 0)return A.images[this.uuid];const g={uuid:this.uuid,url:""},i=this.data;if(i!==null){let I;if(Array.isArray(i)){I=[];for(let C=0,o=i.length;C<o;C++)i[C].isDataTexture?I.push(qn(i[C].image)):I.push(qn(i[C]))}else I=qn(i);g.url=I}return e||(A.images[this.uuid]=g),g}}function qn(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?Mf.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(LA("Texture: Unable to serialize Texture."),{})}let Uf=0;const Hn=new J;class ig extends EI{constructor(A=ig.DEFAULT_IMAGE,e=ig.DEFAULT_MAPPING,g=kt,i=kt,I=Ag,C=bi,o=Hg,a=Sg,Q=ig.DEFAULT_ANISOTROPY,n=ii){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Uf++}),this.uuid=aC(),this.name="",this.source=new Tn(A),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=g,this.wrapT=i,this.magFilter=I,this.minFilter=C,this.anisotropy=Q,this.format=o,this.internalFormat=null,this.type=a,this.offset=new Be(0,0),this.repeat=new Be(1,1),this.center=new Be(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new YA,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=n,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(A&&A.depth&&A.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Hn).x}get height(){return this.source.getSize(Hn).y}get depth(){return this.source.getSize(Hn).z}get image(){return this.source.data}set image(A=null){this.source.data=A}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(A,e){this.updateRanges.push({start:A,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(A){return this.name=A.name,this.source=A.source,this.mipmaps=A.mipmaps.slice(0),this.mapping=A.mapping,this.channel=A.channel,this.wrapS=A.wrapS,this.wrapT=A.wrapT,this.magFilter=A.magFilter,this.minFilter=A.minFilter,this.anisotropy=A.anisotropy,this.format=A.format,this.internalFormat=A.internalFormat,this.type=A.type,this.offset.copy(A.offset),this.repeat.copy(A.repeat),this.center.copy(A.center),this.rotation=A.rotation,this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrix.copy(A.matrix),this.generateMipmaps=A.generateMipmaps,this.premultiplyAlpha=A.premultiplyAlpha,this.flipY=A.flipY,this.unpackAlignment=A.unpackAlignment,this.colorSpace=A.colorSpace,this.renderTarget=A.renderTarget,this.isRenderTargetTexture=A.isRenderTargetTexture,this.isArrayTexture=A.isArrayTexture,this.userData=JSON.parse(JSON.stringify(A.userData)),this.needsUpdate=!0,this}setValues(A){for(const e in A){const g=A[e];if(g===void 0){LA(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){LA(`Texture.setValues(): property '${e}' does not exist.`);continue}i&&g&&i.isVector2&&g.isVector2||i&&g&&i.isVector3&&g.isVector3||i&&g&&i.isMatrix3&&g.isMatrix3?i.copy(g):this[e]=g}}toJSON(A){const e=A===void 0||typeof A=="string";if(!e&&A.textures[this.uuid]!==void 0)return A.textures[this.uuid];const g={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(A).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&&(g.userData=this.userData),e||(A.textures[this.uuid]=g),g}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(A){if(this.mapping!==zr)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case VQ:A.x=A.x-Math.floor(A.x);break;case kt:A.x=A.x<0?0:1;break;case jQ:Math.abs(Math.floor(A.x)%2)===1?A.x=Math.ceil(A.x)-A.x:A.x=A.x-Math.floor(A.x);break}if(A.y<0||A.y>1)switch(this.wrapT){case VQ:A.y=A.y-Math.floor(A.y);break;case kt:A.y=A.y<0?0:1;break;case jQ:Math.abs(Math.floor(A.y)%2)===1?A.y=Math.ceil(A.y)-A.y:A.y=A.y-Math.floor(A.y);break}return this.flipY&&(A.y=1-A.y),A}set needsUpdate(A){A===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(A){A===!0&&this.pmremVersion++}}ig.DEFAULT_IMAGE=null,ig.DEFAULT_MAPPING=zr,ig.DEFAULT_ANISOTROPY=1;class Ke{constructor(A=0,e=0,g=0,i=1){Ke.prototype.isVector4=!0,this.x=A,this.y=e,this.z=g,this.w=i}get width(){return this.z}set width(A){this.z=A}get height(){return this.w}set height(A){this.w=A}set(A,e,g,i){return this.x=A,this.y=e,this.z=g,this.w=i,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this.w=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setW(A){return this.w=A,this}setComponent(A,e){switch(A){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){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: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this.w=A.w!==void 0?A.w:1,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this.w+=A.w,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this.w+=A,this}addVectors(A,e){return this.x=A.x+e.x,this.y=A.y+e.y,this.z=A.z+e.z,this.w=A.w+e.w,this}addScaledVector(A,e){return this.x+=A.x*e,this.y+=A.y*e,this.z+=A.z*e,this.w+=A.w*e,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this.w-=A.w,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this.w-=A,this}subVectors(A,e){return this.x=A.x-e.x,this.y=A.y-e.y,this.z=A.z-e.z,this.w=A.w-e.w,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this.w*=A.w,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this.w*=A,this}applyMatrix4(A){const e=this.x,g=this.y,i=this.z,I=this.w,C=A.elements;return this.x=C[0]*e+C[4]*g+C[8]*i+C[12]*I,this.y=C[1]*e+C[5]*g+C[9]*i+C[13]*I,this.z=C[2]*e+C[6]*g+C[10]*i+C[14]*I,this.w=C[3]*e+C[7]*g+C[11]*i+C[15]*I,this}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this.w/=A.w,this}divideScalar(A){return this.multiplyScalar(1/A)}setAxisAngleFromQuaternion(A){this.w=2*Math.acos(A.w);const e=Math.sqrt(1-A.w*A.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=A.x/e,this.y=A.y/e,this.z=A.z/e),this}setAxisAngleFromRotationMatrix(A){let e,g,i,I;const a=A.elements,Q=a[0],n=a[4],s=a[8],B=a[1],E=a[5],d=a[9],c=a[2],h=a[6],r=a[10];if(Math.abs(n-B)<.01&&Math.abs(s-c)<.01&&Math.abs(d-h)<.01){if(Math.abs(n+B)<.1&&Math.abs(s+c)<.1&&Math.abs(d+h)<.1&&Math.abs(Q+E+r-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const _=(Q+1)/2,l=(E+1)/2,D=(r+1)/2,p=(n+B)/4,y=(s+c)/4,k=(d+h)/4;return _>l&&_>D?_<.01?(g=0,i=.707106781,I=.707106781):(g=Math.sqrt(_),i=p/g,I=y/g):l>D?l<.01?(g=.707106781,i=0,I=.707106781):(i=Math.sqrt(l),g=p/i,I=k/i):D<.01?(g=.707106781,i=.707106781,I=0):(I=Math.sqrt(D),g=y/I,i=k/I),this.set(g,i,I,e),this}let f=Math.sqrt((h-d)*(h-d)+(s-c)*(s-c)+(B-n)*(B-n));return Math.abs(f)<.001&&(f=1),this.x=(h-d)/f,this.y=(s-c)/f,this.z=(B-n)/f,this.w=Math.acos((Q+E+r-1)/2),this}setFromMatrixPosition(A){const e=A.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this.w=Math.min(this.w,A.w),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this.w=Math.max(this.w,A.w),this}clamp(A,e){return this.x=te(this.x,A.x,e.x),this.y=te(this.y,A.y,e.y),this.z=te(this.z,A.z,e.z),this.w=te(this.w,A.w,e.w),this}clampScalar(A,e){return this.x=te(this.x,A,e),this.y=te(this.y,A,e),this.z=te(this.z,A,e),this.w=te(this.w,A,e),this}clampLength(A,e){const g=this.length();return this.divideScalar(g||1).multiplyScalar(te(g,A,e))}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(A){return this.x*A.x+this.y*A.y+this.z*A.z+this.w*A.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(A){return this.normalize().multiplyScalar(A)}lerp(A,e){return this.x+=(A.x-this.x)*e,this.y+=(A.y-this.y)*e,this.z+=(A.z-this.z)*e,this.w+=(A.w-this.w)*e,this}lerpVectors(A,e,g){return this.x=A.x+(e.x-A.x)*g,this.y=A.y+(e.y-A.y)*g,this.z=A.z+(e.z-A.z)*g,this.w=A.w+(e.w-A.w)*g,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z&&A.w===this.w}fromArray(A,e=0){return this.x=A[e],this.y=A[e+1],this.z=A[e+2],this.w=A[e+3],this}toArray(A=[],e=0){return A[e]=this.x,A[e+1]=this.y,A[e+2]=this.z,A[e+3]=this.w,A}fromBufferAttribute(A,e){return this.x=A.getX(e),this.y=A.getY(e),this.z=A.getZ(e),this.w=A.getW(e),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 Lf extends EI{constructor(A=1,e=1,g={}){super(),g=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ag,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},g),this.isRenderTarget=!0,this.width=A,this.height=e,this.depth=g.depth,this.scissor=new Ke(0,0,A,e),this.scissorTest=!1,this.viewport=new Ke(0,0,A,e);const i={width:A,height:e,depth:g.depth},I=new ig(i);this.textures=[];const C=g.count;for(let o=0;o<C;o++)this.textures[o]=I.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(g),this.depthBuffer=g.depthBuffer,this.stencilBuffer=g.stencilBuffer,this.resolveDepthBuffer=g.resolveDepthBuffer,this.resolveStencilBuffer=g.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=g.depthTexture,this.samples=g.samples,this.multiview=g.multiview}_setTextureOptions(A={}){const e={minFilter:Ag,generateMipmaps:!1,flipY:!1,internalFormat:null};A.mapping!==void 0&&(e.mapping=A.mapping),A.wrapS!==void 0&&(e.wrapS=A.wrapS),A.wrapT!==void 0&&(e.wrapT=A.wrapT),A.wrapR!==void 0&&(e.wrapR=A.wrapR),A.magFilter!==void 0&&(e.magFilter=A.magFilter),A.minFilter!==void 0&&(e.minFilter=A.minFilter),A.format!==void 0&&(e.format=A.format),A.type!==void 0&&(e.type=A.type),A.anisotropy!==void 0&&(e.anisotropy=A.anisotropy),A.colorSpace!==void 0&&(e.colorSpace=A.colorSpace),A.flipY!==void 0&&(e.flipY=A.flipY),A.generateMipmaps!==void 0&&(e.generateMipmaps=A.generateMipmaps),A.internalFormat!==void 0&&(e.internalFormat=A.internalFormat);for(let g=0;g<this.textures.length;g++)this.textures[g].setValues(e)}get texture(){return this.textures[0]}set texture(A){this.textures[0]=A}set depthTexture(A){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),A!==null&&(A.renderTarget=this),this._depthTexture=A}get depthTexture(){return this._depthTexture}setSize(A,e,g=1){if(this.width!==A||this.height!==e||this.depth!==g){this.width=A,this.height=e,this.depth=g;for(let i=0,I=this.textures.length;i<I;i++)this.textures[i].image.width=A,this.textures[i].image.height=e,this.textures[i].image.depth=g,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,A,e),this.scissor.set(0,0,A,e)}clone(){return new this.constructor().copy(this)}copy(A){this.width=A.width,this.height=A.height,this.depth=A.depth,this.scissor.copy(A.scissor),this.scissorTest=A.scissorTest,this.viewport.copy(A.viewport),this.textures.length=0;for(let e=0,g=A.textures.length;e<g;e++){this.textures[e]=A.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const i=Object.assign({},A.textures[e].image);this.textures[e].source=new Tn(i)}return this.depthBuffer=A.depthBuffer,this.stencilBuffer=A.stencilBuffer,this.resolveDepthBuffer=A.resolveDepthBuffer,this.resolveStencilBuffer=A.resolveStencilBuffer,A.depthTexture!==null&&(this.depthTexture=A.depthTexture.clone()),this.samples=A.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class st extends Lf{constructor(A=1,e=1,g={}){super(A,e,g),this.isWebGLRenderTarget=!0}}class c0 extends ig{constructor(A=null,e=1,g=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:A,width:e,height:g,depth:i},this.magFilter=$e,this.minFilter=$e,this.wrapR=kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class Kf extends ig{constructor(A=null,e=1,g=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:A,width:e,height:g,depth:i},this.magFilter=$e,this.minFilter=$e,this.wrapR=kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class sC{constructor(A=new J(1/0,1/0,1/0),e=new J(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=A,this.max=e}set(A,e){return this.min.copy(A),this.max.copy(e),this}setFromArray(A){this.makeEmpty();for(let e=0,g=A.length;e<g;e+=3)this.expandByPoint(Pg.fromArray(A,e));return this}setFromBufferAttribute(A){this.makeEmpty();for(let e=0,g=A.count;e<g;e++)this.expandByPoint(Pg.fromBufferAttribute(A,e));return this}setFromPoints(A){this.makeEmpty();for(let e=0,g=A.length;e<g;e++)this.expandByPoint(A[e]);return this}setFromCenterAndSize(A,e){const g=Pg.copy(e).multiplyScalar(.5);return this.min.copy(A).sub(g),this.max.copy(A).add(g),this}setFromObject(A,e=!1){return this.makeEmpty(),this.expandByObject(A,e)}clone(){return new this.constructor().copy(this)}copy(A){return this.min.copy(A.min),this.max.copy(A.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(A){return this.isEmpty()?A.set(0,0,0):A.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(A){return this.isEmpty()?A.set(0,0,0):A.subVectors(this.max,this.min)}expandByPoint(A){return this.min.min(A),this.max.max(A),this}expandByVector(A){return this.min.sub(A),this.max.add(A),this}expandByScalar(A){return this.min.addScalar(-A),this.max.addScalar(A),this}expandByObject(A,e=!1){A.updateWorldMatrix(!1,!1);const g=A.geometry;if(g!==void 0){const I=g.getAttribute("position");if(e===!0&&I!==void 0&&A.isInstancedMesh!==!0)for(let C=0,o=I.count;C<o;C++)A.isMesh===!0?A.getVertexPosition(C,Pg):Pg.fromBufferAttribute(I,C),Pg.applyMatrix4(A.matrixWorld),this.expandByPoint(Pg);else A.boundingBox!==void 0?(A.boundingBox===null&&A.computeBoundingBox(),_o.copy(A.boundingBox)):(g.boundingBox===null&&g.computeBoundingBox(),_o.copy(g.boundingBox)),_o.applyMatrix4(A.matrixWorld),this.union(_o)}const i=A.children;for(let I=0,C=i.length;I<C;I++)this.expandByObject(i[I],e);return this}containsPoint(A){return A.x>=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y&&A.z>=this.min.z&&A.z<=this.max.z}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y&&this.min.z<=A.min.z&&A.max.z<=this.max.z}getParameter(A,e){return e.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y),(A.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y&&A.max.z>=this.min.z&&A.min.z<=this.max.z}intersectsSphere(A){return this.clampPoint(A.center,Pg),Pg.distanceToSquared(A.center)<=A.radius*A.radius}intersectsPlane(A){let e,g;return A.normal.x>0?(e=A.normal.x*this.min.x,g=A.normal.x*this.max.x):(e=A.normal.x*this.max.x,g=A.normal.x*this.min.x),A.normal.y>0?(e+=A.normal.y*this.min.y,g+=A.normal.y*this.max.y):(e+=A.normal.y*this.max.y,g+=A.normal.y*this.min.y),A.normal.z>0?(e+=A.normal.z*this.min.z,g+=A.normal.z*this.max.z):(e+=A.normal.z*this.max.z,g+=A.normal.z*this.min.z),e<=-A.constant&&g>=-A.constant}intersectsTriangle(A){if(this.isEmpty())return!1;this.getCenter(BC),wo.subVectors(this.max,BC),hI.subVectors(A.a,BC),dI.subVectors(A.b,BC),xI.subVectors(A.c,BC),Ii.subVectors(dI,hI),Ci.subVectors(xI,dI),Si.subVectors(hI,xI);let e=[0,-Ii.z,Ii.y,0,-Ci.z,Ci.y,0,-Si.z,Si.y,Ii.z,0,-Ii.x,Ci.z,0,-Ci.x,Si.z,0,-Si.x,-Ii.y,Ii.x,0,-Ci.y,Ci.x,0,-Si.y,Si.x,0];return!Pn(e,hI,dI,xI,wo)||(e=[1,0,0,0,1,0,0,0,1],!Pn(e,hI,dI,xI,wo))?!1:(po.crossVectors(Ii,Ci),e=[po.x,po.y,po.z],Pn(e,hI,dI,xI,wo))}clampPoint(A,e){return e.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,Pg).distanceTo(A)}getBoundingSphere(A){return this.isEmpty()?A.makeEmpty():(this.getCenter(A.center),A.radius=this.getSize(Pg).length()*.5),A}intersect(A){return this.min.max(A.min),this.max.min(A.max),this.isEmpty()&&this.makeEmpty(),this}union(A){return this.min.min(A.min),this.max.max(A.max),this}applyMatrix4(A){return this.isEmpty()?this:(Ft[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),Ft[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),Ft[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),Ft[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),Ft[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),Ft[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),Ft[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),Ft[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(Ft),this)}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(A){return this.min.fromArray(A.min),this.max.fromArray(A.max),this}}const Ft=[new J,new J,new J,new J,new J,new J,new J,new J],Pg=new J,_o=new sC,hI=new J,dI=new J,xI=new J,Ii=new J,Ci=new J,Si=new J,BC=new J,wo=new J,po=new J,ki=new J;function Pn(t,A,e,g,i){for(let I=0,C=t.length-3;I<=C;I+=3){ki.fromArray(t,I);const o=i.x*Math.abs(ki.x)+i.y*Math.abs(ki.y)+i.z*Math.abs(ki.z),a=A.dot(ki),Q=e.dot(ki),n=g.dot(ki);if(Math.max(-Math.max(a,Q,n),Math.min(a,Q,n))>o)return!1}return!0}const vf=new sC,EC=new J,On=new J;class Vn{constructor(A=new J,e=-1){this.isSphere=!0,this.center=A,this.radius=e}set(A,e){return this.center.copy(A),this.radius=e,this}setFromPoints(A,e){const g=this.center;e!==void 0?g.copy(e):vf.setFromPoints(A).getCenter(g);let i=0;for(let I=0,C=A.length;I<C;I++)i=Math.max(i,g.distanceToSquared(A[I]));return this.radius=Math.sqrt(i),this}copy(A){return this.center.copy(A.center),this.radius=A.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(A){return A.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(A){return A.distanceTo(this.center)-this.radius}intersectsSphere(A){const e=this.radius+A.radius;return A.center.distanceToSquared(this.center)<=e*e}intersectsBox(A){return A.intersectsSphere(this)}intersectsPlane(A){return Math.abs(A.distanceToPoint(this.center))<=this.radius}clampPoint(A,e){const g=this.center.distanceToSquared(A);return e.copy(A),g>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(A){return this.isEmpty()?(A.makeEmpty(),A):(A.set(this.center,this.center),A.expandByScalar(this.radius),A)}applyMatrix4(A){return this.center.applyMatrix4(A),this.radius=this.radius*A.getMaxScaleOnAxis(),this}translate(A){return this.center.add(A),this}expandByPoint(A){if(this.isEmpty())return this.center.copy(A),this.radius=0,this;EC.subVectors(A,this.center);const e=EC.lengthSq();if(e>this.radius*this.radius){const g=Math.sqrt(e),i=(g-this.radius)*.5;this.center.addScaledVector(EC,i/g),this.radius+=i}return this}union(A){return A.isEmpty()?this:this.isEmpty()?(this.copy(A),this):(this.center.equals(A.center)===!0?this.radius=Math.max(this.radius,A.radius):(On.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(EC.copy(A.center).add(On)),this.expandByPoint(EC.copy(A.center).sub(On))),this)}equals(A){return A.center.equals(this.center)&&A.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(A){return this.radius=A.radius,this.center.fromArray(A.center),this}}const Ut=new J,jn=new J,mo=new J,oi=new J,Wn=new J,yo=new J,Xn=new J;class Jf{constructor(A=new J,e=new J(0,0,-1)){this.origin=A,this.direction=e}set(A,e){return this.origin.copy(A),this.direction.copy(e),this}copy(A){return this.origin.copy(A.origin),this.direction.copy(A.direction),this}at(A,e){return e.copy(this.origin).addScaledVector(this.direction,A)}lookAt(A){return this.direction.copy(A).sub(this.origin).normalize(),this}recast(A){return this.origin.copy(this.at(A,Ut)),this}closestPointToPoint(A,e){e.subVectors(A,this.origin);const g=e.dot(this.direction);return g<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,g)}distanceToPoint(A){return Math.sqrt(this.distanceSqToPoint(A))}distanceSqToPoint(A){const e=Ut.subVectors(A,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(A):(Ut.copy(this.origin).addScaledVector(this.direction,e),Ut.distanceToSquared(A))}distanceSqToSegment(A,e,g,i){jn.copy(A).add(e).multiplyScalar(.5),mo.copy(e).sub(A).normalize(),oi.copy(this.origin).sub(jn);const I=A.distanceTo(e)*.5,C=-this.direction.dot(mo),o=oi.dot(this.direction),a=-oi.dot(mo),Q=oi.lengthSq(),n=Math.abs(1-C*C);let s,B,E,d;if(n>0)if(s=C*a-o,B=C*o-a,d=I*n,s>=0)if(B>=-d)if(B<=d){const c=1/n;s*=c,B*=c,E=s*(s+C*B+2*o)+B*(C*s+B+2*a)+Q}else B=I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;else B=-I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;else B<=-d?(s=Math.max(0,-(-C*I+o)),B=s>0?-I:Math.min(Math.max(-I,-a),I),E=-s*s+B*(B+2*a)+Q):B<=d?(s=0,B=Math.min(Math.max(-I,-a),I),E=B*(B+2*a)+Q):(s=Math.max(0,-(C*I+o)),B=s>0?I:Math.min(Math.max(-I,-a),I),E=-s*s+B*(B+2*a)+Q);else B=C>0?-I:I,s=Math.max(0,-(C*B+o)),E=-s*s+B*(B+2*a)+Q;return g&&g.copy(this.origin).addScaledVector(this.direction,s),i&&i.copy(jn).addScaledVector(mo,B),E}intersectSphere(A,e){Ut.subVectors(A.center,this.origin);const g=Ut.dot(this.direction),i=Ut.dot(Ut)-g*g,I=A.radius*A.radius;if(i>I)return null;const C=Math.sqrt(I-i),o=g-C,a=g+C;return a<0?null:o<0?this.at(a,e):this.at(o,e)}intersectsSphere(A){return A.radius<0?!1:this.distanceSqToPoint(A.center)<=A.radius*A.radius}distanceToPlane(A){const e=A.normal.dot(this.direction);if(e===0)return A.distanceToPoint(this.origin)===0?0:null;const g=-(this.origin.dot(A.normal)+A.constant)/e;return g>=0?g:null}intersectPlane(A,e){const g=this.distanceToPlane(A);return g===null?null:this.at(g,e)}intersectsPlane(A){const e=A.distanceToPoint(this.origin);return e===0||A.normal.dot(this.direction)*e<0}intersectBox(A,e){let g,i,I,C,o,a;const Q=1/this.direction.x,n=1/this.direction.y,s=1/this.direction.z,B=this.origin;return Q>=0?(g=(A.min.x-B.x)*Q,i=(A.max.x-B.x)*Q):(g=(A.max.x-B.x)*Q,i=(A.min.x-B.x)*Q),n>=0?(I=(A.min.y-B.y)*n,C=(A.max.y-B.y)*n):(I=(A.max.y-B.y)*n,C=(A.min.y-B.y)*n),g>C||I>i||((I>g||isNaN(g))&&(g=I),(C<i||isNaN(i))&&(i=C),s>=0?(o=(A.min.z-B.z)*s,a=(A.max.z-B.z)*s):(o=(A.max.z-B.z)*s,a=(A.min.z-B.z)*s),g>a||o>i)||((o>g||g!==g)&&(g=o),(a<i||i!==i)&&(i=a),i<0)?null:this.at(g>=0?g:i,e)}intersectsBox(A){return this.intersectBox(A,Ut)!==null}intersectTriangle(A,e,g,i,I){Wn.subVectors(e,A),yo.subVectors(g,A),Xn.crossVectors(Wn,yo);let C=this.direction.dot(Xn),o;if(C>0){if(i)return null;o=1}else if(C<0)o=-1,C=-C;else return null;oi.subVectors(this.origin,A);const a=o*this.direction.dot(yo.crossVectors(oi,yo));if(a<0)return null;const Q=o*this.direction.dot(Wn.cross(oi));if(Q<0||a+Q>C)return null;const n=-o*oi.dot(Xn);return n<0?null:this.at(n/C,I)}applyMatrix4(A){return this.origin.applyMatrix4(A),this.direction.transformDirection(A),this}equals(A){return A.origin.equals(this.origin)&&A.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ye{constructor(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h){Ye.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A!==void 0&&this.set(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h)}set(A,e,g,i,I,C,o,a,Q,n,s,B,E,d,c,h){const r=this.elements;return r[0]=A,r[4]=e,r[8]=g,r[12]=i,r[1]=I,r[5]=C,r[9]=o,r[13]=a,r[2]=Q,r[6]=n,r[10]=s,r[14]=B,r[3]=E,r[7]=d,r[11]=c,r[15]=h,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 Ye().fromArray(this.elements)}copy(A){const e=this.elements,g=A.elements;return e[0]=g[0],e[1]=g[1],e[2]=g[2],e[3]=g[3],e[4]=g[4],e[5]=g[5],e[6]=g[6],e[7]=g[7],e[8]=g[8],e[9]=g[9],e[10]=g[10],e[11]=g[11],e[12]=g[12],e[13]=g[13],e[14]=g[14],e[15]=g[15],this}copyPosition(A){const e=this.elements,g=A.elements;return e[12]=g[12],e[13]=g[13],e[14]=g[14],this}setFromMatrix3(A){const e=A.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(A,e,g){return this.determinant()===0?(A.set(1,0,0),e.set(0,1,0),g.set(0,0,1),this):(A.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),g.setFromMatrixColumn(this,2),this)}makeBasis(A,e,g){return this.set(A.x,e.x,g.x,0,A.y,e.y,g.y,0,A.z,e.z,g.z,0,0,0,0,1),this}extractRotation(A){if(A.determinant()===0)return this.identity();const e=this.elements,g=A.elements,i=1/lI.setFromMatrixColumn(A,0).length(),I=1/lI.setFromMatrixColumn(A,1).length(),C=1/lI.setFromMatrixColumn(A,2).length();return e[0]=g[0]*i,e[1]=g[1]*i,e[2]=g[2]*i,e[3]=0,e[4]=g[4]*I,e[5]=g[5]*I,e[6]=g[6]*I,e[7]=0,e[8]=g[8]*C,e[9]=g[9]*C,e[10]=g[10]*C,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(A){const e=this.elements,g=A.x,i=A.y,I=A.z,C=Math.cos(g),o=Math.sin(g),a=Math.cos(i),Q=Math.sin(i),n=Math.cos(I),s=Math.sin(I);if(A.order==="XYZ"){const B=C*n,E=C*s,d=o*n,c=o*s;e[0]=a*n,e[4]=-a*s,e[8]=Q,e[1]=E+d*Q,e[5]=B-c*Q,e[9]=-o*a,e[2]=c-B*Q,e[6]=d+E*Q,e[10]=C*a}else if(A.order==="YXZ"){const B=a*n,E=a*s,d=Q*n,c=Q*s;e[0]=B+c*o,e[4]=d*o-E,e[8]=C*Q,e[1]=C*s,e[5]=C*n,e[9]=-o,e[2]=E*o-d,e[6]=c+B*o,e[10]=C*a}else if(A.order==="ZXY"){const B=a*n,E=a*s,d=Q*n,c=Q*s;e[0]=B-c*o,e[4]=-C*s,e[8]=d+E*o,e[1]=E+d*o,e[5]=C*n,e[9]=c-B*o,e[2]=-C*Q,e[6]=o,e[10]=C*a}else if(A.order==="ZYX"){const B=C*n,E=C*s,d=o*n,c=o*s;e[0]=a*n,e[4]=d*Q-E,e[8]=B*Q+c,e[1]=a*s,e[5]=c*Q+B,e[9]=E*Q-d,e[2]=-Q,e[6]=o*a,e[10]=C*a}else if(A.order==="YZX"){const B=C*a,E=C*Q,d=o*a,c=o*Q;e[0]=a*n,e[4]=c-B*s,e[8]=d*s+E,e[1]=s,e[5]=C*n,e[9]=-o*n,e[2]=-Q*n,e[6]=E*s+d,e[10]=B-c*s}else if(A.order==="XZY"){const B=C*a,E=C*Q,d=o*a,c=o*Q;e[0]=a*n,e[4]=-s,e[8]=Q*n,e[1]=B*s+c,e[5]=C*n,e[9]=E*s-d,e[2]=d*s-E,e[6]=o*n,e[10]=c*s+B}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(A){return this.compose(Yf,A,Tf)}lookAt(A,e,g){const i=this.elements;return wg.subVectors(A,e),wg.lengthSq()===0&&(wg.z=1),wg.normalize(),ai.crossVectors(g,wg),ai.lengthSq()===0&&(Math.abs(g.z)===1?wg.x+=1e-4:wg.z+=1e-4,wg.normalize(),ai.crossVectors(g,wg)),ai.normalize(),bo.crossVectors(wg,ai),i[0]=ai.x,i[4]=bo.x,i[8]=wg.x,i[1]=ai.y,i[5]=bo.y,i[9]=wg.y,i[2]=ai.z,i[6]=bo.z,i[10]=wg.z,this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,e){const g=A.elements,i=e.elements,I=this.elements,C=g[0],o=g[4],a=g[8],Q=g[12],n=g[1],s=g[5],B=g[9],E=g[13],d=g[2],c=g[6],h=g[10],r=g[14],f=g[3],_=g[7],l=g[11],D=g[15],p=i[0],y=i[4],k=i[8],x=i[12],w=i[1],N=i[5],U=i[9],K=i[13],P=i[2],j=i[6],H=i[10],O=i[14],z=i[3],xA=i[7],sA=i[11],fA=i[15];return I[0]=C*p+o*w+a*P+Q*z,I[4]=C*y+o*N+a*j+Q*xA,I[8]=C*k+o*U+a*H+Q*sA,I[12]=C*x+o*K+a*O+Q*fA,I[1]=n*p+s*w+B*P+E*z,I[5]=n*y+s*N+B*j+E*xA,I[9]=n*k+s*U+B*H+E*sA,I[13]=n*x+s*K+B*O+E*fA,I[2]=d*p+c*w+h*P+r*z,I[6]=d*y+c*N+h*j+r*xA,I[10]=d*k+c*U+h*H+r*sA,I[14]=d*x+c*K+h*O+r*fA,I[3]=f*p+_*w+l*P+D*z,I[7]=f*y+_*N+l*j+D*xA,I[11]=f*k+_*U+l*H+D*sA,I[15]=f*x+_*K+l*O+D*fA,this}multiplyScalar(A){const e=this.elements;return e[0]*=A,e[4]*=A,e[8]*=A,e[12]*=A,e[1]*=A,e[5]*=A,e[9]*=A,e[13]*=A,e[2]*=A,e[6]*=A,e[10]*=A,e[14]*=A,e[3]*=A,e[7]*=A,e[11]*=A,e[15]*=A,this}determinant(){const A=this.elements,e=A[0],g=A[4],i=A[8],I=A[12],C=A[1],o=A[5],a=A[9],Q=A[13],n=A[2],s=A[6],B=A[10],E=A[14],d=A[3],c=A[7],h=A[11],r=A[15],f=a*E-Q*B,_=o*E-Q*s,l=o*B-a*s,D=C*E-Q*n,p=C*B-a*n,y=C*s-o*n;return e*(c*f-h*_+r*l)-g*(d*f-h*D+r*p)+i*(d*_-c*D+r*y)-I*(d*l-c*p+h*y)}transpose(){const A=this.elements;let e;return e=A[1],A[1]=A[4],A[4]=e,e=A[2],A[2]=A[8],A[8]=e,e=A[6],A[6]=A[9],A[9]=e,e=A[3],A[3]=A[12],A[12]=e,e=A[7],A[7]=A[13],A[13]=e,e=A[11],A[11]=A[14],A[14]=e,this}setPosition(A,e,g){const i=this.elements;return A.isVector3?(i[12]=A.x,i[13]=A.y,i[14]=A.z):(i[12]=A,i[13]=e,i[14]=g),this}invert(){const A=this.elements,e=A[0],g=A[1],i=A[2],I=A[3],C=A[4],o=A[5],a=A[6],Q=A[7],n=A[8],s=A[9],B=A[10],E=A[11],d=A[12],c=A[13],h=A[14],r=A[15],f=s*h*Q-c*B*Q+c*a*E-o*h*E-s*a*r+o*B*r,_=d*B*Q-n*h*Q-d*a*E+C*h*E+n*a*r-C*B*r,l=n*c*Q-d*s*Q+d*o*E-C*c*E-n*o*r+C*s*r,D=d*s*a-n*c*a-d*o*B+C*c*B+n*o*h-C*s*h,p=e*f+g*_+i*l+I*D;if(p===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const y=1/p;return A[0]=f*y,A[1]=(c*B*I-s*h*I-c*i*E+g*h*E+s*i*r-g*B*r)*y,A[2]=(o*h*I-c*a*I+c*i*Q-g*h*Q-o*i*r+g*a*r)*y,A[3]=(s*a*I-o*B*I-s*i*Q+g*B*Q+o*i*E-g*a*E)*y,A[4]=_*y,A[5]=(n*h*I-d*B*I+d*i*E-e*h*E-n*i*r+e*B*r)*y,A[6]=(d*a*I-C*h*I-d*i*Q+e*h*Q+C*i*r-e*a*r)*y,A[7]=(C*B*I-n*a*I+n*i*Q-e*B*Q-C*i*E+e*a*E)*y,A[8]=l*y,A[9]=(d*s*I-n*c*I-d*g*E+e*c*E+n*g*r-e*s*r)*y,A[10]=(C*c*I-d*o*I+d*g*Q-e*c*Q-C*g*r+e*o*r)*y,A[11]=(n*o*I-C*s*I-n*g*Q+e*s*Q+C*g*E-e*o*E)*y,A[12]=D*y,A[13]=(n*c*i-d*s*i+d*g*B-e*c*B-n*g*h+e*s*h)*y,A[14]=(d*o*i-C*c*i-d*g*a+e*c*a+C*g*h-e*o*h)*y,A[15]=(C*s*i-n*o*i+n*g*a-e*s*a-C*g*B+e*o*B)*y,this}scale(A){const e=this.elements,g=A.x,i=A.y,I=A.z;return e[0]*=g,e[4]*=i,e[8]*=I,e[1]*=g,e[5]*=i,e[9]*=I,e[2]*=g,e[6]*=i,e[10]*=I,e[3]*=g,e[7]*=i,e[11]*=I,this}getMaxScaleOnAxis(){const A=this.elements,e=A[0]*A[0]+A[1]*A[1]+A[2]*A[2],g=A[4]*A[4]+A[5]*A[5]+A[6]*A[6],i=A[8]*A[8]+A[9]*A[9]+A[10]*A[10];return Math.sqrt(Math.max(e,g,i))}makeTranslation(A,e,g){return A.isVector3?this.set(1,0,0,A.x,0,1,0,A.y,0,0,1,A.z,0,0,0,1):this.set(1,0,0,A,0,1,0,e,0,0,1,g,0,0,0,1),this}makeRotationX(A){const e=Math.cos(A),g=Math.sin(A);return this.set(1,0,0,0,0,e,-g,0,0,g,e,0,0,0,0,1),this}makeRotationY(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,0,g,0,0,1,0,0,-g,0,e,0,0,0,0,1),this}makeRotationZ(A){const e=Math.cos(A),g=Math.sin(A);return this.set(e,-g,0,0,g,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(A,e){const g=Math.cos(e),i=Math.sin(e),I=1-g,C=A.x,o=A.y,a=A.z,Q=I*C,n=I*o;return this.set(Q*C+g,Q*o-i*a,Q*a+i*o,0,Q*o+i*a,n*o+g,n*a-i*C,0,Q*a-i*o,n*a+i*C,I*a*a+g,0,0,0,0,1),this}makeScale(A,e,g){return this.set(A,0,0,0,0,e,0,0,0,0,g,0,0,0,0,1),this}makeShear(A,e,g,i,I,C){return this.set(1,g,I,0,A,1,C,0,e,i,1,0,0,0,0,1),this}compose(A,e,g){const i=this.elements,I=e._x,C=e._y,o=e._z,a=e._w,Q=I+I,n=C+C,s=o+o,B=I*Q,E=I*n,d=I*s,c=C*n,h=C*s,r=o*s,f=a*Q,_=a*n,l=a*s,D=g.x,p=g.y,y=g.z;return i[0]=(1-(c+r))*D,i[1]=(E+l)*D,i[2]=(d-_)*D,i[3]=0,i[4]=(E-l)*p,i[5]=(1-(B+r))*p,i[6]=(h+f)*p,i[7]=0,i[8]=(d+_)*y,i[9]=(h-f)*y,i[10]=(1-(B+c))*y,i[11]=0,i[12]=A.x,i[13]=A.y,i[14]=A.z,i[15]=1,this}decompose(A,e,g){const i=this.elements;if(A.x=i[12],A.y=i[13],A.z=i[14],this.determinant()===0)return g.set(1,1,1),e.identity(),this;let I=lI.set(i[0],i[1],i[2]).length();const C=lI.set(i[4],i[5],i[6]).length(),o=lI.set(i[8],i[9],i[10]).length();this.determinant()<0&&(I=-I),Og.copy(this);const Q=1/I,n=1/C,s=1/o;return Og.elements[0]*=Q,Og.elements[1]*=Q,Og.elements[2]*=Q,Og.elements[4]*=n,Og.elements[5]*=n,Og.elements[6]*=n,Og.elements[8]*=s,Og.elements[9]*=s,Og.elements[10]*=s,e.setFromRotationMatrix(Og),g.x=I,g.y=C,g.z=o,this}makePerspective(A,e,g,i,I,C,o=nt,a=!1){const Q=this.elements,n=2*I/(e-A),s=2*I/(g-i),B=(e+A)/(e-A),E=(g+i)/(g-i);let d,c;if(a)d=I/(C-I),c=C*I/(C-I);else if(o===nt)d=-(C+I)/(C-I),c=-2*C*I/(C-I);else if(o===uo)d=-C/(C-I),c=-C*I/(C-I);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return Q[0]=n,Q[4]=0,Q[8]=B,Q[12]=0,Q[1]=0,Q[5]=s,Q[9]=E,Q[13]=0,Q[2]=0,Q[6]=0,Q[10]=d,Q[14]=c,Q[3]=0,Q[7]=0,Q[11]=-1,Q[15]=0,this}makeOrthographic(A,e,g,i,I,C,o=nt,a=!1){const Q=this.elements,n=2/(e-A),s=2/(g-i),B=-(e+A)/(e-A),E=-(g+i)/(g-i);let d,c;if(a)d=1/(C-I),c=C/(C-I);else if(o===nt)d=-2/(C-I),c=-(C+I)/(C-I);else if(o===uo)d=-1/(C-I),c=-I/(C-I);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return Q[0]=n,Q[4]=0,Q[8]=0,Q[12]=B,Q[1]=0,Q[5]=s,Q[9]=0,Q[13]=E,Q[2]=0,Q[6]=0,Q[10]=d,Q[14]=c,Q[3]=0,Q[7]=0,Q[11]=0,Q[15]=1,this}equals(A){const e=this.elements,g=A.elements;for(let i=0;i<16;i++)if(e[i]!==g[i])return!1;return!0}fromArray(A,e=0){for(let g=0;g<16;g++)this.elements[g]=A[g+e];return this}toArray(A=[],e=0){const g=this.elements;return A[e]=g[0],A[e+1]=g[1],A[e+2]=g[2],A[e+3]=g[3],A[e+4]=g[4],A[e+5]=g[5],A[e+6]=g[6],A[e+7]=g[7],A[e+8]=g[8],A[e+9]=g[9],A[e+10]=g[10],A[e+11]=g[11],A[e+12]=g[12],A[e+13]=g[13],A[e+14]=g[14],A[e+15]=g[15],A}}const lI=new J,Og=new Ye,Yf=new J(0,0,0),Tf=new J(1,1,1),ai=new J,bo=new J,wg=new J,h0=new Ye,d0=new nC;class Lt{constructor(A=0,e=0,g=0,i=Lt.DEFAULT_ORDER){this.isEuler=!0,this._x=A,this._y=e,this._z=g,this._order=i}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get order(){return this._order}set order(A){this._order=A,this._onChangeCallback()}set(A,e,g,i=this._order){return this._x=A,this._y=e,this._z=g,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(A){return this._x=A._x,this._y=A._y,this._z=A._z,this._order=A._order,this._onChangeCallback(),this}setFromRotationMatrix(A,e=this._order,g=!0){const i=A.elements,I=i[0],C=i[4],o=i[8],a=i[1],Q=i[5],n=i[9],s=i[2],B=i[6],E=i[10];switch(e){case"XYZ":this._y=Math.asin(te(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-n,E),this._z=Math.atan2(-C,I)):(this._x=Math.atan2(B,Q),this._z=0);break;case"YXZ":this._x=Math.asin(-te(n,-1,1)),Math.abs(n)<.9999999?(this._y=Math.atan2(o,E),this._z=Math.atan2(a,Q)):(this._y=Math.atan2(-s,I),this._z=0);break;case"ZXY":this._x=Math.asin(te(B,-1,1)),Math.abs(B)<.9999999?(this._y=Math.atan2(-s,E),this._z=Math.atan2(-C,Q)):(this._y=0,this._z=Math.atan2(a,I));break;case"ZYX":this._y=Math.asin(-te(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(B,E),this._z=Math.atan2(a,I)):(this._x=0,this._z=Math.atan2(-C,Q));break;case"YZX":this._z=Math.asin(te(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-n,Q),this._y=Math.atan2(-s,I)):(this._x=0,this._y=Math.atan2(o,E));break;case"XZY":this._z=Math.asin(-te(C,-1,1)),Math.abs(C)<.9999999?(this._x=Math.atan2(B,Q),this._y=Math.atan2(o,I)):(this._x=Math.atan2(-n,E),this._y=0);break;default:LA("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,g===!0&&this._onChangeCallback(),this}setFromQuaternion(A,e,g){return h0.makeRotationFromQuaternion(A),this.setFromRotationMatrix(h0,e,g)}setFromVector3(A,e=this._order){return this.set(A.x,A.y,A.z,e)}reorder(A){return d0.setFromEuler(this),this.setFromQuaternion(d0,A)}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._order===this._order}fromArray(A){return this._x=A[0],this._y=A[1],this._z=A[2],A[3]!==void 0&&(this._order=A[3]),this._onChangeCallback(),this}toArray(A=[],e=0){return A[e]=this._x,A[e+1]=this._y,A[e+2]=this._z,A[e+3]=this._order,A}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Lt.DEFAULT_ORDER="XYZ";class x0{constructor(){this.mask=1}set(A){this.mask=(1<<A|0)>>>0}enable(A){this.mask|=1<<A|0}enableAll(){this.mask=-1}toggle(A){this.mask^=1<<A|0}disable(A){this.mask&=~(1<<A|0)}disableAll(){this.mask=0}test(A){return(this.mask&A.mask)!==0}isEnabled(A){return(this.mask&(1<<A|0))!==0}}let qf=0;const l0=new J,fI=new nC,Kt=new Ye,No=new J,rC=new J,Hf=new J,Pf=new nC,f0=new J(1,0,0),u0=new J(0,1,0),D0=new J(0,0,1),_0={type:"added"},Of={type:"removed"},uI={type:"childadded",child:null},Zn={type:"childremoved",child:null};class pg extends EI{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:qf++}),this.uuid=aC(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=pg.DEFAULT_UP.clone();const A=new J,e=new Lt,g=new nC,i=new J(1,1,1);function I(){g.setFromEuler(e,!1)}function C(){e.setFromQuaternion(g,void 0,!1)}e._onChange(I),g._onChange(C),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:A},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:g},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ye},normalMatrix:{value:new YA}}),this.matrix=new Ye,this.matrixWorld=new Ye,this.matrixAutoUpdate=pg.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=pg.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new x0,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(A){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(A),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(A){return this.quaternion.premultiply(A),this}setRotationFromAxisAngle(A,e){this.quaternion.setFromAxisAngle(A,e)}setRotationFromEuler(A){this.quaternion.setFromEuler(A,!0)}setRotationFromMatrix(A){this.quaternion.setFromRotationMatrix(A)}setRotationFromQuaternion(A){this.quaternion.copy(A)}rotateOnAxis(A,e){return fI.setFromAxisAngle(A,e),this.quaternion.multiply(fI),this}rotateOnWorldAxis(A,e){return fI.setFromAxisAngle(A,e),this.quaternion.premultiply(fI),this}rotateX(A){return this.rotateOnAxis(f0,A)}rotateY(A){return this.rotateOnAxis(u0,A)}rotateZ(A){return this.rotateOnAxis(D0,A)}translateOnAxis(A,e){return l0.copy(A).applyQuaternion(this.quaternion),this.position.add(l0.multiplyScalar(e)),this}translateX(A){return this.translateOnAxis(f0,A)}translateY(A){return this.translateOnAxis(u0,A)}translateZ(A){return this.translateOnAxis(D0,A)}localToWorld(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(this.matrixWorld)}worldToLocal(A){return this.updateWorldMatrix(!0,!1),A.applyMatrix4(Kt.copy(this.matrixWorld).invert())}lookAt(A,e,g){A.isVector3?No.copy(A):No.set(A,e,g);const i=this.parent;this.updateWorldMatrix(!0,!1),rC.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Kt.lookAt(rC,No,this.up):Kt.lookAt(No,rC,this.up),this.quaternion.setFromRotationMatrix(Kt),i&&(Kt.extractRotation(i.matrixWorld),fI.setFromRotationMatrix(Kt),this.quaternion.premultiply(fI.invert()))}add(A){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return A===this?(ae("Object3D.add: object can't be added as a child of itself.",A),this):(A&&A.isObject3D?(A.removeFromParent(),A.parent=this,this.children.push(A),A.dispatchEvent(_0),uI.child=A,this.dispatchEvent(uI),uI.child=null):ae("Object3D.add: object not an instance of THREE.Object3D.",A),this)}remove(A){if(arguments.length>1){for(let g=0;g<arguments.length;g++)this.remove(arguments[g]);return this}const e=this.children.indexOf(A);return e!==-1&&(A.parent=null,this.children.splice(e,1),A.dispatchEvent(Of),Zn.child=A,this.dispatchEvent(Zn),Zn.child=null),this}removeFromParent(){const A=this.parent;return A!==null&&A.remove(this),this}clear(){return this.remove(...this.children)}attach(A){return this.updateWorldMatrix(!0,!1),Kt.copy(this.matrixWorld).invert(),A.parent!==null&&(A.parent.updateWorldMatrix(!0,!1),Kt.multiply(A.parent.matrixWorld)),A.applyMatrix4(Kt),A.removeFromParent(),A.parent=this,this.children.push(A),A.updateWorldMatrix(!1,!0),A.dispatchEvent(_0),uI.child=A,this.dispatchEvent(uI),uI.child=null,this}getObjectById(A){return this.getObjectByProperty("id",A)}getObjectByName(A){return this.getObjectByProperty("name",A)}getObjectByProperty(A,e){if(this[A]===e)return this;for(let g=0,i=this.children.length;g<i;g++){const C=this.children[g].getObjectByProperty(A,e);if(C!==void 0)return C}}getObjectsByProperty(A,e,g=[]){this[A]===e&&g.push(this);const i=this.children;for(let I=0,C=i.length;I<C;I++)i[I].getObjectsByProperty(A,e,g);return g}getWorldPosition(A){return this.updateWorldMatrix(!0,!1),A.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rC,A,Hf),A}getWorldScale(A){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rC,Pf,A),A}getWorldDirection(A){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return A.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(A){A(this);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].traverse(A)}traverseVisible(A){if(this.visible===!1)return;A(this);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].traverseVisible(A)}traverseAncestors(A){const e=this.parent;e!==null&&(A(e),e.traverseAncestors(A))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(A){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||A)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,A=!0);const e=this.children;for(let g=0,i=e.length;g<i;g++)e[g].updateMatrixWorld(A)}updateWorldMatrix(A,e){const g=this.parent;if(A===!0&&g!==null&&g.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)),e===!0){const i=this.children;for(let I=0,C=i.length;I<C;I++)i[I].updateWorldMatrix(!1,!0)}}toJSON(A){const e=A===void 0||typeof A=="string",g={};e&&(A={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},g.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(A),i.indirectTexture=this._indirectTexture.toJSON(A),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(A)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function I(o,a){return o[a.uuid]===void 0&&(o[a.uuid]=a.toJSON(A)),a.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(A).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(A).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=I(A.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const a=o.shapes;if(Array.isArray(a))for(let Q=0,n=a.length;Q<n;Q++){const s=a[Q];I(A.shapes,s)}else I(A.shapes,a)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(I(A.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let a=0,Q=this.material.length;a<Q;a++)o.push(I(A.materials,this.material[a]));i.material=o}else i.material=I(A.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(A).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){const a=this.animations[o];i.animations.push(I(A.animations,a))}}if(e){const o=C(A.geometries),a=C(A.materials),Q=C(A.textures),n=C(A.images),s=C(A.shapes),B=C(A.skeletons),E=C(A.animations),d=C(A.nodes);o.length>0&&(g.geometries=o),a.length>0&&(g.materials=a),Q.length>0&&(g.textures=Q),n.length>0&&(g.images=n),s.length>0&&(g.shapes=s),B.length>0&&(g.skeletons=B),E.length>0&&(g.animations=E),d.length>0&&(g.nodes=d)}return g.object=i,g;function C(o){const a=[];for(const Q in o){const n=o[Q];delete n.metadata,a.push(n)}return a}}clone(A){return new this.constructor().copy(this,A)}copy(A,e=!0){if(this.name=A.name,this.up.copy(A.up),this.position.copy(A.position),this.rotation.order=A.rotation.order,this.quaternion.copy(A.quaternion),this.scale.copy(A.scale),this.matrix.copy(A.matrix),this.matrixWorld.copy(A.matrixWorld),this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrixWorldAutoUpdate=A.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=A.matrixWorldNeedsUpdate,this.layers.mask=A.layers.mask,this.visible=A.visible,this.castShadow=A.castShadow,this.receiveShadow=A.receiveShadow,this.frustumCulled=A.frustumCulled,this.renderOrder=A.renderOrder,this.animations=A.animations.slice(),this.userData=JSON.parse(JSON.stringify(A.userData)),e===!0)for(let g=0;g<A.children.length;g++){const i=A.children[g];this.add(i.clone())}return this}}pg.DEFAULT_UP=new J(0,1,0),pg.DEFAULT_MATRIX_AUTO_UPDATE=!0,pg.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Vg=new J,vt=new J,zn=new J,Jt=new J,DI=new J,_I=new J,w0=new J,$n=new J,As=new J,es=new J,gs=new Ke,ts=new Ke,is=new Ke;class jg{constructor(A=new J,e=new J,g=new J){this.a=A,this.b=e,this.c=g}static getNormal(A,e,g,i){i.subVectors(g,e),Vg.subVectors(A,e),i.cross(Vg);const I=i.lengthSq();return I>0?i.multiplyScalar(1/Math.sqrt(I)):i.set(0,0,0)}static getBarycoord(A,e,g,i,I){Vg.subVectors(i,e),vt.subVectors(g,e),zn.subVectors(A,e);const C=Vg.dot(Vg),o=Vg.dot(vt),a=Vg.dot(zn),Q=vt.dot(vt),n=vt.dot(zn),s=C*Q-o*o;if(s===0)return I.set(0,0,0),null;const B=1/s,E=(Q*a-o*n)*B,d=(C*n-o*a)*B;return I.set(1-E-d,d,E)}static containsPoint(A,e,g,i){return this.getBarycoord(A,e,g,i,Jt)===null?!1:Jt.x>=0&&Jt.y>=0&&Jt.x+Jt.y<=1}static getInterpolation(A,e,g,i,I,C,o,a){return this.getBarycoord(A,e,g,i,Jt)===null?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(I,Jt.x),a.addScaledVector(C,Jt.y),a.addScaledVector(o,Jt.z),a)}static getInterpolatedAttribute(A,e,g,i,I,C){return gs.setScalar(0),ts.setScalar(0),is.setScalar(0),gs.fromBufferAttribute(A,e),ts.fromBufferAttribute(A,g),is.fromBufferAttribute(A,i),C.setScalar(0),C.addScaledVector(gs,I.x),C.addScaledVector(ts,I.y),C.addScaledVector(is,I.z),C}static isFrontFacing(A,e,g,i){return Vg.subVectors(g,e),vt.subVectors(A,e),Vg.cross(vt).dot(i)<0}set(A,e,g){return this.a.copy(A),this.b.copy(e),this.c.copy(g),this}setFromPointsAndIndices(A,e,g,i){return this.a.copy(A[e]),this.b.copy(A[g]),this.c.copy(A[i]),this}setFromAttributeAndIndices(A,e,g,i){return this.a.fromBufferAttribute(A,e),this.b.fromBufferAttribute(A,g),this.c.fromBufferAttribute(A,i),this}clone(){return new this.constructor().copy(this)}copy(A){return this.a.copy(A.a),this.b.copy(A.b),this.c.copy(A.c),this}getArea(){return Vg.subVectors(this.c,this.b),vt.subVectors(this.a,this.b),Vg.cross(vt).length()*.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(A){return jg.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,e){return jg.getBarycoord(A,this.a,this.b,this.c,e)}getInterpolation(A,e,g,i,I){return jg.getInterpolation(A,this.a,this.b,this.c,e,g,i,I)}containsPoint(A){return jg.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return jg.isFrontFacing(this.a,this.b,this.c,A)}intersectsBox(A){return A.intersectsTriangle(this)}closestPointToPoint(A,e){const g=this.a,i=this.b,I=this.c;let C,o;DI.subVectors(i,g),_I.subVectors(I,g),$n.subVectors(A,g);const a=DI.dot($n),Q=_I.dot($n);if(a<=0&&Q<=0)return e.copy(g);As.subVectors(A,i);const n=DI.dot(As),s=_I.dot(As);if(n>=0&&s<=n)return e.copy(i);const B=a*s-n*Q;if(B<=0&&a>=0&&n<=0)return C=a/(a-n),e.copy(g).addScaledVector(DI,C);es.subVectors(A,I);const E=DI.dot(es),d=_I.dot(es);if(d>=0&&E<=d)return e.copy(I);const c=E*Q-a*d;if(c<=0&&Q>=0&&d<=0)return o=Q/(Q-d),e.copy(g).addScaledVector(_I,o);const h=n*d-E*s;if(h<=0&&s-n>=0&&E-d>=0)return w0.subVectors(I,i),o=(s-n)/(s-n+(E-d)),e.copy(i).addScaledVector(w0,o);const r=1/(h+c+B);return C=c*r,o=B*r,e.copy(g).addScaledVector(DI,C).addScaledVector(_I,o)}equals(A){return A.a.equals(this.a)&&A.b.equals(this.b)&&A.c.equals(this.c)}}const p0={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},Qi={h:0,s:0,l:0},So={h:0,s:0,l:0};function Is(t,A,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?t+(A-t)*6*e:e<1/2?A:e<2/3?t+(A-t)*6*(2/3-e):t}class Ie{constructor(A,e,g){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(A,e,g)}set(A,e,g){if(e===void 0&&g===void 0){const i=A;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(A,e,g);return this}setScalar(A){return this.r=A,this.g=A,this.b=A,this}setHex(A,e=kg){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,Ce.colorSpaceToWorking(this,e),this}setRGB(A,e,g,i=Ce.workingColorSpace){return this.r=A,this.g=e,this.b=g,Ce.colorSpaceToWorking(this,i),this}setHSL(A,e,g,i=Ce.workingColorSpace){if(A=Rf(A,1),e=te(e,0,1),g=te(g,0,1),e===0)this.r=this.g=this.b=g;else{const I=g<=.5?g*(1+e):g+e-g*e,C=2*g-I;this.r=Is(C,I,A+1/3),this.g=Is(C,I,A),this.b=Is(C,I,A-1/3)}return Ce.colorSpaceToWorking(this,i),this}setStyle(A,e=kg){function g(I){I!==void 0&&parseFloat(I)<1&&LA("Color: Alpha component of "+A+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(A)){let I;const C=i[1],o=i[2];switch(C){case"rgb":case"rgba":if(I=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setRGB(Math.min(255,parseInt(I[1],10))/255,Math.min(255,parseInt(I[2],10))/255,Math.min(255,parseInt(I[3],10))/255,e);if(I=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setRGB(Math.min(100,parseInt(I[1],10))/100,Math.min(100,parseInt(I[2],10))/100,Math.min(100,parseInt(I[3],10))/100,e);break;case"hsl":case"hsla":if(I=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return g(I[4]),this.setHSL(parseFloat(I[1])/360,parseFloat(I[2])/100,parseFloat(I[3])/100,e);break;default:LA("Color: Unknown color model "+A)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(A)){const I=i[1],C=I.length;if(C===3)return this.setRGB(parseInt(I.charAt(0),16)/15,parseInt(I.charAt(1),16)/15,parseInt(I.charAt(2),16)/15,e);if(C===6)return this.setHex(parseInt(I,16),e);LA("Color: Invalid hex color "+A)}else if(A&&A.length>0)return this.setColorName(A,e);return this}setColorName(A,e=kg){const g=p0[A.toLowerCase()];return g!==void 0?this.setHex(g,e):LA("Color: Unknown color "+A),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(A){return this.r=A.r,this.g=A.g,this.b=A.b,this}copySRGBToLinear(A){return this.r=Mt(A.r),this.g=Mt(A.g),this.b=Mt(A.b),this}copyLinearToSRGB(A){return this.r=rI(A.r),this.g=rI(A.g),this.b=rI(A.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(A=kg){return Ce.workingToColorSpace(gg.copy(this),A),Math.round(te(gg.r*255,0,255))*65536+Math.round(te(gg.g*255,0,255))*256+Math.round(te(gg.b*255,0,255))}getHexString(A=kg){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,e=Ce.workingColorSpace){Ce.workingToColorSpace(gg.copy(this),e);const g=gg.r,i=gg.g,I=gg.b,C=Math.max(g,i,I),o=Math.min(g,i,I);let a,Q;const n=(o+C)/2;if(o===C)a=0,Q=0;else{const s=C-o;switch(Q=n<=.5?s/(C+o):s/(2-C-o),C){case g:a=(i-I)/s+(i<I?6:0);break;case i:a=(I-g)/s+2;break;case I:a=(g-i)/s+4;break}a/=6}return A.h=a,A.s=Q,A.l=n,A}getRGB(A,e=Ce.workingColorSpace){return Ce.workingToColorSpace(gg.copy(this),e),A.r=gg.r,A.g=gg.g,A.b=gg.b,A}getStyle(A=kg){Ce.workingToColorSpace(gg.copy(this),A);const e=gg.r,g=gg.g,i=gg.b;return A!==kg?`color(${A} ${e.toFixed(3)} ${g.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(g*255)},${Math.round(i*255)})`}offsetHSL(A,e,g){return this.getHSL(Qi),this.setHSL(Qi.h+A,Qi.s+e,Qi.l+g)}add(A){return this.r+=A.r,this.g+=A.g,this.b+=A.b,this}addColors(A,e){return this.r=A.r+e.r,this.g=A.g+e.g,this.b=A.b+e.b,this}addScalar(A){return this.r+=A,this.g+=A,this.b+=A,this}sub(A){return this.r=Math.max(0,this.r-A.r),this.g=Math.max(0,this.g-A.g),this.b=Math.max(0,this.b-A.b),this}multiply(A){return this.r*=A.r,this.g*=A.g,this.b*=A.b,this}multiplyScalar(A){return this.r*=A,this.g*=A,this.b*=A,this}lerp(A,e){return this.r+=(A.r-this.r)*e,this.g+=(A.g-this.g)*e,this.b+=(A.b-this.b)*e,this}lerpColors(A,e,g){return this.r=A.r+(e.r-A.r)*g,this.g=A.g+(e.g-A.g)*g,this.b=A.b+(e.b-A.b)*g,this}lerpHSL(A,e){this.getHSL(Qi),A.getHSL(So);const g=vn(Qi.h,So.h,e),i=vn(Qi.s,So.s,e),I=vn(Qi.l,So.l,e);return this.setHSL(g,i,I),this}setFromVector3(A){return this.r=A.x,this.g=A.y,this.b=A.z,this}applyMatrix3(A){const e=this.r,g=this.g,i=this.b,I=A.elements;return this.r=I[0]*e+I[3]*g+I[6]*i,this.g=I[1]*e+I[4]*g+I[7]*i,this.b=I[2]*e+I[5]*g+I[8]*i,this}equals(A){return A.r===this.r&&A.g===this.g&&A.b===this.b}fromArray(A,e=0){return this.r=A[e],this.g=A[e+1],this.b=A[e+2],this}toArray(A=[],e=0){return A[e]=this.r,A[e+1]=this.g,A[e+2]=this.b,A}fromBufferAttribute(A,e){return this.r=A.getX(e),this.g=A.getY(e),this.b=A.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const gg=new Ie;Ie.NAMES=p0;let Vf=0;class ko extends EI{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Vf++}),this.uuid=aC(),this.name="",this.type="Material",this.blending=oI,this.side=bt,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=UQ,this.blendDst=LQ,this.blendEquation=mi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ie(0,0,0),this.blendAlpha=0,this.depthFunc=aI,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=C0,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=BI,this.stencilZFail=BI,this.stencilZPass=BI,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(A){this._alphaTest>0!=A>0&&this.version++,this._alphaTest=A}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(A){if(A!==void 0)for(const e in A){const g=A[e];if(g===void 0){LA(`Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];if(i===void 0){LA(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(g):i&&i.isVector3&&g&&g.isVector3?i.copy(g):this[e]=g}}toJSON(A){const e=A===void 0||typeof A=="string";e&&(A={textures:{},images:{}});const g={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};g.uuid=this.uuid,g.type=this.type,this.name!==""&&(g.name=this.name),this.color&&this.color.isColor&&(g.color=this.color.getHex()),this.roughness!==void 0&&(g.roughness=this.roughness),this.metalness!==void 0&&(g.metalness=this.metalness),this.sheen!==void 0&&(g.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(g.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(g.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(g.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(g.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(g.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(g.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(g.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(g.shininess=this.shininess),this.clearcoat!==void 0&&(g.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(g.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(g.clearcoatMap=this.clearcoatMap.toJSON(A).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(g.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(A).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(g.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(A).uuid,g.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(g.sheenColorMap=this.sheenColorMap.toJSON(A).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(g.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(A).uuid),this.dispersion!==void 0&&(g.dispersion=this.dispersion),this.iridescence!==void 0&&(g.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(g.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(g.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(g.iridescenceMap=this.iridescenceMap.toJSON(A).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(g.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(A).uuid),this.anisotropy!==void 0&&(g.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(g.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(g.anisotropyMap=this.anisotropyMap.toJSON(A).uuid),this.map&&this.map.isTexture&&(g.map=this.map.toJSON(A).uuid),this.matcap&&this.matcap.isTexture&&(g.matcap=this.matcap.toJSON(A).uuid),this.alphaMap&&this.alphaMap.isTexture&&(g.alphaMap=this.alphaMap.toJSON(A).uuid),this.lightMap&&this.lightMap.isTexture&&(g.lightMap=this.lightMap.toJSON(A).uuid,g.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(g.aoMap=this.aoMap.toJSON(A).uuid,g.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(g.bumpMap=this.bumpMap.toJSON(A).uuid,g.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(g.normalMap=this.normalMap.toJSON(A).uuid,g.normalMapType=this.normalMapType,g.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(g.displacementMap=this.displacementMap.toJSON(A).uuid,g.displacementScale=this.displacementScale,g.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(g.roughnessMap=this.roughnessMap.toJSON(A).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(g.metalnessMap=this.metalnessMap.toJSON(A).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(g.emissiveMap=this.emissiveMap.toJSON(A).uuid),this.specularMap&&this.specularMap.isTexture&&(g.specularMap=this.specularMap.toJSON(A).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(g.specularIntensityMap=this.specularIntensityMap.toJSON(A).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(g.specularColorMap=this.specularColorMap.toJSON(A).uuid),this.envMap&&this.envMap.isTexture&&(g.envMap=this.envMap.toJSON(A).uuid,this.combine!==void 0&&(g.combine=this.combine)),this.envMapRotation!==void 0&&(g.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(g.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(g.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(g.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(g.gradientMap=this.gradientMap.toJSON(A).uuid),this.transmission!==void 0&&(g.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(g.transmissionMap=this.transmissionMap.toJSON(A).uuid),this.thickness!==void 0&&(g.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(g.thicknessMap=this.thicknessMap.toJSON(A).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(g.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(g.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(g.size=this.size),this.shadowSide!==null&&(g.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(g.sizeAttenuation=this.sizeAttenuation),this.blending!==oI&&(g.blending=this.blending),this.side!==bt&&(g.side=this.side),this.vertexColors===!0&&(g.vertexColors=!0),this.opacity<1&&(g.opacity=this.opacity),this.transparent===!0&&(g.transparent=!0),this.blendSrc!==UQ&&(g.blendSrc=this.blendSrc),this.blendDst!==LQ&&(g.blendDst=this.blendDst),this.blendEquation!==mi&&(g.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(g.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(g.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(g.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(g.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(g.blendAlpha=this.blendAlpha),this.depthFunc!==aI&&(g.depthFunc=this.depthFunc),this.depthTest===!1&&(g.depthTest=this.depthTest),this.depthWrite===!1&&(g.depthWrite=this.depthWrite),this.colorWrite===!1&&(g.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(g.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==C0&&(g.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(g.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(g.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==BI&&(g.stencilFail=this.stencilFail),this.stencilZFail!==BI&&(g.stencilZFail=this.stencilZFail),this.stencilZPass!==BI&&(g.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(g.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(g.rotation=this.rotation),this.polygonOffset===!0&&(g.polygonOffset=!0),this.polygonOffsetFactor!==0&&(g.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(g.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(g.linewidth=this.linewidth),this.dashSize!==void 0&&(g.dashSize=this.dashSize),this.gapSize!==void 0&&(g.gapSize=this.gapSize),this.scale!==void 0&&(g.scale=this.scale),this.dithering===!0&&(g.dithering=!0),this.alphaTest>0&&(g.alphaTest=this.alphaTest),this.alphaHash===!0&&(g.alphaHash=!0),this.alphaToCoverage===!0&&(g.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(g.premultipliedAlpha=!0),this.forceSinglePass===!0&&(g.forceSinglePass=!0),this.allowOverride===!1&&(g.allowOverride=!1),this.wireframe===!0&&(g.wireframe=!0),this.wireframeLinewidth>1&&(g.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(g.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(g.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(g.flatShading=!0),this.visible===!1&&(g.visible=!1),this.toneMapped===!1&&(g.toneMapped=!1),this.fog===!1&&(g.fog=!1),Object.keys(this.userData).length>0&&(g.userData=this.userData);function i(I){const C=[];for(const o in I){const a=I[o];delete a.metadata,C.push(a)}return C}if(e){const I=i(A.textures),C=i(A.images);I.length>0&&(g.textures=I),C.length>0&&(g.images=C)}return g}clone(){return new this.constructor().copy(this)}copy(A){this.name=A.name,this.blending=A.blending,this.side=A.side,this.vertexColors=A.vertexColors,this.opacity=A.opacity,this.transparent=A.transparent,this.blendSrc=A.blendSrc,this.blendDst=A.blendDst,this.blendEquation=A.blendEquation,this.blendSrcAlpha=A.blendSrcAlpha,this.blendDstAlpha=A.blendDstAlpha,this.blendEquationAlpha=A.blendEquationAlpha,this.blendColor.copy(A.blendColor),this.blendAlpha=A.blendAlpha,this.depthFunc=A.depthFunc,this.depthTest=A.depthTest,this.depthWrite=A.depthWrite,this.stencilWriteMask=A.stencilWriteMask,this.stencilFunc=A.stencilFunc,this.stencilRef=A.stencilRef,this.stencilFuncMask=A.stencilFuncMask,this.stencilFail=A.stencilFail,this.stencilZFail=A.stencilZFail,this.stencilZPass=A.stencilZPass,this.stencilWrite=A.stencilWrite;const e=A.clippingPlanes;let g=null;if(e!==null){const i=e.length;g=new Array(i);for(let I=0;I!==i;++I)g[I]=e[I].clone()}return this.clippingPlanes=g,this.clipIntersection=A.clipIntersection,this.clipShadows=A.clipShadows,this.shadowSide=A.shadowSide,this.colorWrite=A.colorWrite,this.precision=A.precision,this.polygonOffset=A.polygonOffset,this.polygonOffsetFactor=A.polygonOffsetFactor,this.polygonOffsetUnits=A.polygonOffsetUnits,this.dithering=A.dithering,this.alphaTest=A.alphaTest,this.alphaHash=A.alphaHash,this.alphaToCoverage=A.alphaToCoverage,this.premultipliedAlpha=A.premultipliedAlpha,this.forceSinglePass=A.forceSinglePass,this.allowOverride=A.allowOverride,this.visible=A.visible,this.toneMapped=A.toneMapped,this.userData=JSON.parse(JSON.stringify(A.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(A){A===!0&&this.version++}}class m0 extends ko{constructor(A){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ie(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 Lt,this.combine=Hr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}const Te=new J,Ro=new Be;let jf=0;class Bt{constructor(A,e,g=!1){if(Array.isArray(A))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:jf++}),this.name="",this.array=A,this.itemSize=e,this.count=A!==void 0?A.length/e:0,this.normalized=g,this.usage=o0,this.updateRanges=[],this.gpuType=Qt,this.version=0}onUploadCallback(){}set needsUpdate(A){A===!0&&this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,e){this.updateRanges.push({start:A,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.name=A.name,this.array=new A.array.constructor(A.array),this.itemSize=A.itemSize,this.count=A.count,this.normalized=A.normalized,this.usage=A.usage,this.gpuType=A.gpuType,this}copyAt(A,e,g){A*=this.itemSize,g*=e.itemSize;for(let i=0,I=this.itemSize;i<I;i++)this.array[A+i]=e.array[g+i];return this}copyArray(A){return this.array.set(A),this}applyMatrix3(A){if(this.itemSize===2)for(let e=0,g=this.count;e<g;e++)Ro.fromBufferAttribute(this,e),Ro.applyMatrix3(A),this.setXY(e,Ro.x,Ro.y);else if(this.itemSize===3)for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix3(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyMatrix4(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix4(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyNormalMatrix(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.applyNormalMatrix(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}transformDirection(A){for(let e=0,g=this.count;e<g;e++)Te.fromBufferAttribute(this,e),Te.transformDirection(A),this.setXYZ(e,Te.x,Te.y,Te.z);return this}set(A,e=0){return this.array.set(A,e),this}getComponent(A,e){let g=this.array[A*this.itemSize+e];return this.normalized&&(g=QC(g,this.array)),g}setComponent(A,e,g){return this.normalized&&(g=hg(g,this.array)),this.array[A*this.itemSize+e]=g,this}getX(A){let e=this.array[A*this.itemSize];return this.normalized&&(e=QC(e,this.array)),e}setX(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize]=e,this}getY(A){let e=this.array[A*this.itemSize+1];return this.normalized&&(e=QC(e,this.array)),e}setY(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+1]=e,this}getZ(A){let e=this.array[A*this.itemSize+2];return this.normalized&&(e=QC(e,this.array)),e}setZ(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+2]=e,this}getW(A){let e=this.array[A*this.itemSize+3];return this.normalized&&(e=QC(e,this.array)),e}setW(A,e){return this.normalized&&(e=hg(e,this.array)),this.array[A*this.itemSize+3]=e,this}setXY(A,e,g){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array)),this.array[A+0]=e,this.array[A+1]=g,this}setXYZ(A,e,g,i){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array),i=hg(i,this.array)),this.array[A+0]=e,this.array[A+1]=g,this.array[A+2]=i,this}setXYZW(A,e,g,i,I){return A*=this.itemSize,this.normalized&&(e=hg(e,this.array),g=hg(g,this.array),i=hg(i,this.array),I=hg(I,this.array)),this.array[A+0]=e,this.array[A+1]=g,this.array[A+2]=i,this.array[A+3]=I,this}onUpload(A){return this.onUploadCallback=A,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const A={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(A.name=this.name),this.usage!==o0&&(A.usage=this.usage),A}}class y0 extends Bt{constructor(A,e,g){super(new Uint16Array(A),e,g)}}class b0 extends Bt{constructor(A,e,g){super(new Uint32Array(A),e,g)}}class Ig extends Bt{constructor(A,e,g){super(new Float32Array(A),e,g)}}let Wf=0;const Rg=new Ye,Cs=new pg,wI=new J,mg=new sC,cC=new sC,Xe=new J;class Wg extends EI{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Wf++}),this.uuid=aC(),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(A){return Array.isArray(A)?this.index=new(Q0(A)?b0:y0)(A,1):this.index=A,this}setIndirect(A,e=0){return this.indirect=A,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(A){return this.attributes[A]}setAttribute(A,e){return this.attributes[A]=e,this}deleteAttribute(A){return delete this.attributes[A],this}hasAttribute(A){return this.attributes[A]!==void 0}addGroup(A,e,g=0){this.groups.push({start:A,count:e,materialIndex:g})}clearGroups(){this.groups=[]}setDrawRange(A,e){this.drawRange.start=A,this.drawRange.count=e}applyMatrix4(A){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(A),e.needsUpdate=!0);const g=this.attributes.normal;if(g!==void 0){const I=new YA().getNormalMatrix(A);g.applyNormalMatrix(I),g.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(A),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(A){return Rg.makeRotationFromQuaternion(A),this.applyMatrix4(Rg),this}rotateX(A){return Rg.makeRotationX(A),this.applyMatrix4(Rg),this}rotateY(A){return Rg.makeRotationY(A),this.applyMatrix4(Rg),this}rotateZ(A){return Rg.makeRotationZ(A),this.applyMatrix4(Rg),this}translate(A,e,g){return Rg.makeTranslation(A,e,g),this.applyMatrix4(Rg),this}scale(A,e,g){return Rg.makeScale(A,e,g),this.applyMatrix4(Rg),this}lookAt(A){return Cs.lookAt(A),Cs.updateMatrix(),this.applyMatrix4(Cs.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(wI).negate(),this.translate(wI.x,wI.y,wI.z),this}setFromPoints(A){const e=this.getAttribute("position");if(e===void 0){const g=[];for(let i=0,I=A.length;i<I;i++){const C=A[i];g.push(C.x,C.y,C.z||0)}this.setAttribute("position",new Ig(g,3))}else{const g=Math.min(A.length,e.count);for(let i=0;i<g;i++){const I=A[i];e.setXYZ(i,I.x,I.y,I.z||0)}A.length>e.count&&LA("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new sC);const A=this.attributes.position,e=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){ae("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new J(-1/0,-1/0,-1/0),new J(1/0,1/0,1/0));return}if(A!==void 0){if(this.boundingBox.setFromBufferAttribute(A),e)for(let g=0,i=e.length;g<i;g++){const I=e[g];mg.setFromBufferAttribute(I),this.morphTargetsRelative?(Xe.addVectors(this.boundingBox.min,mg.min),this.boundingBox.expandByPoint(Xe),Xe.addVectors(this.boundingBox.max,mg.max),this.boundingBox.expandByPoint(Xe)):(this.boundingBox.expandByPoint(mg.min),this.boundingBox.expandByPoint(mg.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&ae('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 Vn);const A=this.attributes.position,e=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){ae("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new J,1/0);return}if(A){const g=this.boundingSphere.center;if(mg.setFromBufferAttribute(A),e)for(let I=0,C=e.length;I<C;I++){const o=e[I];cC.setFromBufferAttribute(o),this.morphTargetsRelative?(Xe.addVectors(mg.min,cC.min),mg.expandByPoint(Xe),Xe.addVectors(mg.max,cC.max),mg.expandByPoint(Xe)):(mg.expandByPoint(cC.min),mg.expandByPoint(cC.max))}mg.getCenter(g);let i=0;for(let I=0,C=A.count;I<C;I++)Xe.fromBufferAttribute(A,I),i=Math.max(i,g.distanceToSquared(Xe));if(e)for(let I=0,C=e.length;I<C;I++){const o=e[I],a=this.morphTargetsRelative;for(let Q=0,n=o.count;Q<n;Q++)Xe.fromBufferAttribute(o,Q),a&&(wI.fromBufferAttribute(A,Q),Xe.add(wI)),i=Math.max(i,g.distanceToSquared(Xe))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&ae('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const A=this.index,e=this.attributes;if(A===null||e.position===void 0||e.normal===void 0||e.uv===void 0){ae("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const g=e.position,i=e.normal,I=e.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Bt(new Float32Array(4*g.count),4));const C=this.getAttribute("tangent"),o=[],a=[];for(let k=0;k<g.count;k++)o[k]=new J,a[k]=new J;const Q=new J,n=new J,s=new J,B=new Be,E=new Be,d=new Be,c=new J,h=new J;function r(k,x,w){Q.fromBufferAttribute(g,k),n.fromBufferAttribute(g,x),s.fromBufferAttribute(g,w),B.fromBufferAttribute(I,k),E.fromBufferAttribute(I,x),d.fromBufferAttribute(I,w),n.sub(Q),s.sub(Q),E.sub(B),d.sub(B);const N=1/(E.x*d.y-d.x*E.y);isFinite(N)&&(c.copy(n).multiplyScalar(d.y).addScaledVector(s,-E.y).multiplyScalar(N),h.copy(s).multiplyScalar(E.x).addScaledVector(n,-d.x).multiplyScalar(N),o[k].add(c),o[x].add(c),o[w].add(c),a[k].add(h),a[x].add(h),a[w].add(h))}let f=this.groups;f.length===0&&(f=[{start:0,count:A.count}]);for(let k=0,x=f.length;k<x;++k){const w=f[k],N=w.start,U=w.count;for(let K=N,P=N+U;K<P;K+=3)r(A.getX(K+0),A.getX(K+1),A.getX(K+2))}const _=new J,l=new J,D=new J,p=new J;function y(k){D.fromBufferAttribute(i,k),p.copy(D);const x=o[k];_.copy(x),_.sub(D.multiplyScalar(D.dot(x))).normalize(),l.crossVectors(p,x);const N=l.dot(a[k])<0?-1:1;C.setXYZW(k,_.x,_.y,_.z,N)}for(let k=0,x=f.length;k<x;++k){const w=f[k],N=w.start,U=w.count;for(let K=N,P=N+U;K<P;K+=3)y(A.getX(K+0)),y(A.getX(K+1)),y(A.getX(K+2))}}computeVertexNormals(){const A=this.index,e=this.getAttribute("position");if(e!==void 0){let g=this.getAttribute("normal");if(g===void 0)g=new Bt(new Float32Array(e.count*3),3),this.setAttribute("normal",g);else for(let B=0,E=g.count;B<E;B++)g.setXYZ(B,0,0,0);const i=new J,I=new J,C=new J,o=new J,a=new J,Q=new J,n=new J,s=new J;if(A)for(let B=0,E=A.count;B<E;B+=3){const d=A.getX(B+0),c=A.getX(B+1),h=A.getX(B+2);i.fromBufferAttribute(e,d),I.fromBufferAttribute(e,c),C.fromBufferAttribute(e,h),n.subVectors(C,I),s.subVectors(i,I),n.cross(s),o.fromBufferAttribute(g,d),a.fromBufferAttribute(g,c),Q.fromBufferAttribute(g,h),o.add(n),a.add(n),Q.add(n),g.setXYZ(d,o.x,o.y,o.z),g.setXYZ(c,a.x,a.y,a.z),g.setXYZ(h,Q.x,Q.y,Q.z)}else for(let B=0,E=e.count;B<E;B+=3)i.fromBufferAttribute(e,B+0),I.fromBufferAttribute(e,B+1),C.fromBufferAttribute(e,B+2),n.subVectors(C,I),s.subVectors(i,I),n.cross(s),g.setXYZ(B+0,n.x,n.y,n.z),g.setXYZ(B+1,n.x,n.y,n.z),g.setXYZ(B+2,n.x,n.y,n.z);this.normalizeNormals(),g.needsUpdate=!0}}normalizeNormals(){const A=this.attributes.normal;for(let e=0,g=A.count;e<g;e++)Xe.fromBufferAttribute(A,e),Xe.normalize(),A.setXYZ(e,Xe.x,Xe.y,Xe.z)}toNonIndexed(){function A(o,a){const Q=o.array,n=o.itemSize,s=o.normalized,B=new Q.constructor(a.length*n);let E=0,d=0;for(let c=0,h=a.length;c<h;c++){o.isInterleavedBufferAttribute?E=a[c]*o.data.stride+o.offset:E=a[c]*n;for(let r=0;r<n;r++)B[d++]=Q[E++]}return new Bt(B,n,s)}if(this.index===null)return LA("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new Wg,g=this.index.array,i=this.attributes;for(const o in i){const a=i[o],Q=A(a,g);e.setAttribute(o,Q)}const I=this.morphAttributes;for(const o in I){const a=[],Q=I[o];for(let n=0,s=Q.length;n<s;n++){const B=Q[n],E=A(B,g);a.push(E)}e.morphAttributes[o]=a}e.morphTargetsRelative=this.morphTargetsRelative;const C=this.groups;for(let o=0,a=C.length;o<a;o++){const Q=C[o];e.addGroup(Q.start,Q.count,Q.materialIndex)}return e}toJSON(){const A={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(A.uuid=this.uuid,A.type=this.type,this.name!==""&&(A.name=this.name),Object.keys(this.userData).length>0&&(A.userData=this.userData),this.parameters!==void 0){const a=this.parameters;for(const Q in a)a[Q]!==void 0&&(A[Q]=a[Q]);return A}A.data={attributes:{}};const e=this.index;e!==null&&(A.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const g=this.attributes;for(const a in g){const Q=g[a];A.data.attributes[a]=Q.toJSON(A.data)}const i={};let I=!1;for(const a in this.morphAttributes){const Q=this.morphAttributes[a],n=[];for(let s=0,B=Q.length;s<B;s++){const E=Q[s];n.push(E.toJSON(A.data))}n.length>0&&(i[a]=n,I=!0)}I&&(A.data.morphAttributes=i,A.data.morphTargetsRelative=this.morphTargetsRelative);const C=this.groups;C.length>0&&(A.data.groups=JSON.parse(JSON.stringify(C)));const o=this.boundingSphere;return o!==null&&(A.data.boundingSphere=o.toJSON()),A}clone(){return new this.constructor().copy(this)}copy(A){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=A.name;const g=A.index;g!==null&&this.setIndex(g.clone());const i=A.attributes;for(const Q in i){const n=i[Q];this.setAttribute(Q,n.clone(e))}const I=A.morphAttributes;for(const Q in I){const n=[],s=I[Q];for(let B=0,E=s.length;B<E;B++)n.push(s[B].clone(e));this.morphAttributes[Q]=n}this.morphTargetsRelative=A.morphTargetsRelative;const C=A.groups;for(let Q=0,n=C.length;Q<n;Q++){const s=C[Q];this.addGroup(s.start,s.count,s.materialIndex)}const o=A.boundingBox;o!==null&&(this.boundingBox=o.clone());const a=A.boundingSphere;return a!==null&&(this.boundingSphere=a.clone()),this.drawRange.start=A.drawRange.start,this.drawRange.count=A.drawRange.count,this.userData=A.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const N0=new Ye,Ri=new Jf,Go=new Vn,S0=new J,Mo=new J,Fo=new J,Uo=new J,os=new J,Lo=new J,k0=new J,Ko=new J;class Xg extends pg{constructor(A=new Wg,e=new m0){super(),this.isMesh=!0,this.type="Mesh",this.geometry=A,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(A,e){return super.copy(A,e),A.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=A.morphTargetInfluences.slice()),A.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},A.morphTargetDictionary)),this.material=Array.isArray(A.material)?A.material.slice():A.material,this.geometry=A.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,g=Object.keys(e);if(g.length>0){const i=e[g[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let I=0,C=i.length;I<C;I++){const o=i[I].name||String(I);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=I}}}}getVertexPosition(A,e){const g=this.geometry,i=g.attributes.position,I=g.morphAttributes.position,C=g.morphTargetsRelative;e.fromBufferAttribute(i,A);const o=this.morphTargetInfluences;if(I&&o){Lo.set(0,0,0);for(let a=0,Q=I.length;a<Q;a++){const n=o[a],s=I[a];n!==0&&(os.fromBufferAttribute(s,A),C?Lo.addScaledVector(os,n):Lo.addScaledVector(os.sub(e),n))}e.add(Lo)}return e}raycast(A,e){const g=this.geometry,i=this.material,I=this.matrixWorld;i!==void 0&&(g.boundingSphere===null&&g.computeBoundingSphere(),Go.copy(g.boundingSphere),Go.applyMatrix4(I),Ri.copy(A.ray).recast(A.near),!(Go.containsPoint(Ri.origin)===!1&&(Ri.intersectSphere(Go,S0)===null||Ri.origin.distanceToSquared(S0)>(A.far-A.near)**2))&&(N0.copy(I).invert(),Ri.copy(A.ray).applyMatrix4(N0),!(g.boundingBox!==null&&Ri.intersectsBox(g.boundingBox)===!1)&&this._computeIntersections(A,e,Ri)))}_computeIntersections(A,e,g){let i;const I=this.geometry,C=this.material,o=I.index,a=I.attributes.position,Q=I.attributes.uv,n=I.attributes.uv1,s=I.attributes.normal,B=I.groups,E=I.drawRange;if(o!==null)if(Array.isArray(C))for(let d=0,c=B.length;d<c;d++){const h=B[d],r=C[h.materialIndex],f=Math.max(h.start,E.start),_=Math.min(o.count,Math.min(h.start+h.count,E.start+E.count));for(let l=f,D=_;l<D;l+=3){const p=o.getX(l),y=o.getX(l+1),k=o.getX(l+2);i=vo(this,r,A,g,Q,n,s,p,y,k),i&&(i.faceIndex=Math.floor(l/3),i.face.materialIndex=h.materialIndex,e.push(i))}}else{const d=Math.max(0,E.start),c=Math.min(o.count,E.start+E.count);for(let h=d,r=c;h<r;h+=3){const f=o.getX(h),_=o.getX(h+1),l=o.getX(h+2);i=vo(this,C,A,g,Q,n,s,f,_,l),i&&(i.faceIndex=Math.floor(h/3),e.push(i))}}else if(a!==void 0)if(Array.isArray(C))for(let d=0,c=B.length;d<c;d++){const h=B[d],r=C[h.materialIndex],f=Math.max(h.start,E.start),_=Math.min(a.count,Math.min(h.start+h.count,E.start+E.count));for(let l=f,D=_;l<D;l+=3){const p=l,y=l+1,k=l+2;i=vo(this,r,A,g,Q,n,s,p,y,k),i&&(i.faceIndex=Math.floor(l/3),i.face.materialIndex=h.materialIndex,e.push(i))}}else{const d=Math.max(0,E.start),c=Math.min(a.count,E.start+E.count);for(let h=d,r=c;h<r;h+=3){const f=h,_=h+1,l=h+2;i=vo(this,C,A,g,Q,n,s,f,_,l),i&&(i.faceIndex=Math.floor(h/3),e.push(i))}}}}function Xf(t,A,e,g,i,I,C,o){let a;if(A.side===tg?a=g.intersectTriangle(C,I,i,!0,o):a=g.intersectTriangle(i,I,C,A.side===bt,o),a===null)return null;Ko.copy(o),Ko.applyMatrix4(t.matrixWorld);const Q=e.ray.origin.distanceTo(Ko);return Q<e.near||Q>e.far?null:{distance:Q,point:Ko.clone(),object:t}}function vo(t,A,e,g,i,I,C,o,a,Q){t.getVertexPosition(o,Mo),t.getVertexPosition(a,Fo),t.getVertexPosition(Q,Uo);const n=Xf(t,A,e,g,Mo,Fo,Uo,k0);if(n){const s=new J;jg.getBarycoord(k0,Mo,Fo,Uo,s),i&&(n.uv=jg.getInterpolatedAttribute(i,o,a,Q,s,new Be)),I&&(n.uv1=jg.getInterpolatedAttribute(I,o,a,Q,s,new Be)),C&&(n.normal=jg.getInterpolatedAttribute(C,o,a,Q,s,new J),n.normal.dot(g.direction)>0&&n.normal.multiplyScalar(-1));const B={a:o,b:a,c:Q,normal:new J,materialIndex:0};jg.getNormal(Mo,Fo,Uo,B.normal),n.face=B,n.barycoord=s}return n}class hC extends Wg{constructor(A=1,e=1,g=1,i=1,I=1,C=1){super(),this.type="BoxGeometry",this.parameters={width:A,height:e,depth:g,widthSegments:i,heightSegments:I,depthSegments:C};const o=this;i=Math.floor(i),I=Math.floor(I),C=Math.floor(C);const a=[],Q=[],n=[],s=[];let B=0,E=0;d("z","y","x",-1,-1,g,e,A,C,I,0),d("z","y","x",1,-1,g,e,-A,C,I,1),d("x","z","y",1,1,A,g,e,i,C,2),d("x","z","y",1,-1,A,g,-e,i,C,3),d("x","y","z",1,-1,A,e,g,i,I,4),d("x","y","z",-1,-1,A,e,-g,i,I,5),this.setIndex(a),this.setAttribute("position",new Ig(Q,3)),this.setAttribute("normal",new Ig(n,3)),this.setAttribute("uv",new Ig(s,2));function d(c,h,r,f,_,l,D,p,y,k,x){const w=l/y,N=D/k,U=l/2,K=D/2,P=p/2,j=y+1,H=k+1;let O=0,z=0;const xA=new J;for(let sA=0;sA<H;sA++){const fA=sA*N-K;for(let JA=0;JA<j;JA++){const vA=JA*w-U;xA[c]=vA*f,xA[h]=fA*_,xA[r]=P,Q.push(xA.x,xA.y,xA.z),xA[c]=0,xA[h]=0,xA[r]=p>0?1:-1,n.push(xA.x,xA.y,xA.z),s.push(JA/y),s.push(1-sA/k),O+=1}}for(let sA=0;sA<k;sA++)for(let fA=0;fA<y;fA++){const JA=B+fA+j*sA,vA=B+fA+j*(sA+1),be=B+(fA+1)+j*(sA+1),le=B+(fA+1)+j*sA;a.push(JA,vA,le),a.push(vA,be,le),z+=6}o.addGroup(E,z,x),E+=z,B+=O}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new hC(A.width,A.height,A.depth,A.widthSegments,A.heightSegments,A.depthSegments)}}function pI(t){const A={};for(const e in t){A[e]={};for(const g in t[e]){const i=t[e][g];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(LA("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),A[e][g]=null):A[e][g]=i.clone():Array.isArray(i)?A[e][g]=i.slice():A[e][g]=i}}return A}function Cg(t){const A={};for(let e=0;e<t.length;e++){const g=pI(t[e]);for(const i in g)A[i]=g[i]}return A}function Zf(t){const A=[];for(let e=0;e<t.length;e++)A.push(t[e].clone());return A}function R0(t){const A=t.getRenderTarget();return A===null?t.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ce.workingColorSpace}const zf={clone:pI,merge:Cg};var $f=`void main() {
|
|
152
152
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
153
153
|
}`,Au=`void main() {
|
|
154
154
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
155
|
-
}`;class Gg extends ko{constructor(A){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=$f,this.fragmentShader=Au,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,A!==void 0&&this.setValues(A)}copy(A){return super.copy(A),this.fragmentShader=A.fragmentShader,this.vertexShader=A.vertexShader,this.uniforms=pI(A.uniforms),this.uniformsGroups=Zf(A.uniformsGroups),this.defines=Object.assign({},A.defines),this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.fog=A.fog,this.lights=A.lights,this.clipping=A.clipping,this.extensions=Object.assign({},A.extensions),this.glslVersion=A.glslVersion,this.defaultAttributeValues=Object.assign({},A.defaultAttributeValues),this.index0AttributeName=A.index0AttributeName,this.uniformsNeedUpdate=A.uniformsNeedUpdate,this}toJSON(A){const e=super.toJSON(A);e.glslVersion=this.glslVersion,e.uniforms={};for(const i in this.uniforms){const C=this.uniforms[i].value;C&&C.isTexture?e.uniforms[i]={type:"t",value:C.toJSON(A).uuid}:C&&C.isColor?e.uniforms[i]={type:"c",value:C.getHex()}:C&&C.isVector2?e.uniforms[i]={type:"v2",value:C.toArray()}:C&&C.isVector3?e.uniforms[i]={type:"v3",value:C.toArray()}:C&&C.isVector4?e.uniforms[i]={type:"v4",value:C.toArray()}:C&&C.isMatrix3?e.uniforms[i]={type:"m3",value:C.toArray()}:C&&C.isMatrix4?e.uniforms[i]={type:"m4",value:C.toArray()}:e.uniforms[i]={value:C}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const g={};for(const i in this.extensions)this.extensions[i]===!0&&(g[i]=!0);return Object.keys(g).length>0&&(e.extensions=g),e}}class G0 extends pg{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ye,this.projectionMatrix=new Ye,this.projectionMatrixInverse=new Ye,this.coordinateSystem=nt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(A,e){return super.copy(A,e),this.matrixWorldInverse.copy(A.matrixWorldInverse),this.projectionMatrix.copy(A.projectionMatrix),this.projectionMatrixInverse.copy(A.projectionMatrixInverse),this.coordinateSystem=A.coordinateSystem,this}getWorldDirection(A){return super.getWorldDirection(A).negate()}updateMatrixWorld(A){super.updateMatrixWorld(A),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(A,e){super.updateWorldMatrix(A,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ni=new J,M0=new Be,F0=new Be;class Mg extends G0{constructor(A=50,e=1,g=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=A,this.zoom=1,this.near=g,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(A,e){return super.copy(A,e),this.fov=A.fov,this.zoom=A.zoom,this.near=A.near,this.far=A.far,this.focus=A.focus,this.aspect=A.aspect,this.view=A.view===null?null:Object.assign({},A.view),this.filmGauge=A.filmGauge,this.filmOffset=A.filmOffset,this}setFocalLength(A){const e=.5*this.getFilmHeight()/A;this.fov=Kn*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const A=Math.tan(Ln*.5*this.fov);return .5*this.getFilmHeight()/A}getEffectiveFOV(){return Kn*2*Math.atan(Math.tan(Ln*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(A,e,g){ni.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(ni.x,ni.y).multiplyScalar(-A/ni.z),ni.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),g.set(ni.x,ni.y).multiplyScalar(-A/ni.z)}getViewSize(A,e){return this.getViewBounds(A,M0,F0),e.subVectors(F0,M0)}setViewOffset(A,e,g,i,I,C){this.aspect=A/e,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=A,this.view.fullHeight=e,this.view.offsetX=g,this.view.offsetY=i,this.view.width=I,this.view.height=C,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=this.near;let e=A*Math.tan(Ln*.5*this.fov)/this.zoom,g=2*e,i=this.aspect*g,I=-.5*i;const C=this.view;if(this.view!==null&&this.view.enabled){const a=C.fullWidth,Q=C.fullHeight;I+=C.offsetX*i/a,e-=C.offsetY*g/Q,i*=C.width/a,g*=C.height/Q}const o=this.filmOffset;o!==0&&(I+=A*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(I,I+i,e,e-g,A,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const e=super.toJSON(A);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const mI=-90,yI=1;class eu extends pg{constructor(A,e,g){super(),this.type="CubeCamera",this.renderTarget=g,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Mg(mI,yI,A,e);i.layers=this.layers,this.add(i);const I=new Mg(mI,yI,A,e);I.layers=this.layers,this.add(I);const C=new Mg(mI,yI,A,e);C.layers=this.layers,this.add(C);const o=new Mg(mI,yI,A,e);o.layers=this.layers,this.add(o);const a=new Mg(mI,yI,A,e);a.layers=this.layers,this.add(a);const Q=new Mg(mI,yI,A,e);Q.layers=this.layers,this.add(Q)}updateCoordinateSystem(){const A=this.coordinateSystem,e=this.children.concat(),[g,i,I,C,o,a]=e;for(const Q of e)this.remove(Q);if(A===nt)g.up.set(0,1,0),g.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),I.up.set(0,0,-1),I.lookAt(0,1,0),C.up.set(0,0,1),C.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else if(A===uo)g.up.set(0,-1,0),g.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),I.up.set(0,0,1),I.lookAt(0,1,0),C.up.set(0,0,-1),C.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(const Q of e)this.add(Q),Q.updateMatrixWorld()}update(A,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:g,activeMipmapLevel:i}=this;this.coordinateSystem!==A.coordinateSystem&&(this.coordinateSystem=A.coordinateSystem,this.updateCoordinateSystem());const[I,C,o,a,Q,n]=this.children,s=A.getRenderTarget(),B=A.getActiveCubeFace(),E=A.getActiveMipmapLevel(),d=A.xr.enabled;A.xr.enabled=!1;const c=g.texture.generateMipmaps;g.texture.generateMipmaps=!1,A.setRenderTarget(g,0,i),A.render(e,I),A.setRenderTarget(g,1,i),A.render(e,C),A.setRenderTarget(g,2,i),A.render(e,o),A.setRenderTarget(g,3,i),A.render(e,a),A.setRenderTarget(g,4,i),A.render(e,Q),g.texture.generateMipmaps=c,A.setRenderTarget(g,5,i),A.render(e,n),A.setRenderTarget(s,B,E),A.xr.enabled=d,g.texture.needsPMREMUpdate=!0}}class U0 extends ig{constructor(A=[],e=
|
|
155
|
+
}`;class Gg extends ko{constructor(A){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=$f,this.fragmentShader=Au,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,A!==void 0&&this.setValues(A)}copy(A){return super.copy(A),this.fragmentShader=A.fragmentShader,this.vertexShader=A.vertexShader,this.uniforms=pI(A.uniforms),this.uniformsGroups=Zf(A.uniformsGroups),this.defines=Object.assign({},A.defines),this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.fog=A.fog,this.lights=A.lights,this.clipping=A.clipping,this.extensions=Object.assign({},A.extensions),this.glslVersion=A.glslVersion,this.defaultAttributeValues=Object.assign({},A.defaultAttributeValues),this.index0AttributeName=A.index0AttributeName,this.uniformsNeedUpdate=A.uniformsNeedUpdate,this}toJSON(A){const e=super.toJSON(A);e.glslVersion=this.glslVersion,e.uniforms={};for(const i in this.uniforms){const C=this.uniforms[i].value;C&&C.isTexture?e.uniforms[i]={type:"t",value:C.toJSON(A).uuid}:C&&C.isColor?e.uniforms[i]={type:"c",value:C.getHex()}:C&&C.isVector2?e.uniforms[i]={type:"v2",value:C.toArray()}:C&&C.isVector3?e.uniforms[i]={type:"v3",value:C.toArray()}:C&&C.isVector4?e.uniforms[i]={type:"v4",value:C.toArray()}:C&&C.isMatrix3?e.uniforms[i]={type:"m3",value:C.toArray()}:C&&C.isMatrix4?e.uniforms[i]={type:"m4",value:C.toArray()}:e.uniforms[i]={value:C}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const g={};for(const i in this.extensions)this.extensions[i]===!0&&(g[i]=!0);return Object.keys(g).length>0&&(e.extensions=g),e}}class G0 extends pg{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ye,this.projectionMatrix=new Ye,this.projectionMatrixInverse=new Ye,this.coordinateSystem=nt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(A,e){return super.copy(A,e),this.matrixWorldInverse.copy(A.matrixWorldInverse),this.projectionMatrix.copy(A.projectionMatrix),this.projectionMatrixInverse.copy(A.projectionMatrixInverse),this.coordinateSystem=A.coordinateSystem,this}getWorldDirection(A){return super.getWorldDirection(A).negate()}updateMatrixWorld(A){super.updateMatrixWorld(A),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(A,e){super.updateWorldMatrix(A,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ni=new J,M0=new Be,F0=new Be;class Mg extends G0{constructor(A=50,e=1,g=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=A,this.zoom=1,this.near=g,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(A,e){return super.copy(A,e),this.fov=A.fov,this.zoom=A.zoom,this.near=A.near,this.far=A.far,this.focus=A.focus,this.aspect=A.aspect,this.view=A.view===null?null:Object.assign({},A.view),this.filmGauge=A.filmGauge,this.filmOffset=A.filmOffset,this}setFocalLength(A){const e=.5*this.getFilmHeight()/A;this.fov=Kn*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const A=Math.tan(Ln*.5*this.fov);return .5*this.getFilmHeight()/A}getEffectiveFOV(){return Kn*2*Math.atan(Math.tan(Ln*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(A,e,g){ni.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(ni.x,ni.y).multiplyScalar(-A/ni.z),ni.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),g.set(ni.x,ni.y).multiplyScalar(-A/ni.z)}getViewSize(A,e){return this.getViewBounds(A,M0,F0),e.subVectors(F0,M0)}setViewOffset(A,e,g,i,I,C){this.aspect=A/e,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=A,this.view.fullHeight=e,this.view.offsetX=g,this.view.offsetY=i,this.view.width=I,this.view.height=C,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=this.near;let e=A*Math.tan(Ln*.5*this.fov)/this.zoom,g=2*e,i=this.aspect*g,I=-.5*i;const C=this.view;if(this.view!==null&&this.view.enabled){const a=C.fullWidth,Q=C.fullHeight;I+=C.offsetX*i/a,e-=C.offsetY*g/Q,i*=C.width/a,g*=C.height/Q}const o=this.filmOffset;o!==0&&(I+=A*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(I,I+i,e,e-g,A,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const e=super.toJSON(A);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const mI=-90,yI=1;class eu extends pg{constructor(A,e,g){super(),this.type="CubeCamera",this.renderTarget=g,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Mg(mI,yI,A,e);i.layers=this.layers,this.add(i);const I=new Mg(mI,yI,A,e);I.layers=this.layers,this.add(I);const C=new Mg(mI,yI,A,e);C.layers=this.layers,this.add(C);const o=new Mg(mI,yI,A,e);o.layers=this.layers,this.add(o);const a=new Mg(mI,yI,A,e);a.layers=this.layers,this.add(a);const Q=new Mg(mI,yI,A,e);Q.layers=this.layers,this.add(Q)}updateCoordinateSystem(){const A=this.coordinateSystem,e=this.children.concat(),[g,i,I,C,o,a]=e;for(const Q of e)this.remove(Q);if(A===nt)g.up.set(0,1,0),g.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),I.up.set(0,0,-1),I.lookAt(0,1,0),C.up.set(0,0,1),C.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else if(A===uo)g.up.set(0,-1,0),g.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),I.up.set(0,0,1),I.lookAt(0,1,0),C.up.set(0,0,-1),C.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(const Q of e)this.add(Q),Q.updateMatrixWorld()}update(A,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:g,activeMipmapLevel:i}=this;this.coordinateSystem!==A.coordinateSystem&&(this.coordinateSystem=A.coordinateSystem,this.updateCoordinateSystem());const[I,C,o,a,Q,n]=this.children,s=A.getRenderTarget(),B=A.getActiveCubeFace(),E=A.getActiveMipmapLevel(),d=A.xr.enabled;A.xr.enabled=!1;const c=g.texture.generateMipmaps;g.texture.generateMipmaps=!1,A.setRenderTarget(g,0,i),A.render(e,I),A.setRenderTarget(g,1,i),A.render(e,C),A.setRenderTarget(g,2,i),A.render(e,o),A.setRenderTarget(g,3,i),A.render(e,a),A.setRenderTarget(g,4,i),A.render(e,Q),g.texture.generateMipmaps=c,A.setRenderTarget(g,5,i),A.render(e,n),A.setRenderTarget(s,B,E),A.xr.enabled=d,g.texture.needsPMREMUpdate=!0}}class U0 extends ig{constructor(A=[],e=yi,g,i,I,C,o,a,Q,n){super(A,e,g,i,I,C,o,a,Q,n),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(A){this.image=A}}class L0 extends st{constructor(A=1,e={}){super(A,A,e),this.isWebGLCubeRenderTarget=!0;const g={width:A,height:A,depth:1},i=[g,g,g,g,g,g];this.texture=new U0(i),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(A,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const g={uniforms:{tEquirect:{value:null}},vertexShader:`
|
|
156
156
|
|
|
157
157
|
varying vec3 vWorldDirection;
|
|
158
158
|
|
|
@@ -187,7 +187,7 @@ a=extmap-allow-mixed`)!==-1){const I=i.sdp.split(`
|
|
|
187
187
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
188
188
|
|
|
189
189
|
}
|
|
190
|
-
`},i=new hC(5,5,5),I=new Gg({name:"CubemapFromEquirect",uniforms:pI(g.uniforms),vertexShader:g.vertexShader,fragmentShader:g.fragmentShader,side:tg,blending:St});I.uniforms.tEquirect.value=e;const C=new Xg(i,I),o=e.minFilter;return e.minFilter===yi&&(e.minFilter=Ag),new eu(1,10,this).update(A,C),e.minFilter=o,C.geometry.dispose(),C.material.dispose(),this}clear(A,e=!0,g=!0,i=!0){const I=A.getRenderTarget();for(let C=0;C<6;C++)A.setRenderTarget(this,C),A.clear(e,g,i);A.setRenderTarget(I)}}class Jo extends pg{constructor(){super(),this.isGroup=!0,this.type="Group"}}const gu={type:"move"};class as{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Jo,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 Jo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new J,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new J),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Jo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new J,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new J),this._grip}dispatchEvent(A){return this._targetRay!==null&&this._targetRay.dispatchEvent(A),this._grip!==null&&this._grip.dispatchEvent(A),this._hand!==null&&this._hand.dispatchEvent(A),this}connect(A){if(A&&A.hand){const e=this._hand;if(e)for(const g of A.hand.values())this._getHandJoint(e,g)}return this.dispatchEvent({type:"connected",data:A}),this}disconnect(A){return this.dispatchEvent({type:"disconnected",data:A}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(A,e,g){let i=null,I=null,C=null;const o=this._targetRay,a=this._grip,Q=this._hand;if(A&&e.session.visibilityState!=="visible-blurred"){if(Q&&A.hand){C=!0;for(const c of A.hand.values()){const h=e.getJointPose(c,g),r=this._getHandJoint(Q,c);h!==null&&(r.matrix.fromArray(h.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=h.radius),r.visible=h!==null}const n=Q.joints["index-finger-tip"],s=Q.joints["thumb-tip"],B=n.position.distanceTo(s.position),E=.02,d=.005;Q.inputState.pinching&&B>E+d?(Q.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this})):!Q.inputState.pinching&&B<=E-d&&(Q.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this}))}else a!==null&&A.gripSpace&&(I=e.getPose(A.gripSpace,g),I!==null&&(a.matrix.fromArray(I.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,I.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(I.linearVelocity)):a.hasLinearVelocity=!1,I.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(I.angularVelocity)):a.hasAngularVelocity=!1));o!==null&&(i=e.getPose(A.targetRaySpace,g),i===null&&I!==null&&(i=I),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(gu)))}return o!==null&&(o.visible=i!==null),a!==null&&(a.visible=I!==null),Q!==null&&(Q.visible=C!==null),this}_getHandJoint(A,e){if(A.joints[e.jointName]===void 0){const g=new Jo;g.matrixAutoUpdate=!1,g.visible=!1,A.joints[e.jointName]=g,A.add(g)}return A.joints[e.jointName]}}class tu extends pg{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 Lt,this.environmentIntensity=1,this.environmentRotation=new Lt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(A,e){return super.copy(A,e),A.background!==null&&(this.background=A.background.clone()),A.environment!==null&&(this.environment=A.environment.clone()),A.fog!==null&&(this.fog=A.fog.clone()),this.backgroundBlurriness=A.backgroundBlurriness,this.backgroundIntensity=A.backgroundIntensity,this.backgroundRotation.copy(A.backgroundRotation),this.environmentIntensity=A.environmentIntensity,this.environmentRotation.copy(A.environmentRotation),A.overrideMaterial!==null&&(this.overrideMaterial=A.overrideMaterial.clone()),this.matrixAutoUpdate=A.matrixAutoUpdate,this}toJSON(A){const e=super.toJSON(A);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class iu extends ig{constructor(A=null,e=1,g=1,i,I,C,o,a,Q=$e,n=$e,s,B){super(null,C,o,a,Q,n,i,I,s,B),this.isDataTexture=!0,this.image={data:A,width:e,height:g},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Qs=new J,Iu=new J,Cu=new YA;class Ri{constructor(A=new J(1,0,0),e=0){this.isPlane=!0,this.normal=A,this.constant=e}set(A,e){return this.normal.copy(A),this.constant=e,this}setComponents(A,e,g,i){return this.normal.set(A,e,g),this.constant=i,this}setFromNormalAndCoplanarPoint(A,e){return this.normal.copy(A),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(A,e,g){const i=Qs.subVectors(g,e).cross(Iu.subVectors(A,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,A),this}copy(A){return this.normal.copy(A.normal),this.constant=A.constant,this}normalize(){const A=1/this.normal.length();return this.normal.multiplyScalar(A),this.constant*=A,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(A){return this.normal.dot(A)+this.constant}distanceToSphere(A){return this.distanceToPoint(A.center)-A.radius}projectPoint(A,e){return e.copy(A).addScaledVector(this.normal,-this.distanceToPoint(A))}intersectLine(A,e){const g=A.delta(Qs),i=this.normal.dot(g);if(i===0)return this.distanceToPoint(A.start)===0?e.copy(A.start):null;const I=-(A.start.dot(this.normal)+this.constant)/i;return I<0||I>1?null:e.copy(A.start).addScaledVector(g,I)}intersectsLine(A){const e=this.distanceToPoint(A.start),g=this.distanceToPoint(A.end);return e<0&&g>0||g<0&&e>0}intersectsBox(A){return A.intersectsPlane(this)}intersectsSphere(A){return A.intersectsPlane(this)}coplanarPoint(A){return A.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(A,e){const g=e||Cu.getNormalMatrix(A),i=this.coplanarPoint(Qs).applyMatrix4(A),I=this.normal.applyMatrix3(g).normalize();return this.constant=-i.dot(I),this}translate(A){return this.constant-=A.dot(this.normal),this}equals(A){return A.normal.equals(this.normal)&&A.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Gi=new Vn,ou=new Be(.5,.5),Yo=new J;class K0{constructor(A=new Ri,e=new Ri,g=new Ri,i=new Ri,I=new Ri,C=new Ri){this.planes=[A,e,g,i,I,C]}set(A,e,g,i,I,C){const o=this.planes;return o[0].copy(A),o[1].copy(e),o[2].copy(g),o[3].copy(i),o[4].copy(I),o[5].copy(C),this}copy(A){const e=this.planes;for(let g=0;g<6;g++)e[g].copy(A.planes[g]);return this}setFromProjectionMatrix(A,e=nt,g=!1){const i=this.planes,I=A.elements,C=I[0],o=I[1],a=I[2],Q=I[3],n=I[4],s=I[5],B=I[6],E=I[7],d=I[8],c=I[9],h=I[10],r=I[11],f=I[12],_=I[13],l=I[14],D=I[15];if(i[0].setComponents(Q-C,E-n,r-d,D-f).normalize(),i[1].setComponents(Q+C,E+n,r+d,D+f).normalize(),i[2].setComponents(Q+o,E+s,r+c,D+_).normalize(),i[3].setComponents(Q-o,E-s,r-c,D-_).normalize(),g)i[4].setComponents(a,B,h,l).normalize(),i[5].setComponents(Q-a,E-B,r-h,D-l).normalize();else if(i[4].setComponents(Q-a,E-B,r-h,D-l).normalize(),e===nt)i[5].setComponents(Q+a,E+B,r+h,D+l).normalize();else if(e===uo)i[5].setComponents(a,B,h,l).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(A){if(A.boundingSphere!==void 0)A.boundingSphere===null&&A.computeBoundingSphere(),Gi.copy(A.boundingSphere).applyMatrix4(A.matrixWorld);else{const e=A.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Gi.copy(e.boundingSphere).applyMatrix4(A.matrixWorld)}return this.intersectsSphere(Gi)}intersectsSprite(A){Gi.center.set(0,0,0);const e=ou.distanceTo(A.center);return Gi.radius=.7071067811865476+e,Gi.applyMatrix4(A.matrixWorld),this.intersectsSphere(Gi)}intersectsSphere(A){const e=this.planes,g=A.center,i=-A.radius;for(let I=0;I<6;I++)if(e[I].distanceToPoint(g)<i)return!1;return!0}intersectsBox(A){const e=this.planes;for(let g=0;g<6;g++){const i=e[g];if(Yo.x=i.normal.x>0?A.max.x:A.min.x,Yo.y=i.normal.y>0?A.max.y:A.min.y,Yo.z=i.normal.z>0?A.max.z:A.min.z,i.distanceToPoint(Yo)<0)return!1}return!0}containsPoint(A){const e=this.planes;for(let g=0;g<6;g++)if(e[g].distanceToPoint(A)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class dC extends ig{constructor(A,e,g=at,i,I,C,o=$e,a=$e,Q,n=Gt,s=1){if(n!==Gt&&n!==bi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const B={width:A,height:e,depth:s};super(B,i,I,C,o,a,n,g,Q),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(A){return super.copy(A),this.source=new Tn(Object.assign({},A.image)),this.compareFunction=A.compareFunction,this}toJSON(A){const e=super.toJSON(A);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class au extends dC{constructor(A,e=at,g=mi,i,I,C=$e,o=$e,a,Q=Gt){const n={width:A,height:A,depth:1},s=[n,n,n,n,n,n];super(A,A,e,g,i,I,C,o,a,Q),this.image=s,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(A){this.image=A}}class v0 extends ig{constructor(A=null){super(),this.sourceTexture=A,this.isExternalTexture=!0}copy(A){return super.copy(A),this.sourceTexture=A.sourceTexture,this}}class ns extends Wg{constructor(A=[],e=[],g=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:A,indices:e,radius:g,detail:i};const I=[],C=[];o(i),Q(g),n(),this.setAttribute("position",new Ig(I,3)),this.setAttribute("normal",new Ig(I.slice(),3)),this.setAttribute("uv",new Ig(C,2)),i===0?this.computeVertexNormals():this.normalizeNormals();function o(f){const _=new J,l=new J,D=new J;for(let p=0;p<e.length;p+=3)E(e[p+0],_),E(e[p+1],l),E(e[p+2],D),a(_,l,D,f)}function a(f,_,l,D){const p=D+1,y=[];for(let k=0;k<=p;k++){y[k]=[];const x=f.clone().lerp(l,k/p),w=_.clone().lerp(l,k/p),N=p-k;for(let U=0;U<=N;U++)U===0&&k===p?y[k][U]=x:y[k][U]=x.clone().lerp(w,U/N)}for(let k=0;k<p;k++)for(let x=0;x<2*(p-k)-1;x++){const w=Math.floor(x/2);x%2===0?(B(y[k][w+1]),B(y[k+1][w]),B(y[k][w])):(B(y[k][w+1]),B(y[k+1][w+1]),B(y[k+1][w]))}}function Q(f){const _=new J;for(let l=0;l<I.length;l+=3)_.x=I[l+0],_.y=I[l+1],_.z=I[l+2],_.normalize().multiplyScalar(f),I[l+0]=_.x,I[l+1]=_.y,I[l+2]=_.z}function n(){const f=new J;for(let _=0;_<I.length;_+=3){f.x=I[_+0],f.y=I[_+1],f.z=I[_+2];const l=h(f)/2/Math.PI+.5,D=r(f)/Math.PI+.5;C.push(l,1-D)}d(),s()}function s(){for(let f=0;f<C.length;f+=6){const _=C[f+0],l=C[f+2],D=C[f+4],p=Math.max(_,l,D),y=Math.min(_,l,D);p>.9&&y<.1&&(_<.2&&(C[f+0]+=1),l<.2&&(C[f+2]+=1),D<.2&&(C[f+4]+=1))}}function B(f){I.push(f.x,f.y,f.z)}function E(f,_){const l=f*3;_.x=A[l+0],_.y=A[l+1],_.z=A[l+2]}function d(){const f=new J,_=new J,l=new J,D=new J,p=new Be,y=new Be,k=new Be;for(let x=0,w=0;x<I.length;x+=9,w+=6){f.set(I[x+0],I[x+1],I[x+2]),_.set(I[x+3],I[x+4],I[x+5]),l.set(I[x+6],I[x+7],I[x+8]),p.set(C[w+0],C[w+1]),y.set(C[w+2],C[w+3]),k.set(C[w+4],C[w+5]),D.copy(f).add(_).add(l).divideScalar(3);const N=h(D);c(p,w+0,f,N),c(y,w+2,_,N),c(k,w+4,l,N)}}function c(f,_,l,D){D<0&&f.x===1&&(C[_]=f.x-1),l.x===0&&l.z===0&&(C[_]=D/2/Math.PI+.5)}function h(f){return Math.atan2(f.z,-f.x)}function r(f){return Math.atan2(-f.y,Math.sqrt(f.x*f.x+f.z*f.z))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new ns(A.vertices,A.indices,A.radius,A.detail)}}class ss extends ns{constructor(A=1,e=0){const g=(1+Math.sqrt(5))/2,i=[-1,g,0,1,g,0,-1,-g,0,1,-g,0,0,-1,g,0,1,g,0,-1,-g,0,1,-g,g,0,-1,g,0,1,-g,0,-1,-g,0,1],I=[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(i,I,A,e),this.type="IcosahedronGeometry",this.parameters={radius:A,detail:e}}static fromJSON(A){return new ss(A.radius,A.detail)}}class To extends Wg{constructor(A=1,e=1,g=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:A,height:e,widthSegments:g,heightSegments:i};const I=A/2,C=e/2,o=Math.floor(g),a=Math.floor(i),Q=o+1,n=a+1,s=A/o,B=e/a,E=[],d=[],c=[],h=[];for(let r=0;r<n;r++){const f=r*B-C;for(let _=0;_<Q;_++){const l=_*s-I;d.push(l,-f,0),c.push(0,0,1),h.push(_/o),h.push(1-r/a)}}for(let r=0;r<a;r++)for(let f=0;f<o;f++){const _=f+Q*r,l=f+Q*(r+1),D=f+1+Q*(r+1),p=f+1+Q*r;E.push(_,l,p),E.push(l,D,p)}this.setIndex(E),this.setAttribute("position",new Ig(d,3)),this.setAttribute("normal",new Ig(c,3)),this.setAttribute("uv",new Ig(h,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new To(A.width,A.height,A.widthSegments,A.heightSegments)}}class Bs extends Wg{constructor(A=1,e=32,g=16,i=0,I=Math.PI*2,C=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:A,widthSegments:e,heightSegments:g,phiStart:i,phiLength:I,thetaStart:C,thetaLength:o},e=Math.max(3,Math.floor(e)),g=Math.max(2,Math.floor(g));const a=Math.min(C+o,Math.PI);let Q=0;const n=[],s=new J,B=new J,E=[],d=[],c=[],h=[];for(let r=0;r<=g;r++){const f=[],_=r/g;let l=0;r===0&&C===0?l=.5/e:r===g&&a===Math.PI&&(l=-.5/e);for(let D=0;D<=e;D++){const p=D/e;s.x=-A*Math.cos(i+p*I)*Math.sin(C+_*o),s.y=A*Math.cos(C+_*o),s.z=A*Math.sin(i+p*I)*Math.sin(C+_*o),d.push(s.x,s.y,s.z),B.copy(s).normalize(),c.push(B.x,B.y,B.z),h.push(p+l,1-_),f.push(Q++)}n.push(f)}for(let r=0;r<g;r++)for(let f=0;f<e;f++){const _=n[r][f+1],l=n[r][f],D=n[r+1][f],p=n[r+1][f+1];(r!==0||C>0)&&E.push(_,l,p),(r!==g-1||a<Math.PI)&&E.push(l,D,p)}this.setIndex(E),this.setAttribute("position",new Ig(d,3)),this.setAttribute("normal",new Ig(c,3)),this.setAttribute("uv",new Ig(h,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new Bs(A.radius,A.widthSegments,A.heightSegments,A.phiStart,A.phiLength,A.thetaStart,A.thetaLength)}}class Qu extends Gg{constructor(A){super(A),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class nu extends ko{constructor(A){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=uf,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(A)}copy(A){return super.copy(A),this.depthPacking=A.depthPacking,this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this}}class su extends ko{constructor(A){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(A)}copy(A){return super.copy(A),this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this}}class J0 extends G0{constructor(A=-1,e=1,g=1,i=-1,I=.1,C=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=A,this.right=e,this.top=g,this.bottom=i,this.near=I,this.far=C,this.updateProjectionMatrix()}copy(A,e){return super.copy(A,e),this.left=A.left,this.right=A.right,this.top=A.top,this.bottom=A.bottom,this.near=A.near,this.far=A.far,this.zoom=A.zoom,this.view=A.view===null?null:Object.assign({},A.view),this}setViewOffset(A,e,g,i,I,C){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=A,this.view.fullHeight=e,this.view.offsetX=g,this.view.offsetY=i,this.view.width=I,this.view.height=C,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),g=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let I=g-A,C=g+A,o=i+e,a=i-e;if(this.view!==null&&this.view.enabled){const Q=(this.right-this.left)/this.view.fullWidth/this.zoom,n=(this.top-this.bottom)/this.view.fullHeight/this.zoom;I+=Q*this.view.offsetX,C=I+Q*this.view.width,o-=n*this.view.offsetY,a=o-n*this.view.height}this.projectionMatrix.makeOrthographic(I,C,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const e=super.toJSON(A);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}}class Bu extends Mg{constructor(A=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=A}}class Eu{constructor(A=!0){this.autoStart=A,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 A=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=performance.now();A=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=A}return A}}function Y0(t,A,e,g){const i=ru(g);switch(e){case t0:return t*A;case I0:return t*A/i.components*i.byteLength;case $Q:return t*A/i.components*i.byteLength;case nI:return t*A*2/i.components*i.byteLength;case An:return t*A*2/i.components*i.byteLength;case i0:return t*A*3/i.components*i.byteLength;case Hg:return t*A*4/i.components*i.byteLength;case en:return t*A*4/i.components*i.byteLength;case co:case ho:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*8;case xo:case lo:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case tn:case Cn:return Math.max(t,16)*Math.max(A,8)/4;case gn:case In:return Math.max(t,8)*Math.max(A,8)/2;case on:case an:case nn:case sn:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*8;case Qn:case Bn:case En:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case rn:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case cn:return Math.floor((t+4)/5)*Math.floor((A+3)/4)*16;case hn:return Math.floor((t+4)/5)*Math.floor((A+4)/5)*16;case dn:return Math.floor((t+5)/6)*Math.floor((A+4)/5)*16;case xn:return Math.floor((t+5)/6)*Math.floor((A+5)/6)*16;case ln:return Math.floor((t+7)/8)*Math.floor((A+4)/5)*16;case fn:return Math.floor((t+7)/8)*Math.floor((A+5)/6)*16;case un:return Math.floor((t+7)/8)*Math.floor((A+7)/8)*16;case Dn:return Math.floor((t+9)/10)*Math.floor((A+4)/5)*16;case _n:return Math.floor((t+9)/10)*Math.floor((A+5)/6)*16;case wn:return Math.floor((t+9)/10)*Math.floor((A+7)/8)*16;case pn:return Math.floor((t+9)/10)*Math.floor((A+9)/10)*16;case mn:return Math.floor((t+11)/12)*Math.floor((A+9)/10)*16;case yn:return Math.floor((t+11)/12)*Math.floor((A+11)/12)*16;case bn:case Nn:case Sn:return Math.ceil(t/4)*Math.ceil(A/4)*16;case kn:case Rn:return Math.ceil(t/4)*Math.ceil(A/4)*8;case Gn:case Mn:return Math.ceil(t/4)*Math.ceil(A/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function ru(t){switch(t){case Sg:case $r:return{byteLength:1,components:1};case IC:case A0:case Rt:return{byteLength:2,components:1};case ZQ:case zQ:return{byteLength:2,components:4};case at:case XQ:case Qt:return{byteLength:4,components:1};case e0:case g0:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:MQ}})),typeof window<"u"&&(window.__THREE__?LA("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=MQ);/**
|
|
190
|
+
`},i=new hC(5,5,5),I=new Gg({name:"CubemapFromEquirect",uniforms:pI(g.uniforms),vertexShader:g.vertexShader,fragmentShader:g.fragmentShader,side:tg,blending:St});I.uniforms.tEquirect.value=e;const C=new Xg(i,I),o=e.minFilter;return e.minFilter===bi&&(e.minFilter=Ag),new eu(1,10,this).update(A,C),e.minFilter=o,C.geometry.dispose(),C.material.dispose(),this}clear(A,e=!0,g=!0,i=!0){const I=A.getRenderTarget();for(let C=0;C<6;C++)A.setRenderTarget(this,C),A.clear(e,g,i);A.setRenderTarget(I)}}class Jo extends pg{constructor(){super(),this.isGroup=!0,this.type="Group"}}const gu={type:"move"};class as{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Jo,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 Jo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new J,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new J),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Jo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new J,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new J),this._grip}dispatchEvent(A){return this._targetRay!==null&&this._targetRay.dispatchEvent(A),this._grip!==null&&this._grip.dispatchEvent(A),this._hand!==null&&this._hand.dispatchEvent(A),this}connect(A){if(A&&A.hand){const e=this._hand;if(e)for(const g of A.hand.values())this._getHandJoint(e,g)}return this.dispatchEvent({type:"connected",data:A}),this}disconnect(A){return this.dispatchEvent({type:"disconnected",data:A}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(A,e,g){let i=null,I=null,C=null;const o=this._targetRay,a=this._grip,Q=this._hand;if(A&&e.session.visibilityState!=="visible-blurred"){if(Q&&A.hand){C=!0;for(const c of A.hand.values()){const h=e.getJointPose(c,g),r=this._getHandJoint(Q,c);h!==null&&(r.matrix.fromArray(h.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=h.radius),r.visible=h!==null}const n=Q.joints["index-finger-tip"],s=Q.joints["thumb-tip"],B=n.position.distanceTo(s.position),E=.02,d=.005;Q.inputState.pinching&&B>E+d?(Q.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this})):!Q.inputState.pinching&&B<=E-d&&(Q.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this}))}else a!==null&&A.gripSpace&&(I=e.getPose(A.gripSpace,g),I!==null&&(a.matrix.fromArray(I.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,I.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(I.linearVelocity)):a.hasLinearVelocity=!1,I.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(I.angularVelocity)):a.hasAngularVelocity=!1));o!==null&&(i=e.getPose(A.targetRaySpace,g),i===null&&I!==null&&(i=I),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(gu)))}return o!==null&&(o.visible=i!==null),a!==null&&(a.visible=I!==null),Q!==null&&(Q.visible=C!==null),this}_getHandJoint(A,e){if(A.joints[e.jointName]===void 0){const g=new Jo;g.matrixAutoUpdate=!1,g.visible=!1,A.joints[e.jointName]=g,A.add(g)}return A.joints[e.jointName]}}class tu extends pg{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 Lt,this.environmentIntensity=1,this.environmentRotation=new Lt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(A,e){return super.copy(A,e),A.background!==null&&(this.background=A.background.clone()),A.environment!==null&&(this.environment=A.environment.clone()),A.fog!==null&&(this.fog=A.fog.clone()),this.backgroundBlurriness=A.backgroundBlurriness,this.backgroundIntensity=A.backgroundIntensity,this.backgroundRotation.copy(A.backgroundRotation),this.environmentIntensity=A.environmentIntensity,this.environmentRotation.copy(A.environmentRotation),A.overrideMaterial!==null&&(this.overrideMaterial=A.overrideMaterial.clone()),this.matrixAutoUpdate=A.matrixAutoUpdate,this}toJSON(A){const e=super.toJSON(A);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class iu extends ig{constructor(A=null,e=1,g=1,i,I,C,o,a,Q=$e,n=$e,s,B){super(null,C,o,a,Q,n,i,I,s,B),this.isDataTexture=!0,this.image={data:A,width:e,height:g},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Qs=new J,Iu=new J,Cu=new YA;class Gi{constructor(A=new J(1,0,0),e=0){this.isPlane=!0,this.normal=A,this.constant=e}set(A,e){return this.normal.copy(A),this.constant=e,this}setComponents(A,e,g,i){return this.normal.set(A,e,g),this.constant=i,this}setFromNormalAndCoplanarPoint(A,e){return this.normal.copy(A),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(A,e,g){const i=Qs.subVectors(g,e).cross(Iu.subVectors(A,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,A),this}copy(A){return this.normal.copy(A.normal),this.constant=A.constant,this}normalize(){const A=1/this.normal.length();return this.normal.multiplyScalar(A),this.constant*=A,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(A){return this.normal.dot(A)+this.constant}distanceToSphere(A){return this.distanceToPoint(A.center)-A.radius}projectPoint(A,e){return e.copy(A).addScaledVector(this.normal,-this.distanceToPoint(A))}intersectLine(A,e){const g=A.delta(Qs),i=this.normal.dot(g);if(i===0)return this.distanceToPoint(A.start)===0?e.copy(A.start):null;const I=-(A.start.dot(this.normal)+this.constant)/i;return I<0||I>1?null:e.copy(A.start).addScaledVector(g,I)}intersectsLine(A){const e=this.distanceToPoint(A.start),g=this.distanceToPoint(A.end);return e<0&&g>0||g<0&&e>0}intersectsBox(A){return A.intersectsPlane(this)}intersectsSphere(A){return A.intersectsPlane(this)}coplanarPoint(A){return A.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(A,e){const g=e||Cu.getNormalMatrix(A),i=this.coplanarPoint(Qs).applyMatrix4(A),I=this.normal.applyMatrix3(g).normalize();return this.constant=-i.dot(I),this}translate(A){return this.constant-=A.dot(this.normal),this}equals(A){return A.normal.equals(this.normal)&&A.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Mi=new Vn,ou=new Be(.5,.5),Yo=new J;class K0{constructor(A=new Gi,e=new Gi,g=new Gi,i=new Gi,I=new Gi,C=new Gi){this.planes=[A,e,g,i,I,C]}set(A,e,g,i,I,C){const o=this.planes;return o[0].copy(A),o[1].copy(e),o[2].copy(g),o[3].copy(i),o[4].copy(I),o[5].copy(C),this}copy(A){const e=this.planes;for(let g=0;g<6;g++)e[g].copy(A.planes[g]);return this}setFromProjectionMatrix(A,e=nt,g=!1){const i=this.planes,I=A.elements,C=I[0],o=I[1],a=I[2],Q=I[3],n=I[4],s=I[5],B=I[6],E=I[7],d=I[8],c=I[9],h=I[10],r=I[11],f=I[12],_=I[13],l=I[14],D=I[15];if(i[0].setComponents(Q-C,E-n,r-d,D-f).normalize(),i[1].setComponents(Q+C,E+n,r+d,D+f).normalize(),i[2].setComponents(Q+o,E+s,r+c,D+_).normalize(),i[3].setComponents(Q-o,E-s,r-c,D-_).normalize(),g)i[4].setComponents(a,B,h,l).normalize(),i[5].setComponents(Q-a,E-B,r-h,D-l).normalize();else if(i[4].setComponents(Q-a,E-B,r-h,D-l).normalize(),e===nt)i[5].setComponents(Q+a,E+B,r+h,D+l).normalize();else if(e===uo)i[5].setComponents(a,B,h,l).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(A){if(A.boundingSphere!==void 0)A.boundingSphere===null&&A.computeBoundingSphere(),Mi.copy(A.boundingSphere).applyMatrix4(A.matrixWorld);else{const e=A.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Mi.copy(e.boundingSphere).applyMatrix4(A.matrixWorld)}return this.intersectsSphere(Mi)}intersectsSprite(A){Mi.center.set(0,0,0);const e=ou.distanceTo(A.center);return Mi.radius=.7071067811865476+e,Mi.applyMatrix4(A.matrixWorld),this.intersectsSphere(Mi)}intersectsSphere(A){const e=this.planes,g=A.center,i=-A.radius;for(let I=0;I<6;I++)if(e[I].distanceToPoint(g)<i)return!1;return!0}intersectsBox(A){const e=this.planes;for(let g=0;g<6;g++){const i=e[g];if(Yo.x=i.normal.x>0?A.max.x:A.min.x,Yo.y=i.normal.y>0?A.max.y:A.min.y,Yo.z=i.normal.z>0?A.max.z:A.min.z,i.distanceToPoint(Yo)<0)return!1}return!0}containsPoint(A){const e=this.planes;for(let g=0;g<6;g++)if(e[g].distanceToPoint(A)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class dC extends ig{constructor(A,e,g=at,i,I,C,o=$e,a=$e,Q,n=Gt,s=1){if(n!==Gt&&n!==Ni)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const B={width:A,height:e,depth:s};super(B,i,I,C,o,a,n,g,Q),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(A){return super.copy(A),this.source=new Tn(Object.assign({},A.image)),this.compareFunction=A.compareFunction,this}toJSON(A){const e=super.toJSON(A);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class au extends dC{constructor(A,e=at,g=yi,i,I,C=$e,o=$e,a,Q=Gt){const n={width:A,height:A,depth:1},s=[n,n,n,n,n,n];super(A,A,e,g,i,I,C,o,a,Q),this.image=s,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(A){this.image=A}}class v0 extends ig{constructor(A=null){super(),this.sourceTexture=A,this.isExternalTexture=!0}copy(A){return super.copy(A),this.sourceTexture=A.sourceTexture,this}}class ns extends Wg{constructor(A=[],e=[],g=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:A,indices:e,radius:g,detail:i};const I=[],C=[];o(i),Q(g),n(),this.setAttribute("position",new Ig(I,3)),this.setAttribute("normal",new Ig(I.slice(),3)),this.setAttribute("uv",new Ig(C,2)),i===0?this.computeVertexNormals():this.normalizeNormals();function o(f){const _=new J,l=new J,D=new J;for(let p=0;p<e.length;p+=3)E(e[p+0],_),E(e[p+1],l),E(e[p+2],D),a(_,l,D,f)}function a(f,_,l,D){const p=D+1,y=[];for(let k=0;k<=p;k++){y[k]=[];const x=f.clone().lerp(l,k/p),w=_.clone().lerp(l,k/p),N=p-k;for(let U=0;U<=N;U++)U===0&&k===p?y[k][U]=x:y[k][U]=x.clone().lerp(w,U/N)}for(let k=0;k<p;k++)for(let x=0;x<2*(p-k)-1;x++){const w=Math.floor(x/2);x%2===0?(B(y[k][w+1]),B(y[k+1][w]),B(y[k][w])):(B(y[k][w+1]),B(y[k+1][w+1]),B(y[k+1][w]))}}function Q(f){const _=new J;for(let l=0;l<I.length;l+=3)_.x=I[l+0],_.y=I[l+1],_.z=I[l+2],_.normalize().multiplyScalar(f),I[l+0]=_.x,I[l+1]=_.y,I[l+2]=_.z}function n(){const f=new J;for(let _=0;_<I.length;_+=3){f.x=I[_+0],f.y=I[_+1],f.z=I[_+2];const l=h(f)/2/Math.PI+.5,D=r(f)/Math.PI+.5;C.push(l,1-D)}d(),s()}function s(){for(let f=0;f<C.length;f+=6){const _=C[f+0],l=C[f+2],D=C[f+4],p=Math.max(_,l,D),y=Math.min(_,l,D);p>.9&&y<.1&&(_<.2&&(C[f+0]+=1),l<.2&&(C[f+2]+=1),D<.2&&(C[f+4]+=1))}}function B(f){I.push(f.x,f.y,f.z)}function E(f,_){const l=f*3;_.x=A[l+0],_.y=A[l+1],_.z=A[l+2]}function d(){const f=new J,_=new J,l=new J,D=new J,p=new Be,y=new Be,k=new Be;for(let x=0,w=0;x<I.length;x+=9,w+=6){f.set(I[x+0],I[x+1],I[x+2]),_.set(I[x+3],I[x+4],I[x+5]),l.set(I[x+6],I[x+7],I[x+8]),p.set(C[w+0],C[w+1]),y.set(C[w+2],C[w+3]),k.set(C[w+4],C[w+5]),D.copy(f).add(_).add(l).divideScalar(3);const N=h(D);c(p,w+0,f,N),c(y,w+2,_,N),c(k,w+4,l,N)}}function c(f,_,l,D){D<0&&f.x===1&&(C[_]=f.x-1),l.x===0&&l.z===0&&(C[_]=D/2/Math.PI+.5)}function h(f){return Math.atan2(f.z,-f.x)}function r(f){return Math.atan2(-f.y,Math.sqrt(f.x*f.x+f.z*f.z))}}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new ns(A.vertices,A.indices,A.radius,A.detail)}}class ss extends ns{constructor(A=1,e=0){const g=(1+Math.sqrt(5))/2,i=[-1,g,0,1,g,0,-1,-g,0,1,-g,0,0,-1,g,0,1,g,0,-1,-g,0,1,-g,g,0,-1,g,0,1,-g,0,-1,-g,0,1],I=[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(i,I,A,e),this.type="IcosahedronGeometry",this.parameters={radius:A,detail:e}}static fromJSON(A){return new ss(A.radius,A.detail)}}class To extends Wg{constructor(A=1,e=1,g=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:A,height:e,widthSegments:g,heightSegments:i};const I=A/2,C=e/2,o=Math.floor(g),a=Math.floor(i),Q=o+1,n=a+1,s=A/o,B=e/a,E=[],d=[],c=[],h=[];for(let r=0;r<n;r++){const f=r*B-C;for(let _=0;_<Q;_++){const l=_*s-I;d.push(l,-f,0),c.push(0,0,1),h.push(_/o),h.push(1-r/a)}}for(let r=0;r<a;r++)for(let f=0;f<o;f++){const _=f+Q*r,l=f+Q*(r+1),D=f+1+Q*(r+1),p=f+1+Q*r;E.push(_,l,p),E.push(l,D,p)}this.setIndex(E),this.setAttribute("position",new Ig(d,3)),this.setAttribute("normal",new Ig(c,3)),this.setAttribute("uv",new Ig(h,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new To(A.width,A.height,A.widthSegments,A.heightSegments)}}class Bs extends Wg{constructor(A=1,e=32,g=16,i=0,I=Math.PI*2,C=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:A,widthSegments:e,heightSegments:g,phiStart:i,phiLength:I,thetaStart:C,thetaLength:o},e=Math.max(3,Math.floor(e)),g=Math.max(2,Math.floor(g));const a=Math.min(C+o,Math.PI);let Q=0;const n=[],s=new J,B=new J,E=[],d=[],c=[],h=[];for(let r=0;r<=g;r++){const f=[],_=r/g;let l=0;r===0&&C===0?l=.5/e:r===g&&a===Math.PI&&(l=-.5/e);for(let D=0;D<=e;D++){const p=D/e;s.x=-A*Math.cos(i+p*I)*Math.sin(C+_*o),s.y=A*Math.cos(C+_*o),s.z=A*Math.sin(i+p*I)*Math.sin(C+_*o),d.push(s.x,s.y,s.z),B.copy(s).normalize(),c.push(B.x,B.y,B.z),h.push(p+l,1-_),f.push(Q++)}n.push(f)}for(let r=0;r<g;r++)for(let f=0;f<e;f++){const _=n[r][f+1],l=n[r][f],D=n[r+1][f],p=n[r+1][f+1];(r!==0||C>0)&&E.push(_,l,p),(r!==g-1||a<Math.PI)&&E.push(l,D,p)}this.setIndex(E),this.setAttribute("position",new Ig(d,3)),this.setAttribute("normal",new Ig(c,3)),this.setAttribute("uv",new Ig(h,2))}copy(A){return super.copy(A),this.parameters=Object.assign({},A.parameters),this}static fromJSON(A){return new Bs(A.radius,A.widthSegments,A.heightSegments,A.phiStart,A.phiLength,A.thetaStart,A.thetaLength)}}class Qu extends Gg{constructor(A){super(A),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class nu extends ko{constructor(A){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=uf,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(A)}copy(A){return super.copy(A),this.depthPacking=A.depthPacking,this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this}}class su extends ko{constructor(A){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(A)}copy(A){return super.copy(A),this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this}}class J0 extends G0{constructor(A=-1,e=1,g=1,i=-1,I=.1,C=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=A,this.right=e,this.top=g,this.bottom=i,this.near=I,this.far=C,this.updateProjectionMatrix()}copy(A,e){return super.copy(A,e),this.left=A.left,this.right=A.right,this.top=A.top,this.bottom=A.bottom,this.near=A.near,this.far=A.far,this.zoom=A.zoom,this.view=A.view===null?null:Object.assign({},A.view),this}setViewOffset(A,e,g,i,I,C){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=A,this.view.fullHeight=e,this.view.offsetX=g,this.view.offsetY=i,this.view.width=I,this.view.height=C,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const A=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),g=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let I=g-A,C=g+A,o=i+e,a=i-e;if(this.view!==null&&this.view.enabled){const Q=(this.right-this.left)/this.view.fullWidth/this.zoom,n=(this.top-this.bottom)/this.view.fullHeight/this.zoom;I+=Q*this.view.offsetX,C=I+Q*this.view.width,o-=n*this.view.offsetY,a=o-n*this.view.height}this.projectionMatrix.makeOrthographic(I,C,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){const e=super.toJSON(A);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}}class Bu extends Mg{constructor(A=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=A}}class Eu{constructor(A=!0){this.autoStart=A,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 A=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=performance.now();A=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=A}return A}}function Y0(t,A,e,g){const i=ru(g);switch(e){case t0:return t*A;case I0:return t*A/i.components*i.byteLength;case $Q:return t*A/i.components*i.byteLength;case nI:return t*A*2/i.components*i.byteLength;case An:return t*A*2/i.components*i.byteLength;case i0:return t*A*3/i.components*i.byteLength;case Hg:return t*A*4/i.components*i.byteLength;case en:return t*A*4/i.components*i.byteLength;case co:case ho:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*8;case xo:case lo:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case tn:case Cn:return Math.max(t,16)*Math.max(A,8)/4;case gn:case In:return Math.max(t,8)*Math.max(A,8)/2;case on:case an:case nn:case sn:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*8;case Qn:case Bn:case En:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case rn:return Math.floor((t+3)/4)*Math.floor((A+3)/4)*16;case cn:return Math.floor((t+4)/5)*Math.floor((A+3)/4)*16;case hn:return Math.floor((t+4)/5)*Math.floor((A+4)/5)*16;case dn:return Math.floor((t+5)/6)*Math.floor((A+4)/5)*16;case xn:return Math.floor((t+5)/6)*Math.floor((A+5)/6)*16;case ln:return Math.floor((t+7)/8)*Math.floor((A+4)/5)*16;case fn:return Math.floor((t+7)/8)*Math.floor((A+5)/6)*16;case un:return Math.floor((t+7)/8)*Math.floor((A+7)/8)*16;case Dn:return Math.floor((t+9)/10)*Math.floor((A+4)/5)*16;case _n:return Math.floor((t+9)/10)*Math.floor((A+5)/6)*16;case wn:return Math.floor((t+9)/10)*Math.floor((A+7)/8)*16;case pn:return Math.floor((t+9)/10)*Math.floor((A+9)/10)*16;case mn:return Math.floor((t+11)/12)*Math.floor((A+9)/10)*16;case yn:return Math.floor((t+11)/12)*Math.floor((A+11)/12)*16;case bn:case Nn:case Sn:return Math.ceil(t/4)*Math.ceil(A/4)*16;case kn:case Rn:return Math.ceil(t/4)*Math.ceil(A/4)*8;case Gn:case Mn:return Math.ceil(t/4)*Math.ceil(A/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function ru(t){switch(t){case Sg:case $r:return{byteLength:1,components:1};case IC:case A0:case Rt:return{byteLength:2,components:1};case ZQ:case zQ:return{byteLength:2,components:4};case at:case XQ:case Qt:return{byteLength:4,components:1};case e0:case g0:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:MQ}})),typeof window<"u"&&(window.__THREE__?LA("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=MQ);/**
|
|
191
191
|
* @license
|
|
192
192
|
* Copyright 2010-2025 Three.js Authors
|
|
193
193
|
* SPDX-License-Identifier: MIT
|
|
@@ -3756,7 +3756,7 @@ void main() {
|
|
|
3756
3756
|
#include <tonemapping_fragment>
|
|
3757
3757
|
#include <colorspace_fragment>
|
|
3758
3758
|
#include <fog_fragment>
|
|
3759
|
-
}`},dA={common:{diffuse:{value:new Ie(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new YA},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new YA}},envmap:{envMap:{value:null},envMapRotation:{value:new YA},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 YA}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new YA}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new YA},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new YA},normalScale:{value:new Be(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new YA},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new YA}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new YA}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new YA}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ie(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 Ie(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0},uvTransform:{value:new YA}},sprite:{diffuse:{value:new Ie(16777215)},opacity:{value:1},center:{value:new Be(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new YA},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0}}},Et={basic:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.fog]),vertexShader:qA.meshbasic_vert,fragmentShader:qA.meshbasic_frag},lambert:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)}}]),vertexShader:qA.meshlambert_vert,fragmentShader:qA.meshlambert_frag},phong:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)},specular:{value:new Ie(1118481)},shininess:{value:30}}]),vertexShader:qA.meshphong_vert,fragmentShader:qA.meshphong_frag},standard:{uniforms:Cg([dA.common,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.roughnessmap,dA.metalnessmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:qA.meshphysical_vert,fragmentShader:qA.meshphysical_frag},toon:{uniforms:Cg([dA.common,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.gradientmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)}}]),vertexShader:qA.meshtoon_vert,fragmentShader:qA.meshtoon_frag},matcap:{uniforms:Cg([dA.common,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,{matcap:{value:null}}]),vertexShader:qA.meshmatcap_vert,fragmentShader:qA.meshmatcap_frag},points:{uniforms:Cg([dA.points,dA.fog]),vertexShader:qA.points_vert,fragmentShader:qA.points_frag},dashed:{uniforms:Cg([dA.common,dA.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:qA.linedashed_vert,fragmentShader:qA.linedashed_frag},depth:{uniforms:Cg([dA.common,dA.displacementmap]),vertexShader:qA.depth_vert,fragmentShader:qA.depth_frag},normal:{uniforms:Cg([dA.common,dA.bumpmap,dA.normalmap,dA.displacementmap,{opacity:{value:1}}]),vertexShader:qA.meshnormal_vert,fragmentShader:qA.meshnormal_frag},sprite:{uniforms:Cg([dA.sprite,dA.fog]),vertexShader:qA.sprite_vert,fragmentShader:qA.sprite_frag},background:{uniforms:{uvTransform:{value:new YA},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:qA.background_vert,fragmentShader:qA.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new YA}},vertexShader:qA.backgroundCube_vert,fragmentShader:qA.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:qA.cube_vert,fragmentShader:qA.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:qA.equirect_vert,fragmentShader:qA.equirect_frag},distance:{uniforms:Cg([dA.common,dA.displacementmap,{referencePosition:{value:new J},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:qA.distance_vert,fragmentShader:qA.distance_frag},shadow:{uniforms:Cg([dA.lights,dA.fog,{color:{value:new Ie(0)},opacity:{value:1}}]),vertexShader:qA.shadow_vert,fragmentShader:qA.shadow_frag}};Et.physical={uniforms:Cg([Et.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new YA},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new YA},clearcoatNormalScale:{value:new Be(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new YA},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new YA},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new YA},sheen:{value:0},sheenColor:{value:new Ie(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new YA},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new YA},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new YA},transmissionSamplerSize:{value:new Be},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new YA},attenuationDistance:{value:0},attenuationColor:{value:new Ie(0)},specularColor:{value:new Ie(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new YA},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new YA},anisotropyVector:{value:new Be},anisotropyMap:{value:null},anisotropyMapTransform:{value:new YA}}]),vertexShader:qA.meshphysical_vert,fragmentShader:qA.meshphysical_frag};const qo={r:0,b:0,g:0},Mi=new Lt,c_=new Ye;function h_(t,A,e,g,i,I,C){const o=new Ie(0);let a=I===!0?0:1,Q,n,s=null,B=0,E=null;function d(_){let l=_.isScene===!0?_.background:null;return l&&l.isTexture&&(l=(_.backgroundBlurriness>0?e:A).get(l)),l}function c(_){let l=!1;const D=d(_);D===null?r(o,a):D&&D.isColor&&(r(D,1),l=!0);const p=t.xr.getEnvironmentBlendMode();p==="additive"?g.buffers.color.setClear(0,0,0,1,C):p==="alpha-blend"&&g.buffers.color.setClear(0,0,0,0,C),(t.autoClear||l)&&(g.buffers.depth.setTest(!0),g.buffers.depth.setMask(!0),g.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function h(_,l){const D=d(l);D&&(D.isCubeTexture||D.mapping===Eo)?(n===void 0&&(n=new Xg(new hC(1,1,1),new Gg({name:"BackgroundCubeMaterial",uniforms:pI(Et.backgroundCube.uniforms),vertexShader:Et.backgroundCube.vertexShader,fragmentShader:Et.backgroundCube.fragmentShader,side:tg,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),n.geometry.deleteAttribute("normal"),n.geometry.deleteAttribute("uv"),n.onBeforeRender=function(p,y,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(n.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(n)),Mi.copy(l.backgroundRotation),Mi.x*=-1,Mi.y*=-1,Mi.z*=-1,D.isCubeTexture&&D.isRenderTargetTexture===!1&&(Mi.y*=-1,Mi.z*=-1),n.material.uniforms.envMap.value=D,n.material.uniforms.flipEnvMap.value=D.isCubeTexture&&D.isRenderTargetTexture===!1?-1:1,n.material.uniforms.backgroundBlurriness.value=l.backgroundBlurriness,n.material.uniforms.backgroundIntensity.value=l.backgroundIntensity,n.material.uniforms.backgroundRotation.value.setFromMatrix4(c_.makeRotationFromEuler(Mi)),n.material.toneMapped=Ce.getTransfer(D.colorSpace)!==re,(s!==D||B!==D.version||E!==t.toneMapping)&&(n.material.needsUpdate=!0,s=D,B=D.version,E=t.toneMapping),n.layers.enableAll(),_.unshift(n,n.geometry,n.material,0,0,null)):D&&D.isTexture&&(Q===void 0&&(Q=new Xg(new To(2,2),new Gg({name:"BackgroundMaterial",uniforms:pI(Et.background.uniforms),vertexShader:Et.background.vertexShader,fragmentShader:Et.background.fragmentShader,side:bt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),Q.geometry.deleteAttribute("normal"),Object.defineProperty(Q.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(Q)),Q.material.uniforms.t2D.value=D,Q.material.uniforms.backgroundIntensity.value=l.backgroundIntensity,Q.material.toneMapped=Ce.getTransfer(D.colorSpace)!==re,D.matrixAutoUpdate===!0&&D.updateMatrix(),Q.material.uniforms.uvTransform.value.copy(D.matrix),(s!==D||B!==D.version||E!==t.toneMapping)&&(Q.material.needsUpdate=!0,s=D,B=D.version,E=t.toneMapping),Q.layers.enableAll(),_.unshift(Q,Q.geometry,Q.material,0,0,null))}function r(_,l){_.getRGB(qo,R0(t)),g.buffers.color.setClear(qo.r,qo.g,qo.b,l,C)}function f(){n!==void 0&&(n.geometry.dispose(),n.material.dispose(),n=void 0),Q!==void 0&&(Q.geometry.dispose(),Q.material.dispose(),Q=void 0)}return{getClearColor:function(){return o},setClearColor:function(_,l=1){o.set(_),a=l,r(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(_){a=_,r(o,a)},render:c,addToRenderList:h,dispose:f}}function d_(t,A){const e=t.getParameter(t.MAX_VERTEX_ATTRIBS),g={},i=B(null);let I=i,C=!1;function o(w,N,U,K,P){let j=!1;const H=s(K,U,N);I!==H&&(I=H,Q(I.object)),j=E(w,K,U,P),j&&d(w,K,U,P),P!==null&&A.update(P,t.ELEMENT_ARRAY_BUFFER),(j||C)&&(C=!1,l(w,N,U,K),P!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,A.get(P).buffer))}function a(){return t.createVertexArray()}function Q(w){return t.bindVertexArray(w)}function n(w){return t.deleteVertexArray(w)}function s(w,N,U){const K=U.wireframe===!0;let P=g[w.id];P===void 0&&(P={},g[w.id]=P);let j=P[N.id];j===void 0&&(j={},P[N.id]=j);let H=j[K];return H===void 0&&(H=B(a()),j[K]=H),H}function B(w){const N=[],U=[],K=[];for(let P=0;P<e;P++)N[P]=0,U[P]=0,K[P]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:N,enabledAttributes:U,attributeDivisors:K,object:w,attributes:{},index:null}}function E(w,N,U,K){const P=I.attributes,j=N.attributes;let H=0;const O=U.getAttributes();for(const z in O)if(O[z].location>=0){const sA=P[z];let fA=j[z];if(fA===void 0&&(z==="instanceMatrix"&&w.instanceMatrix&&(fA=w.instanceMatrix),z==="instanceColor"&&w.instanceColor&&(fA=w.instanceColor)),sA===void 0||sA.attribute!==fA||fA&&sA.data!==fA.data)return!0;H++}return I.attributesNum!==H||I.index!==K}function d(w,N,U,K){const P={},j=N.attributes;let H=0;const O=U.getAttributes();for(const z in O)if(O[z].location>=0){let sA=j[z];sA===void 0&&(z==="instanceMatrix"&&w.instanceMatrix&&(sA=w.instanceMatrix),z==="instanceColor"&&w.instanceColor&&(sA=w.instanceColor));const fA={};fA.attribute=sA,sA&&sA.data&&(fA.data=sA.data),P[z]=fA,H++}I.attributes=P,I.attributesNum=H,I.index=K}function c(){const w=I.newAttributes;for(let N=0,U=w.length;N<U;N++)w[N]=0}function h(w){r(w,0)}function r(w,N){const U=I.newAttributes,K=I.enabledAttributes,P=I.attributeDivisors;U[w]=1,K[w]===0&&(t.enableVertexAttribArray(w),K[w]=1),P[w]!==N&&(t.vertexAttribDivisor(w,N),P[w]=N)}function f(){const w=I.newAttributes,N=I.enabledAttributes;for(let U=0,K=N.length;U<K;U++)N[U]!==w[U]&&(t.disableVertexAttribArray(U),N[U]=0)}function _(w,N,U,K,P,j,H){H===!0?t.vertexAttribIPointer(w,N,U,P,j):t.vertexAttribPointer(w,N,U,K,P,j)}function l(w,N,U,K){c();const P=K.attributes,j=U.getAttributes(),H=N.defaultAttributeValues;for(const O in j){const z=j[O];if(z.location>=0){let xA=P[O];if(xA===void 0&&(O==="instanceMatrix"&&w.instanceMatrix&&(xA=w.instanceMatrix),O==="instanceColor"&&w.instanceColor&&(xA=w.instanceColor)),xA!==void 0){const sA=xA.normalized,fA=xA.itemSize,JA=A.get(xA);if(JA===void 0)continue;const vA=JA.buffer,be=JA.type,le=JA.bytesPerElement,Z=be===t.INT||be===t.UNSIGNED_INT||xA.gpuType===XQ;if(xA.isInterleavedBufferAttribute){const iA=xA.data,wA=iA.stride,TA=xA.offset;if(iA.isInstancedInterleavedBuffer){for(let yA=0;yA<z.locationSize;yA++)r(z.location+yA,iA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=iA.meshPerAttribute*iA.count)}else for(let yA=0;yA<z.locationSize;yA++)h(z.location+yA);t.bindBuffer(t.ARRAY_BUFFER,vA);for(let yA=0;yA<z.locationSize;yA++)_(z.location+yA,fA/z.locationSize,be,sA,wA*le,(TA+fA/z.locationSize*yA)*le,Z)}else{if(xA.isInstancedBufferAttribute){for(let iA=0;iA<z.locationSize;iA++)r(z.location+iA,xA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=xA.meshPerAttribute*xA.count)}else for(let iA=0;iA<z.locationSize;iA++)h(z.location+iA);t.bindBuffer(t.ARRAY_BUFFER,vA);for(let iA=0;iA<z.locationSize;iA++)_(z.location+iA,fA/z.locationSize,be,sA,fA*le,fA/z.locationSize*iA*le,Z)}}else if(H!==void 0){const sA=H[O];if(sA!==void 0)switch(sA.length){case 2:t.vertexAttrib2fv(z.location,sA);break;case 3:t.vertexAttrib3fv(z.location,sA);break;case 4:t.vertexAttrib4fv(z.location,sA);break;default:t.vertexAttrib1fv(z.location,sA)}}}}f()}function D(){k();for(const w in g){const N=g[w];for(const U in N){const K=N[U];for(const P in K)n(K[P].object),delete K[P];delete N[U]}delete g[w]}}function p(w){if(g[w.id]===void 0)return;const N=g[w.id];for(const U in N){const K=N[U];for(const P in K)n(K[P].object),delete K[P];delete N[U]}delete g[w.id]}function y(w){for(const N in g){const U=g[N];if(U[w.id]===void 0)continue;const K=U[w.id];for(const P in K)n(K[P].object),delete K[P];delete U[w.id]}}function k(){x(),C=!0,I!==i&&(I=i,Q(I.object))}function x(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:o,reset:k,resetDefaultState:x,dispose:D,releaseStatesOfGeometry:p,releaseStatesOfProgram:y,initAttributes:c,enableAttribute:h,disableUnusedAttributes:f}}function x_(t,A,e){let g;function i(Q){g=Q}function I(Q,n){t.drawArrays(g,Q,n),e.update(n,g,1)}function C(Q,n,s){s!==0&&(t.drawArraysInstanced(g,Q,n,s),e.update(n,g,s))}function o(Q,n,s){if(s===0)return;A.get("WEBGL_multi_draw").multiDrawArraysWEBGL(g,Q,0,n,0,s);let E=0;for(let d=0;d<s;d++)E+=n[d];e.update(E,g,1)}function a(Q,n,s,B){if(s===0)return;const E=A.get("WEBGL_multi_draw");if(E===null)for(let d=0;d<Q.length;d++)C(Q[d],n[d],B[d]);else{E.multiDrawArraysInstancedWEBGL(g,Q,0,n,0,B,0,s);let d=0;for(let c=0;c<s;c++)d+=n[c]*B[c];e.update(d,g,1)}}this.setMode=i,this.render=I,this.renderInstances=C,this.renderMultiDraw=o,this.renderMultiDrawInstances=a}function l_(t,A,e,g){let i;function I(){if(i!==void 0)return i;if(A.has("EXT_texture_filter_anisotropic")===!0){const y=A.get("EXT_texture_filter_anisotropic");i=t.getParameter(y.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function C(y){return!(y!==Hg&&g.convert(y)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(y){const k=y===Rt&&(A.has("EXT_color_buffer_half_float")||A.has("EXT_color_buffer_float"));return!(y!==Sg&&g.convert(y)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&y!==Qt&&!k)}function a(y){if(y==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";y="mediump"}return y==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let Q=e.precision!==void 0?e.precision:"highp";const n=a(Q);n!==Q&&(LA("WebGLRenderer:",Q,"not supported, using",n,"instead."),Q=n);const s=e.logarithmicDepthBuffer===!0,B=e.reversedDepthBuffer===!0&&A.has("EXT_clip_control"),E=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),d=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),c=t.getParameter(t.MAX_TEXTURE_SIZE),h=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),r=t.getParameter(t.MAX_VERTEX_ATTRIBS),f=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),_=t.getParameter(t.MAX_VARYING_VECTORS),l=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),D=t.getParameter(t.MAX_SAMPLES),p=t.getParameter(t.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:I,getMaxPrecision:a,textureFormatReadable:C,textureTypeReadable:o,precision:Q,logarithmicDepthBuffer:s,reversedDepthBuffer:B,maxTextures:E,maxVertexTextures:d,maxTextureSize:c,maxCubemapSize:h,maxAttributes:r,maxVertexUniforms:f,maxVaryings:_,maxFragmentUniforms:l,maxSamples:D,samples:p}}function f_(t){const A=this;let e=null,g=0,i=!1,I=!1;const C=new Ri,o=new YA,a={value:null,needsUpdate:!1};this.uniform=a,this.numPlanes=0,this.numIntersection=0,this.init=function(s,B){const E=s.length!==0||B||g!==0||i;return i=B,g=s.length,E},this.beginShadows=function(){I=!0,n(null)},this.endShadows=function(){I=!1},this.setGlobalState=function(s,B){e=n(s,B,0)},this.setState=function(s,B,E){const d=s.clippingPlanes,c=s.clipIntersection,h=s.clipShadows,r=t.get(s);if(!i||d===null||d.length===0||I&&!h)I?n(null):Q();else{const f=I?0:g,_=f*4;let l=r.clippingState||null;a.value=l,l=n(d,B,_,E);for(let D=0;D!==_;++D)l[D]=e[D];r.clippingState=l,this.numIntersection=c?this.numPlanes:0,this.numPlanes+=f}};function Q(){a.value!==e&&(a.value=e,a.needsUpdate=g>0),A.numPlanes=g,A.numIntersection=0}function n(s,B,E,d){const c=s!==null?s.length:0;let h=null;if(c!==0){if(h=a.value,d!==!0||h===null){const r=E+c*4,f=B.matrixWorldInverse;o.getNormalMatrix(f),(h===null||h.length<r)&&(h=new Float32Array(r));for(let _=0,l=E;_!==c;++_,l+=4)C.copy(s[_]).applyMatrix4(f,o),C.normal.toArray(h,l),h[l+3]=C.constant}a.value=h,a.needsUpdate=!0}return A.numPlanes=c,A.numIntersection=0,h}}function u_(t){let A=new WeakMap;function e(C,o){return o===PQ?C.mapping=mi:o===OQ&&(C.mapping=QI),C}function g(C){if(C&&C.isTexture){const o=C.mapping;if(o===PQ||o===OQ)if(A.has(C)){const a=A.get(C).texture;return e(a,C.mapping)}else{const a=C.image;if(a&&a.height>0){const Q=new L0(a.height);return Q.fromEquirectangularTexture(t,C),A.set(C,Q),C.addEventListener("dispose",i),e(Q.texture,C.mapping)}else return null}}return C}function i(C){const o=C.target;o.removeEventListener("dispose",i);const a=A.get(o);a!==void 0&&(A.delete(o),a.dispose())}function I(){A=new WeakMap}return{get:g,dispose:I}}const si=4,q0=[.125,.215,.35,.446,.526,.582],Fi=20,D_=256,xC=new J0,H0=new Ie;let Es=null,rs=0,cs=0,hs=!1;const __=new J;class P0{constructor(A){this._renderer=A,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(A,e=0,g=.1,i=100,I={}){const{size:C=256,position:o=__}=I;Es=this._renderer.getRenderTarget(),rs=this._renderer.getActiveCubeFace(),cs=this._renderer.getActiveMipmapLevel(),hs=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(C);const a=this._allocateTargets();return a.depthBuffer=!0,this._sceneToCubeUV(A,g,i,a,o),e>0&&this._blur(a,0,0,e),this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(A,e=null){return this._fromTexture(A,e)}fromCubemap(A,e=null){return this._fromTexture(A,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=j0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=V0(),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(A){this._lodMax=Math.floor(Math.log2(A)),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 A=0;A<this._lodMeshes.length;A++)this._lodMeshes[A].geometry.dispose()}_cleanup(A){this._renderer.setRenderTarget(Es,rs,cs),this._renderer.xr.enabled=hs,A.scissorTest=!1,bI(A,0,0,A.width,A.height)}_fromTexture(A,e){A.mapping===mi||A.mapping===QI?this._setSize(A.image.length===0?16:A.image[0].width||A.image[0].image.width):this._setSize(A.image.width/4),Es=this._renderer.getRenderTarget(),rs=this._renderer.getActiveCubeFace(),cs=this._renderer.getActiveMipmapLevel(),hs=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const g=e||this._allocateTargets();return this._textureToCubeUV(A,g),this._applyPMREM(g),this._cleanup(g),g}_allocateTargets(){const A=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,g={magFilter:Ag,minFilter:Ag,generateMipmaps:!1,type:Rt,format:Hg,colorSpace:sI,depthBuffer:!1},i=O0(A,e,g);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==A||this._pingPongRenderTarget.height!==e){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=O0(A,e,g);const{_lodMax:I}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=w_(I)),this._blurMaterial=m_(I,A,e),this._ggxMaterial=p_(I,A,e)}return i}_compileMaterial(A){const e=new Xg(new Wg,A);this._renderer.compile(e,xC)}_sceneToCubeUV(A,e,g,i,I){const a=new Mg(90,1,e,g),Q=[1,-1,1,1,1,1],n=[1,1,1,-1,-1,-1],s=this._renderer,B=s.autoClear,E=s.toneMapping;s.getClearColor(H0),s.toneMapping=ot,s.autoClear=!1,s.state.buffers.depth.getReversed()&&(s.setRenderTarget(i),s.clearDepth(),s.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Xg(new hC,new m0({name:"PMREM.Background",side:tg,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let r=!1;const f=A.background;f?f.isColor&&(h.color.copy(f),A.background=null,r=!0):(h.color.copy(H0),r=!0);for(let _=0;_<6;_++){const l=_%3;l===0?(a.up.set(0,Q[_],0),a.position.set(I.x,I.y,I.z),a.lookAt(I.x+n[_],I.y,I.z)):l===1?(a.up.set(0,0,Q[_]),a.position.set(I.x,I.y,I.z),a.lookAt(I.x,I.y+n[_],I.z)):(a.up.set(0,Q[_],0),a.position.set(I.x,I.y,I.z),a.lookAt(I.x,I.y,I.z+n[_]));const D=this._cubeSize;bI(i,l*D,_>2?D:0,D,D),s.setRenderTarget(i),r&&s.render(c,a),s.render(A,a)}s.toneMapping=E,s.autoClear=B,A.background=f}_textureToCubeUV(A,e){const g=this._renderer,i=A.mapping===mi||A.mapping===QI;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=j0()),this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=V0());const I=i?this._cubemapMaterial:this._equirectMaterial,C=this._lodMeshes[0];C.material=I;const o=I.uniforms;o.envMap.value=A;const a=this._cubeSize;bI(e,0,0,3*a,2*a),g.setRenderTarget(e),g.render(C,xC)}_applyPMREM(A){const e=this._renderer,g=e.autoClear;e.autoClear=!1;const i=this._lodMeshes.length;for(let I=1;I<i;I++)this._applyGGXFilter(A,I-1,I);e.autoClear=g}_applyGGXFilter(A,e,g){const i=this._renderer,I=this._pingPongRenderTarget,C=this._ggxMaterial,o=this._lodMeshes[g];o.material=C;const a=C.uniforms,Q=g/(this._lodMeshes.length-1),n=e/(this._lodMeshes.length-1),s=Math.sqrt(Q*Q-n*n),B=0+Q*1.25,E=s*B,{_lodMax:d}=this,c=this._sizeLods[g],h=3*c*(g>d-si?g-d+si:0),r=4*(this._cubeSize-c);a.envMap.value=A.texture,a.roughness.value=E,a.mipInt.value=d-e,bI(I,h,r,3*c,2*c),i.setRenderTarget(I),i.render(o,xC),a.envMap.value=I.texture,a.roughness.value=0,a.mipInt.value=d-g,bI(A,h,r,3*c,2*c),i.setRenderTarget(A),i.render(o,xC)}_blur(A,e,g,i,I){const C=this._pingPongRenderTarget;this._halfBlur(A,C,e,g,i,"latitudinal",I),this._halfBlur(C,A,g,g,i,"longitudinal",I)}_halfBlur(A,e,g,i,I,C,o){const a=this._renderer,Q=this._blurMaterial;C!=="latitudinal"&&C!=="longitudinal"&&ae("blur direction must be either latitudinal or longitudinal!");const n=3,s=this._lodMeshes[i];s.material=Q;const B=Q.uniforms,E=this._sizeLods[g]-1,d=isFinite(I)?Math.PI/(2*E):2*Math.PI/(2*Fi-1),c=I/d,h=isFinite(I)?1+Math.floor(n*c):Fi;h>Fi&&LA(`sigmaRadians, ${I}, is too large and will clip, as it requested ${h} samples when the maximum is set to ${Fi}`);const r=[];let f=0;for(let y=0;y<Fi;++y){const k=y/c,x=Math.exp(-k*k/2);r.push(x),y===0?f+=x:y<h&&(f+=2*x)}for(let y=0;y<r.length;y++)r[y]=r[y]/f;B.envMap.value=A.texture,B.samples.value=h,B.weights.value=r,B.latitudinal.value=C==="latitudinal",o&&(B.poleAxis.value=o);const{_lodMax:_}=this;B.dTheta.value=d,B.mipInt.value=_-g;const l=this._sizeLods[i],D=3*l*(i>_-si?i-_+si:0),p=4*(this._cubeSize-l);bI(e,D,p,3*l,2*l),a.setRenderTarget(e),a.render(s,xC)}}function w_(t){const A=[],e=[],g=[];let i=t;const I=t-si+1+q0.length;for(let C=0;C<I;C++){const o=Math.pow(2,i);A.push(o);let a=1/o;C>t-si?a=q0[C-t+si-1]:C===0&&(a=0),e.push(a);const Q=1/(o-2),n=-Q,s=1+Q,B=[n,n,s,n,s,s,n,n,s,s,n,s],E=6,d=6,c=3,h=2,r=1,f=new Float32Array(c*d*E),_=new Float32Array(h*d*E),l=new Float32Array(r*d*E);for(let p=0;p<E;p++){const y=p%3*2/3-1,k=p>2?0:-1,x=[y,k,0,y+2/3,k,0,y+2/3,k+1,0,y,k,0,y+2/3,k+1,0,y,k+1,0];f.set(x,c*d*p),_.set(B,h*d*p);const w=[p,p,p,p,p,p];l.set(w,r*d*p)}const D=new Wg;D.setAttribute("position",new Bt(f,c)),D.setAttribute("uv",new Bt(_,h)),D.setAttribute("faceIndex",new Bt(l,r)),g.push(new Xg(D,null)),i>si&&i--}return{lodMeshes:g,sizeLods:A,sigmas:e}}function O0(t,A,e){const g=new st(t,A,e);return g.texture.mapping=Eo,g.texture.name="PMREM.cubeUv",g.scissorTest=!0,g}function bI(t,A,e,g,i){t.viewport.set(A,e,g,i),t.scissor.set(A,e,g,i)}function p_(t,A,e){return new Gg({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:D_,CUBEUV_TEXEL_WIDTH:1/A,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ho(),fragmentShader:`
|
|
3759
|
+
}`},dA={common:{diffuse:{value:new Ie(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new YA},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new YA}},envmap:{envMap:{value:null},envMapRotation:{value:new YA},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 YA}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new YA}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new YA},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new YA},normalScale:{value:new Be(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new YA},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new YA}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new YA}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new YA}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ie(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 Ie(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0},uvTransform:{value:new YA}},sprite:{diffuse:{value:new Ie(16777215)},opacity:{value:1},center:{value:new Be(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new YA},alphaMap:{value:null},alphaMapTransform:{value:new YA},alphaTest:{value:0}}},Et={basic:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.fog]),vertexShader:qA.meshbasic_vert,fragmentShader:qA.meshbasic_frag},lambert:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)}}]),vertexShader:qA.meshlambert_vert,fragmentShader:qA.meshlambert_frag},phong:{uniforms:Cg([dA.common,dA.specularmap,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)},specular:{value:new Ie(1118481)},shininess:{value:30}}]),vertexShader:qA.meshphong_vert,fragmentShader:qA.meshphong_frag},standard:{uniforms:Cg([dA.common,dA.envmap,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.roughnessmap,dA.metalnessmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:qA.meshphysical_vert,fragmentShader:qA.meshphysical_frag},toon:{uniforms:Cg([dA.common,dA.aomap,dA.lightmap,dA.emissivemap,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.gradientmap,dA.fog,dA.lights,{emissive:{value:new Ie(0)}}]),vertexShader:qA.meshtoon_vert,fragmentShader:qA.meshtoon_frag},matcap:{uniforms:Cg([dA.common,dA.bumpmap,dA.normalmap,dA.displacementmap,dA.fog,{matcap:{value:null}}]),vertexShader:qA.meshmatcap_vert,fragmentShader:qA.meshmatcap_frag},points:{uniforms:Cg([dA.points,dA.fog]),vertexShader:qA.points_vert,fragmentShader:qA.points_frag},dashed:{uniforms:Cg([dA.common,dA.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:qA.linedashed_vert,fragmentShader:qA.linedashed_frag},depth:{uniforms:Cg([dA.common,dA.displacementmap]),vertexShader:qA.depth_vert,fragmentShader:qA.depth_frag},normal:{uniforms:Cg([dA.common,dA.bumpmap,dA.normalmap,dA.displacementmap,{opacity:{value:1}}]),vertexShader:qA.meshnormal_vert,fragmentShader:qA.meshnormal_frag},sprite:{uniforms:Cg([dA.sprite,dA.fog]),vertexShader:qA.sprite_vert,fragmentShader:qA.sprite_frag},background:{uniforms:{uvTransform:{value:new YA},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:qA.background_vert,fragmentShader:qA.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new YA}},vertexShader:qA.backgroundCube_vert,fragmentShader:qA.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:qA.cube_vert,fragmentShader:qA.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:qA.equirect_vert,fragmentShader:qA.equirect_frag},distance:{uniforms:Cg([dA.common,dA.displacementmap,{referencePosition:{value:new J},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:qA.distance_vert,fragmentShader:qA.distance_frag},shadow:{uniforms:Cg([dA.lights,dA.fog,{color:{value:new Ie(0)},opacity:{value:1}}]),vertexShader:qA.shadow_vert,fragmentShader:qA.shadow_frag}};Et.physical={uniforms:Cg([Et.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new YA},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new YA},clearcoatNormalScale:{value:new Be(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new YA},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new YA},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new YA},sheen:{value:0},sheenColor:{value:new Ie(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new YA},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new YA},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new YA},transmissionSamplerSize:{value:new Be},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new YA},attenuationDistance:{value:0},attenuationColor:{value:new Ie(0)},specularColor:{value:new Ie(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new YA},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new YA},anisotropyVector:{value:new Be},anisotropyMap:{value:null},anisotropyMapTransform:{value:new YA}}]),vertexShader:qA.meshphysical_vert,fragmentShader:qA.meshphysical_frag};const qo={r:0,b:0,g:0},Fi=new Lt,c_=new Ye;function h_(t,A,e,g,i,I,C){const o=new Ie(0);let a=I===!0?0:1,Q,n,s=null,B=0,E=null;function d(_){let l=_.isScene===!0?_.background:null;return l&&l.isTexture&&(l=(_.backgroundBlurriness>0?e:A).get(l)),l}function c(_){let l=!1;const D=d(_);D===null?r(o,a):D&&D.isColor&&(r(D,1),l=!0);const p=t.xr.getEnvironmentBlendMode();p==="additive"?g.buffers.color.setClear(0,0,0,1,C):p==="alpha-blend"&&g.buffers.color.setClear(0,0,0,0,C),(t.autoClear||l)&&(g.buffers.depth.setTest(!0),g.buffers.depth.setMask(!0),g.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function h(_,l){const D=d(l);D&&(D.isCubeTexture||D.mapping===Eo)?(n===void 0&&(n=new Xg(new hC(1,1,1),new Gg({name:"BackgroundCubeMaterial",uniforms:pI(Et.backgroundCube.uniforms),vertexShader:Et.backgroundCube.vertexShader,fragmentShader:Et.backgroundCube.fragmentShader,side:tg,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),n.geometry.deleteAttribute("normal"),n.geometry.deleteAttribute("uv"),n.onBeforeRender=function(p,y,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(n.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(n)),Fi.copy(l.backgroundRotation),Fi.x*=-1,Fi.y*=-1,Fi.z*=-1,D.isCubeTexture&&D.isRenderTargetTexture===!1&&(Fi.y*=-1,Fi.z*=-1),n.material.uniforms.envMap.value=D,n.material.uniforms.flipEnvMap.value=D.isCubeTexture&&D.isRenderTargetTexture===!1?-1:1,n.material.uniforms.backgroundBlurriness.value=l.backgroundBlurriness,n.material.uniforms.backgroundIntensity.value=l.backgroundIntensity,n.material.uniforms.backgroundRotation.value.setFromMatrix4(c_.makeRotationFromEuler(Fi)),n.material.toneMapped=Ce.getTransfer(D.colorSpace)!==re,(s!==D||B!==D.version||E!==t.toneMapping)&&(n.material.needsUpdate=!0,s=D,B=D.version,E=t.toneMapping),n.layers.enableAll(),_.unshift(n,n.geometry,n.material,0,0,null)):D&&D.isTexture&&(Q===void 0&&(Q=new Xg(new To(2,2),new Gg({name:"BackgroundMaterial",uniforms:pI(Et.background.uniforms),vertexShader:Et.background.vertexShader,fragmentShader:Et.background.fragmentShader,side:bt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),Q.geometry.deleteAttribute("normal"),Object.defineProperty(Q.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(Q)),Q.material.uniforms.t2D.value=D,Q.material.uniforms.backgroundIntensity.value=l.backgroundIntensity,Q.material.toneMapped=Ce.getTransfer(D.colorSpace)!==re,D.matrixAutoUpdate===!0&&D.updateMatrix(),Q.material.uniforms.uvTransform.value.copy(D.matrix),(s!==D||B!==D.version||E!==t.toneMapping)&&(Q.material.needsUpdate=!0,s=D,B=D.version,E=t.toneMapping),Q.layers.enableAll(),_.unshift(Q,Q.geometry,Q.material,0,0,null))}function r(_,l){_.getRGB(qo,R0(t)),g.buffers.color.setClear(qo.r,qo.g,qo.b,l,C)}function f(){n!==void 0&&(n.geometry.dispose(),n.material.dispose(),n=void 0),Q!==void 0&&(Q.geometry.dispose(),Q.material.dispose(),Q=void 0)}return{getClearColor:function(){return o},setClearColor:function(_,l=1){o.set(_),a=l,r(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(_){a=_,r(o,a)},render:c,addToRenderList:h,dispose:f}}function d_(t,A){const e=t.getParameter(t.MAX_VERTEX_ATTRIBS),g={},i=B(null);let I=i,C=!1;function o(w,N,U,K,P){let j=!1;const H=s(K,U,N);I!==H&&(I=H,Q(I.object)),j=E(w,K,U,P),j&&d(w,K,U,P),P!==null&&A.update(P,t.ELEMENT_ARRAY_BUFFER),(j||C)&&(C=!1,l(w,N,U,K),P!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,A.get(P).buffer))}function a(){return t.createVertexArray()}function Q(w){return t.bindVertexArray(w)}function n(w){return t.deleteVertexArray(w)}function s(w,N,U){const K=U.wireframe===!0;let P=g[w.id];P===void 0&&(P={},g[w.id]=P);let j=P[N.id];j===void 0&&(j={},P[N.id]=j);let H=j[K];return H===void 0&&(H=B(a()),j[K]=H),H}function B(w){const N=[],U=[],K=[];for(let P=0;P<e;P++)N[P]=0,U[P]=0,K[P]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:N,enabledAttributes:U,attributeDivisors:K,object:w,attributes:{},index:null}}function E(w,N,U,K){const P=I.attributes,j=N.attributes;let H=0;const O=U.getAttributes();for(const z in O)if(O[z].location>=0){const sA=P[z];let fA=j[z];if(fA===void 0&&(z==="instanceMatrix"&&w.instanceMatrix&&(fA=w.instanceMatrix),z==="instanceColor"&&w.instanceColor&&(fA=w.instanceColor)),sA===void 0||sA.attribute!==fA||fA&&sA.data!==fA.data)return!0;H++}return I.attributesNum!==H||I.index!==K}function d(w,N,U,K){const P={},j=N.attributes;let H=0;const O=U.getAttributes();for(const z in O)if(O[z].location>=0){let sA=j[z];sA===void 0&&(z==="instanceMatrix"&&w.instanceMatrix&&(sA=w.instanceMatrix),z==="instanceColor"&&w.instanceColor&&(sA=w.instanceColor));const fA={};fA.attribute=sA,sA&&sA.data&&(fA.data=sA.data),P[z]=fA,H++}I.attributes=P,I.attributesNum=H,I.index=K}function c(){const w=I.newAttributes;for(let N=0,U=w.length;N<U;N++)w[N]=0}function h(w){r(w,0)}function r(w,N){const U=I.newAttributes,K=I.enabledAttributes,P=I.attributeDivisors;U[w]=1,K[w]===0&&(t.enableVertexAttribArray(w),K[w]=1),P[w]!==N&&(t.vertexAttribDivisor(w,N),P[w]=N)}function f(){const w=I.newAttributes,N=I.enabledAttributes;for(let U=0,K=N.length;U<K;U++)N[U]!==w[U]&&(t.disableVertexAttribArray(U),N[U]=0)}function _(w,N,U,K,P,j,H){H===!0?t.vertexAttribIPointer(w,N,U,P,j):t.vertexAttribPointer(w,N,U,K,P,j)}function l(w,N,U,K){c();const P=K.attributes,j=U.getAttributes(),H=N.defaultAttributeValues;for(const O in j){const z=j[O];if(z.location>=0){let xA=P[O];if(xA===void 0&&(O==="instanceMatrix"&&w.instanceMatrix&&(xA=w.instanceMatrix),O==="instanceColor"&&w.instanceColor&&(xA=w.instanceColor)),xA!==void 0){const sA=xA.normalized,fA=xA.itemSize,JA=A.get(xA);if(JA===void 0)continue;const vA=JA.buffer,be=JA.type,le=JA.bytesPerElement,Z=be===t.INT||be===t.UNSIGNED_INT||xA.gpuType===XQ;if(xA.isInterleavedBufferAttribute){const iA=xA.data,wA=iA.stride,TA=xA.offset;if(iA.isInstancedInterleavedBuffer){for(let yA=0;yA<z.locationSize;yA++)r(z.location+yA,iA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=iA.meshPerAttribute*iA.count)}else for(let yA=0;yA<z.locationSize;yA++)h(z.location+yA);t.bindBuffer(t.ARRAY_BUFFER,vA);for(let yA=0;yA<z.locationSize;yA++)_(z.location+yA,fA/z.locationSize,be,sA,wA*le,(TA+fA/z.locationSize*yA)*le,Z)}else{if(xA.isInstancedBufferAttribute){for(let iA=0;iA<z.locationSize;iA++)r(z.location+iA,xA.meshPerAttribute);w.isInstancedMesh!==!0&&K._maxInstanceCount===void 0&&(K._maxInstanceCount=xA.meshPerAttribute*xA.count)}else for(let iA=0;iA<z.locationSize;iA++)h(z.location+iA);t.bindBuffer(t.ARRAY_BUFFER,vA);for(let iA=0;iA<z.locationSize;iA++)_(z.location+iA,fA/z.locationSize,be,sA,fA*le,fA/z.locationSize*iA*le,Z)}}else if(H!==void 0){const sA=H[O];if(sA!==void 0)switch(sA.length){case 2:t.vertexAttrib2fv(z.location,sA);break;case 3:t.vertexAttrib3fv(z.location,sA);break;case 4:t.vertexAttrib4fv(z.location,sA);break;default:t.vertexAttrib1fv(z.location,sA)}}}}f()}function D(){k();for(const w in g){const N=g[w];for(const U in N){const K=N[U];for(const P in K)n(K[P].object),delete K[P];delete N[U]}delete g[w]}}function p(w){if(g[w.id]===void 0)return;const N=g[w.id];for(const U in N){const K=N[U];for(const P in K)n(K[P].object),delete K[P];delete N[U]}delete g[w.id]}function y(w){for(const N in g){const U=g[N];if(U[w.id]===void 0)continue;const K=U[w.id];for(const P in K)n(K[P].object),delete K[P];delete U[w.id]}}function k(){x(),C=!0,I!==i&&(I=i,Q(I.object))}function x(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:o,reset:k,resetDefaultState:x,dispose:D,releaseStatesOfGeometry:p,releaseStatesOfProgram:y,initAttributes:c,enableAttribute:h,disableUnusedAttributes:f}}function x_(t,A,e){let g;function i(Q){g=Q}function I(Q,n){t.drawArrays(g,Q,n),e.update(n,g,1)}function C(Q,n,s){s!==0&&(t.drawArraysInstanced(g,Q,n,s),e.update(n,g,s))}function o(Q,n,s){if(s===0)return;A.get("WEBGL_multi_draw").multiDrawArraysWEBGL(g,Q,0,n,0,s);let E=0;for(let d=0;d<s;d++)E+=n[d];e.update(E,g,1)}function a(Q,n,s,B){if(s===0)return;const E=A.get("WEBGL_multi_draw");if(E===null)for(let d=0;d<Q.length;d++)C(Q[d],n[d],B[d]);else{E.multiDrawArraysInstancedWEBGL(g,Q,0,n,0,B,0,s);let d=0;for(let c=0;c<s;c++)d+=n[c]*B[c];e.update(d,g,1)}}this.setMode=i,this.render=I,this.renderInstances=C,this.renderMultiDraw=o,this.renderMultiDrawInstances=a}function l_(t,A,e,g){let i;function I(){if(i!==void 0)return i;if(A.has("EXT_texture_filter_anisotropic")===!0){const y=A.get("EXT_texture_filter_anisotropic");i=t.getParameter(y.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function C(y){return!(y!==Hg&&g.convert(y)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(y){const k=y===Rt&&(A.has("EXT_color_buffer_half_float")||A.has("EXT_color_buffer_float"));return!(y!==Sg&&g.convert(y)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&y!==Qt&&!k)}function a(y){if(y==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";y="mediump"}return y==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let Q=e.precision!==void 0?e.precision:"highp";const n=a(Q);n!==Q&&(LA("WebGLRenderer:",Q,"not supported, using",n,"instead."),Q=n);const s=e.logarithmicDepthBuffer===!0,B=e.reversedDepthBuffer===!0&&A.has("EXT_clip_control"),E=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),d=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),c=t.getParameter(t.MAX_TEXTURE_SIZE),h=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),r=t.getParameter(t.MAX_VERTEX_ATTRIBS),f=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),_=t.getParameter(t.MAX_VARYING_VECTORS),l=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),D=t.getParameter(t.MAX_SAMPLES),p=t.getParameter(t.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:I,getMaxPrecision:a,textureFormatReadable:C,textureTypeReadable:o,precision:Q,logarithmicDepthBuffer:s,reversedDepthBuffer:B,maxTextures:E,maxVertexTextures:d,maxTextureSize:c,maxCubemapSize:h,maxAttributes:r,maxVertexUniforms:f,maxVaryings:_,maxFragmentUniforms:l,maxSamples:D,samples:p}}function f_(t){const A=this;let e=null,g=0,i=!1,I=!1;const C=new Gi,o=new YA,a={value:null,needsUpdate:!1};this.uniform=a,this.numPlanes=0,this.numIntersection=0,this.init=function(s,B){const E=s.length!==0||B||g!==0||i;return i=B,g=s.length,E},this.beginShadows=function(){I=!0,n(null)},this.endShadows=function(){I=!1},this.setGlobalState=function(s,B){e=n(s,B,0)},this.setState=function(s,B,E){const d=s.clippingPlanes,c=s.clipIntersection,h=s.clipShadows,r=t.get(s);if(!i||d===null||d.length===0||I&&!h)I?n(null):Q();else{const f=I?0:g,_=f*4;let l=r.clippingState||null;a.value=l,l=n(d,B,_,E);for(let D=0;D!==_;++D)l[D]=e[D];r.clippingState=l,this.numIntersection=c?this.numPlanes:0,this.numPlanes+=f}};function Q(){a.value!==e&&(a.value=e,a.needsUpdate=g>0),A.numPlanes=g,A.numIntersection=0}function n(s,B,E,d){const c=s!==null?s.length:0;let h=null;if(c!==0){if(h=a.value,d!==!0||h===null){const r=E+c*4,f=B.matrixWorldInverse;o.getNormalMatrix(f),(h===null||h.length<r)&&(h=new Float32Array(r));for(let _=0,l=E;_!==c;++_,l+=4)C.copy(s[_]).applyMatrix4(f,o),C.normal.toArray(h,l),h[l+3]=C.constant}a.value=h,a.needsUpdate=!0}return A.numPlanes=c,A.numIntersection=0,h}}function u_(t){let A=new WeakMap;function e(C,o){return o===PQ?C.mapping=yi:o===OQ&&(C.mapping=QI),C}function g(C){if(C&&C.isTexture){const o=C.mapping;if(o===PQ||o===OQ)if(A.has(C)){const a=A.get(C).texture;return e(a,C.mapping)}else{const a=C.image;if(a&&a.height>0){const Q=new L0(a.height);return Q.fromEquirectangularTexture(t,C),A.set(C,Q),C.addEventListener("dispose",i),e(Q.texture,C.mapping)}else return null}}return C}function i(C){const o=C.target;o.removeEventListener("dispose",i);const a=A.get(o);a!==void 0&&(A.delete(o),a.dispose())}function I(){A=new WeakMap}return{get:g,dispose:I}}const si=4,q0=[.125,.215,.35,.446,.526,.582],Ui=20,D_=256,xC=new J0,H0=new Ie;let Es=null,rs=0,cs=0,hs=!1;const __=new J;class P0{constructor(A){this._renderer=A,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(A,e=0,g=.1,i=100,I={}){const{size:C=256,position:o=__}=I;Es=this._renderer.getRenderTarget(),rs=this._renderer.getActiveCubeFace(),cs=this._renderer.getActiveMipmapLevel(),hs=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(C);const a=this._allocateTargets();return a.depthBuffer=!0,this._sceneToCubeUV(A,g,i,a,o),e>0&&this._blur(a,0,0,e),this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(A,e=null){return this._fromTexture(A,e)}fromCubemap(A,e=null){return this._fromTexture(A,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=j0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=V0(),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(A){this._lodMax=Math.floor(Math.log2(A)),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 A=0;A<this._lodMeshes.length;A++)this._lodMeshes[A].geometry.dispose()}_cleanup(A){this._renderer.setRenderTarget(Es,rs,cs),this._renderer.xr.enabled=hs,A.scissorTest=!1,bI(A,0,0,A.width,A.height)}_fromTexture(A,e){A.mapping===yi||A.mapping===QI?this._setSize(A.image.length===0?16:A.image[0].width||A.image[0].image.width):this._setSize(A.image.width/4),Es=this._renderer.getRenderTarget(),rs=this._renderer.getActiveCubeFace(),cs=this._renderer.getActiveMipmapLevel(),hs=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const g=e||this._allocateTargets();return this._textureToCubeUV(A,g),this._applyPMREM(g),this._cleanup(g),g}_allocateTargets(){const A=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,g={magFilter:Ag,minFilter:Ag,generateMipmaps:!1,type:Rt,format:Hg,colorSpace:sI,depthBuffer:!1},i=O0(A,e,g);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==A||this._pingPongRenderTarget.height!==e){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=O0(A,e,g);const{_lodMax:I}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=w_(I)),this._blurMaterial=m_(I,A,e),this._ggxMaterial=p_(I,A,e)}return i}_compileMaterial(A){const e=new Xg(new Wg,A);this._renderer.compile(e,xC)}_sceneToCubeUV(A,e,g,i,I){const a=new Mg(90,1,e,g),Q=[1,-1,1,1,1,1],n=[1,1,1,-1,-1,-1],s=this._renderer,B=s.autoClear,E=s.toneMapping;s.getClearColor(H0),s.toneMapping=ot,s.autoClear=!1,s.state.buffers.depth.getReversed()&&(s.setRenderTarget(i),s.clearDepth(),s.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Xg(new hC,new m0({name:"PMREM.Background",side:tg,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let r=!1;const f=A.background;f?f.isColor&&(h.color.copy(f),A.background=null,r=!0):(h.color.copy(H0),r=!0);for(let _=0;_<6;_++){const l=_%3;l===0?(a.up.set(0,Q[_],0),a.position.set(I.x,I.y,I.z),a.lookAt(I.x+n[_],I.y,I.z)):l===1?(a.up.set(0,0,Q[_]),a.position.set(I.x,I.y,I.z),a.lookAt(I.x,I.y+n[_],I.z)):(a.up.set(0,Q[_],0),a.position.set(I.x,I.y,I.z),a.lookAt(I.x,I.y,I.z+n[_]));const D=this._cubeSize;bI(i,l*D,_>2?D:0,D,D),s.setRenderTarget(i),r&&s.render(c,a),s.render(A,a)}s.toneMapping=E,s.autoClear=B,A.background=f}_textureToCubeUV(A,e){const g=this._renderer,i=A.mapping===yi||A.mapping===QI;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=j0()),this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=V0());const I=i?this._cubemapMaterial:this._equirectMaterial,C=this._lodMeshes[0];C.material=I;const o=I.uniforms;o.envMap.value=A;const a=this._cubeSize;bI(e,0,0,3*a,2*a),g.setRenderTarget(e),g.render(C,xC)}_applyPMREM(A){const e=this._renderer,g=e.autoClear;e.autoClear=!1;const i=this._lodMeshes.length;for(let I=1;I<i;I++)this._applyGGXFilter(A,I-1,I);e.autoClear=g}_applyGGXFilter(A,e,g){const i=this._renderer,I=this._pingPongRenderTarget,C=this._ggxMaterial,o=this._lodMeshes[g];o.material=C;const a=C.uniforms,Q=g/(this._lodMeshes.length-1),n=e/(this._lodMeshes.length-1),s=Math.sqrt(Q*Q-n*n),B=0+Q*1.25,E=s*B,{_lodMax:d}=this,c=this._sizeLods[g],h=3*c*(g>d-si?g-d+si:0),r=4*(this._cubeSize-c);a.envMap.value=A.texture,a.roughness.value=E,a.mipInt.value=d-e,bI(I,h,r,3*c,2*c),i.setRenderTarget(I),i.render(o,xC),a.envMap.value=I.texture,a.roughness.value=0,a.mipInt.value=d-g,bI(A,h,r,3*c,2*c),i.setRenderTarget(A),i.render(o,xC)}_blur(A,e,g,i,I){const C=this._pingPongRenderTarget;this._halfBlur(A,C,e,g,i,"latitudinal",I),this._halfBlur(C,A,g,g,i,"longitudinal",I)}_halfBlur(A,e,g,i,I,C,o){const a=this._renderer,Q=this._blurMaterial;C!=="latitudinal"&&C!=="longitudinal"&&ae("blur direction must be either latitudinal or longitudinal!");const n=3,s=this._lodMeshes[i];s.material=Q;const B=Q.uniforms,E=this._sizeLods[g]-1,d=isFinite(I)?Math.PI/(2*E):2*Math.PI/(2*Ui-1),c=I/d,h=isFinite(I)?1+Math.floor(n*c):Ui;h>Ui&&LA(`sigmaRadians, ${I}, is too large and will clip, as it requested ${h} samples when the maximum is set to ${Ui}`);const r=[];let f=0;for(let y=0;y<Ui;++y){const k=y/c,x=Math.exp(-k*k/2);r.push(x),y===0?f+=x:y<h&&(f+=2*x)}for(let y=0;y<r.length;y++)r[y]=r[y]/f;B.envMap.value=A.texture,B.samples.value=h,B.weights.value=r,B.latitudinal.value=C==="latitudinal",o&&(B.poleAxis.value=o);const{_lodMax:_}=this;B.dTheta.value=d,B.mipInt.value=_-g;const l=this._sizeLods[i],D=3*l*(i>_-si?i-_+si:0),p=4*(this._cubeSize-l);bI(e,D,p,3*l,2*l),a.setRenderTarget(e),a.render(s,xC)}}function w_(t){const A=[],e=[],g=[];let i=t;const I=t-si+1+q0.length;for(let C=0;C<I;C++){const o=Math.pow(2,i);A.push(o);let a=1/o;C>t-si?a=q0[C-t+si-1]:C===0&&(a=0),e.push(a);const Q=1/(o-2),n=-Q,s=1+Q,B=[n,n,s,n,s,s,n,n,s,s,n,s],E=6,d=6,c=3,h=2,r=1,f=new Float32Array(c*d*E),_=new Float32Array(h*d*E),l=new Float32Array(r*d*E);for(let p=0;p<E;p++){const y=p%3*2/3-1,k=p>2?0:-1,x=[y,k,0,y+2/3,k,0,y+2/3,k+1,0,y,k,0,y+2/3,k+1,0,y,k+1,0];f.set(x,c*d*p),_.set(B,h*d*p);const w=[p,p,p,p,p,p];l.set(w,r*d*p)}const D=new Wg;D.setAttribute("position",new Bt(f,c)),D.setAttribute("uv",new Bt(_,h)),D.setAttribute("faceIndex",new Bt(l,r)),g.push(new Xg(D,null)),i>si&&i--}return{lodMeshes:g,sizeLods:A,sigmas:e}}function O0(t,A,e){const g=new st(t,A,e);return g.texture.mapping=Eo,g.texture.name="PMREM.cubeUv",g.scissorTest=!0,g}function bI(t,A,e,g,i){t.viewport.set(A,e,g,i),t.scissor.set(A,e,g,i)}function p_(t,A,e){return new Gg({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:D_,CUBEUV_TEXEL_WIDTH:1/A,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ho(),fragmentShader:`
|
|
3760
3760
|
|
|
3761
3761
|
precision highp float;
|
|
3762
3762
|
precision highp int;
|
|
@@ -3864,7 +3864,7 @@ void main() {
|
|
|
3864
3864
|
|
|
3865
3865
|
gl_FragColor = vec4(prefilteredColor, 1.0);
|
|
3866
3866
|
}
|
|
3867
|
-
`,blending:St,depthTest:!1,depthWrite:!1})}function m_(t,A,e){const g=new Float32Array(
|
|
3867
|
+
`,blending:St,depthTest:!1,depthWrite:!1})}function m_(t,A,e){const g=new Float32Array(Ui),i=new J(0,1,0);return new Gg({name:"SphericalGaussianBlur",defines:{n:Ui,CUBEUV_TEXEL_WIDTH:1/A,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:g},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Ho(),fragmentShader:`
|
|
3868
3868
|
|
|
3869
3869
|
precision mediump float;
|
|
3870
3870
|
precision mediump int;
|
|
@@ -4014,7 +4014,7 @@ void main() {
|
|
|
4014
4014
|
gl_Position = vec4( position, 1.0 );
|
|
4015
4015
|
|
|
4016
4016
|
}
|
|
4017
|
-
`}function y_(t){let A=new WeakMap,e=null;function g(o){if(o&&o.isTexture){const a=o.mapping,Q=a===PQ||a===OQ,n=a===
|
|
4017
|
+
`}function y_(t){let A=new WeakMap,e=null;function g(o){if(o&&o.isTexture){const a=o.mapping,Q=a===PQ||a===OQ,n=a===yi||a===QI;if(Q||n){let s=A.get(o);const B=s!==void 0?s.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==B)return e===null&&(e=new P0(t)),s=Q?e.fromEquirectangular(o,s):e.fromCubemap(o,s),s.texture.pmremVersion=o.pmremVersion,A.set(o,s),s.texture;if(s!==void 0)return s.texture;{const E=o.image;return Q&&E&&E.height>0||n&&E&&i(E)?(e===null&&(e=new P0(t)),s=Q?e.fromEquirectangular(o):e.fromCubemap(o),s.texture.pmremVersion=o.pmremVersion,A.set(o,s),o.addEventListener("dispose",I),s.texture):null}}}return o}function i(o){let a=0;const Q=6;for(let n=0;n<Q;n++)o[n]!==void 0&&a++;return a===Q}function I(o){const a=o.target;a.removeEventListener("dispose",I);const Q=A.get(a);Q!==void 0&&(A.delete(a),Q.dispose())}function C(){A=new WeakMap,e!==null&&(e.dispose(),e=null)}return{get:g,dispose:C}}function b_(t){const A={};function e(g){if(A[g]!==void 0)return A[g];const i=t.getExtension(g);return A[g]=i,i}return{has:function(g){return e(g)!==null},init:function(){e("EXT_color_buffer_float"),e("WEBGL_clip_cull_distance"),e("OES_texture_float_linear"),e("EXT_color_buffer_half_float"),e("WEBGL_multisampled_render_to_texture"),e("WEBGL_render_shared_exponent")},get:function(g){const i=e(g);return i===null&&oC("WebGLRenderer: "+g+" extension not supported."),i}}}function N_(t,A,e,g){const i={},I=new WeakMap;function C(s){const B=s.target;B.index!==null&&A.remove(B.index);for(const d in B.attributes)A.remove(B.attributes[d]);B.removeEventListener("dispose",C),delete i[B.id];const E=I.get(B);E&&(A.remove(E),I.delete(B)),g.releaseStatesOfGeometry(B),B.isInstancedBufferGeometry===!0&&delete B._maxInstanceCount,e.memory.geometries--}function o(s,B){return i[B.id]===!0||(B.addEventListener("dispose",C),i[B.id]=!0,e.memory.geometries++),B}function a(s){const B=s.attributes;for(const E in B)A.update(B[E],t.ARRAY_BUFFER)}function Q(s){const B=[],E=s.index,d=s.attributes.position;let c=0;if(E!==null){const f=E.array;c=E.version;for(let _=0,l=f.length;_<l;_+=3){const D=f[_+0],p=f[_+1],y=f[_+2];B.push(D,p,p,y,y,D)}}else if(d!==void 0){const f=d.array;c=d.version;for(let _=0,l=f.length/3-1;_<l;_+=3){const D=_+0,p=_+1,y=_+2;B.push(D,p,p,y,y,D)}}else return;const h=new(Q0(B)?b0:y0)(B,1);h.version=c;const r=I.get(s);r&&A.remove(r),I.set(s,h)}function n(s){const B=I.get(s);if(B){const E=s.index;E!==null&&B.version<E.version&&Q(s)}else Q(s);return I.get(s)}return{get:o,update:a,getWireframeAttribute:n}}function S_(t,A,e){let g;function i(B){g=B}let I,C;function o(B){I=B.type,C=B.bytesPerElement}function a(B,E){t.drawElements(g,E,I,B*C),e.update(E,g,1)}function Q(B,E,d){d!==0&&(t.drawElementsInstanced(g,E,I,B*C,d),e.update(E,g,d))}function n(B,E,d){if(d===0)return;A.get("WEBGL_multi_draw").multiDrawElementsWEBGL(g,E,0,I,B,0,d);let h=0;for(let r=0;r<d;r++)h+=E[r];e.update(h,g,1)}function s(B,E,d,c){if(d===0)return;const h=A.get("WEBGL_multi_draw");if(h===null)for(let r=0;r<B.length;r++)Q(B[r]/C,E[r],c[r]);else{h.multiDrawElementsInstancedWEBGL(g,E,0,I,B,0,c,0,d);let r=0;for(let f=0;f<d;f++)r+=E[f]*c[f];e.update(r,g,1)}}this.setMode=i,this.setIndex=o,this.render=a,this.renderInstances=Q,this.renderMultiDraw=n,this.renderMultiDrawInstances=s}function k_(t){const A={geometries:0,textures:0},e={frame:0,calls:0,triangles:0,points:0,lines:0};function g(I,C,o){switch(e.calls++,C){case t.TRIANGLES:e.triangles+=o*(I/3);break;case t.LINES:e.lines+=o*(I/2);break;case t.LINE_STRIP:e.lines+=o*(I-1);break;case t.LINE_LOOP:e.lines+=o*I;break;case t.POINTS:e.points+=o*I;break;default:ae("WebGLInfo: Unknown draw mode:",C);break}}function i(){e.calls=0,e.triangles=0,e.points=0,e.lines=0}return{memory:A,render:e,programs:null,autoReset:!0,reset:i,update:g}}function R_(t,A,e){const g=new WeakMap,i=new Ke;function I(C,o,a){const Q=C.morphTargetInfluences,n=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,s=n!==void 0?n.length:0;let B=g.get(o);if(B===void 0||B.count!==s){let x=function(){y.dispose(),g.delete(o),o.removeEventListener("dispose",x)};B!==void 0&&B.texture.dispose();const E=o.morphAttributes.position!==void 0,d=o.morphAttributes.normal!==void 0,c=o.morphAttributes.color!==void 0,h=o.morphAttributes.position||[],r=o.morphAttributes.normal||[],f=o.morphAttributes.color||[];let _=0;E===!0&&(_=1),d===!0&&(_=2),c===!0&&(_=3);let l=o.attributes.position.count*_,D=1;l>A.maxTextureSize&&(D=Math.ceil(l/A.maxTextureSize),l=A.maxTextureSize);const p=new Float32Array(l*D*4*s),y=new c0(p,l,D,s);y.type=Qt,y.needsUpdate=!0;const k=_*4;for(let w=0;w<s;w++){const N=h[w],U=r[w],K=f[w],P=l*D*4*w;for(let j=0;j<N.count;j++){const H=j*k;E===!0&&(i.fromBufferAttribute(N,j),p[P+H+0]=i.x,p[P+H+1]=i.y,p[P+H+2]=i.z,p[P+H+3]=0),d===!0&&(i.fromBufferAttribute(U,j),p[P+H+4]=i.x,p[P+H+5]=i.y,p[P+H+6]=i.z,p[P+H+7]=0),c===!0&&(i.fromBufferAttribute(K,j),p[P+H+8]=i.x,p[P+H+9]=i.y,p[P+H+10]=i.z,p[P+H+11]=K.itemSize===4?i.w:1)}}B={count:s,texture:y,size:new Be(l,D)},g.set(o,B),o.addEventListener("dispose",x)}if(C.isInstancedMesh===!0&&C.morphTexture!==null)a.getUniforms().setValue(t,"morphTexture",C.morphTexture,e);else{let E=0;for(let c=0;c<Q.length;c++)E+=Q[c];const d=o.morphTargetsRelative?1:1-E;a.getUniforms().setValue(t,"morphTargetBaseInfluence",d),a.getUniforms().setValue(t,"morphTargetInfluences",Q)}a.getUniforms().setValue(t,"morphTargetsTexture",B.texture,e),a.getUniforms().setValue(t,"morphTargetsTextureSize",B.size)}return{update:I}}function G_(t,A,e,g){let i=new WeakMap;function I(a){const Q=g.render.frame,n=a.geometry,s=A.get(a,n);if(i.get(s)!==Q&&(A.update(s),i.set(s,Q)),a.isInstancedMesh&&(a.hasEventListener("dispose",o)===!1&&a.addEventListener("dispose",o),i.get(a)!==Q&&(e.update(a.instanceMatrix,t.ARRAY_BUFFER),a.instanceColor!==null&&e.update(a.instanceColor,t.ARRAY_BUFFER),i.set(a,Q))),a.isSkinnedMesh){const B=a.skeleton;i.get(B)!==Q&&(B.update(),i.set(B,Q))}return s}function C(){i=new WeakMap}function o(a){const Q=a.target;Q.removeEventListener("dispose",o),e.remove(Q.instanceMatrix),Q.instanceColor!==null&&e.remove(Q.instanceColor)}return{update:I,dispose:C}}const M_={[Pr]:"LINEAR_TONE_MAPPING",[Or]:"REINHARD_TONE_MAPPING",[Vr]:"CINEON_TONE_MAPPING",[jr]:"ACES_FILMIC_TONE_MAPPING",[Xr]:"AGX_TONE_MAPPING",[Zr]:"NEUTRAL_TONE_MAPPING",[Wr]:"CUSTOM_TONE_MAPPING"};function F_(t,A,e,g,i){const I=new st(A,e,{type:t,depthBuffer:g,stencilBuffer:i}),C=new st(A,e,{type:Rt,depthBuffer:!1,stencilBuffer:!1}),o=new Wg;o.setAttribute("position",new Ig([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new Ig([0,2,0,0,2,0],2));const a=new Qu({uniforms:{tDiffuse:{value:null}},vertexShader:`
|
|
4018
4018
|
precision highp float;
|
|
4019
4019
|
|
|
4020
4020
|
uniform mat4 modelViewMatrix;
|
|
@@ -4090,7 +4090,7 @@ void main() {
|
|
|
4090
4090
|
`;return t.precision==="highp"?A+=`
|
|
4091
4091
|
#define HIGH_PRECISION`:t.precision==="mediump"?A+=`
|
|
4092
4092
|
#define MEDIUM_PRECISION`:t.precision==="lowp"&&(A+=`
|
|
4093
|
-
#define LOW_PRECISION`),A}const T2={[Bo]:"SHADOWMAP_TYPE_PCF",[iC]:"SHADOWMAP_TYPE_VSM"};function q2(t){return T2[t.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const H2={[
|
|
4093
|
+
#define LOW_PRECISION`),A}const T2={[Bo]:"SHADOWMAP_TYPE_PCF",[iC]:"SHADOWMAP_TYPE_VSM"};function q2(t){return T2[t.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const H2={[yi]:"ENVMAP_TYPE_CUBE",[QI]:"ENVMAP_TYPE_CUBE",[Eo]:"ENVMAP_TYPE_CUBE_UV"};function P2(t){return t.envMap===!1?"ENVMAP_TYPE_CUBE":H2[t.envMapMode]||"ENVMAP_TYPE_CUBE"}const O2={[QI]:"ENVMAP_MODE_REFRACTION"};function V2(t){return t.envMap===!1?"ENVMAP_MODE_REFLECTION":O2[t.envMapMode]||"ENVMAP_MODE_REFLECTION"}const j2={[Hr]:"ENVMAP_BLENDING_MULTIPLY",[xf]:"ENVMAP_BLENDING_MIX",[lf]:"ENVMAP_BLENDING_ADD"};function W2(t){return t.envMap===!1?"ENVMAP_BLENDING_NONE":j2[t.combine]||"ENVMAP_BLENDING_NONE"}function X2(t){const A=t.envMapCubeUVHeight;if(A===null)return null;const e=Math.log2(A)-2,g=1/A;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:g,maxMip:e}}function Z2(t,A,e,g){const i=t.getContext(),I=e.defines;let C=e.vertexShader,o=e.fragmentShader;const a=q2(e),Q=P2(e),n=V2(e),s=W2(e),B=X2(e),E=M2(e),d=F2(I),c=i.createProgram();let h,r,f=e.glslVersion?"#version "+e.glslVersion+`
|
|
4094
4094
|
`:"";e.isRawShaderMaterial?(h=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,d].filter(lC).join(`
|
|
4095
4095
|
`),h.length>0&&(h+=`
|
|
4096
4096
|
`),r=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,d].filter(lC).join(`
|
|
@@ -4138,7 +4138,7 @@ void main() {
|
|
|
4138
4138
|
squared_mean = squared_mean / samples;
|
|
4139
4139
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
4140
4140
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
4141
|
-
}`,Ew=[new J(1,0,0),new J(-1,0,0),new J(0,1,0),new J(0,-1,0),new J(0,0,1),new J(0,0,-1)],rw=[new J(0,-1,0),new J(0,-1,0),new J(0,0,1),new J(0,0,-1),new J(0,-1,0),new J(0,-1,0)],cc=new Ye,fC=new J,fs=new J;function cw(t,A,e){let g=new K0;const i=new Be,I=new Be,C=new Ke,o=new nu,a=new su,Q={},n=e.maxTextureSize,s={[bt]:tg,[tg]:bt,[Nt]:Nt},B=new Gg({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Be},radius:{value:4}},vertexShader:sw,fragmentShader:Bw}),E=B.clone();E.defines.HORIZONTAL_PASS=1;const d=new Wg;d.setAttribute("position",new Bt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const c=new Xg(d,B),h=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Bo;let r=this.type;this.render=function(p,y,k){if(h.enabled===!1||h.autoUpdate===!1&&h.needsUpdate===!1||p.length===0)return;p.type===zl&&(LA("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),p.type=Bo);const x=t.getRenderTarget(),w=t.getActiveCubeFace(),N=t.getActiveMipmapLevel(),U=t.state;U.setBlending(St),U.buffers.depth.getReversed()===!0?U.buffers.color.setClear(0,0,0,0):U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const K=r!==this.type;K&&y.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(j=>j.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,j=p.length;P<j;P++){const H=p[P],O=H.shadow;if(O===void 0){LA("WebGLShadowMap:",H,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;i.copy(O.mapSize);const z=O.getFrameExtents();if(i.multiply(z),I.copy(O.mapSize),(i.x>n||i.y>n)&&(i.x>n&&(I.x=Math.floor(n/z.x),i.x=I.x*z.x,O.mapSize.x=I.x),i.y>n&&(I.y=Math.floor(n/z.y),i.y=I.y*z.y,O.mapSize.y=I.y)),O.map===null||K===!0){if(O.map!==null&&(O.map.depthTexture!==null&&(O.map.depthTexture.dispose(),O.map.depthTexture=null),O.map.dispose()),this.type===iC){if(H.isPointLight){LA("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new st(i.x,i.y,{format:nI,type:Rt,minFilter:Ag,magFilter:Ag,generateMipmaps:!1}),O.map.texture.name=H.name+".shadowMap",O.map.depthTexture=new dC(i.x,i.y,Qt),O.map.depthTexture.name=H.name+".shadowMapDepth",O.map.depthTexture.format=Gt,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=$e,O.map.depthTexture.magFilter=$e}else{H.isPointLight?(O.map=new L0(i.x),O.map.depthTexture=new au(i.x,at)):(O.map=new st(i.x,i.y),O.map.depthTexture=new dC(i.x,i.y,at)),O.map.depthTexture.name=H.name+".shadowMap",O.map.depthTexture.format=Gt;const sA=t.state.buffers.depth.getReversed();this.type===Bo?(O.map.depthTexture.compareFunction=sA?Un:Fn,O.map.depthTexture.minFilter=Ag,O.map.depthTexture.magFilter=Ag):(O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=$e,O.map.depthTexture.magFilter=$e)}O.camera.updateProjectionMatrix()}const xA=O.map.isWebGLCubeRenderTarget?6:1;for(let sA=0;sA<xA;sA++){if(O.map.isWebGLCubeRenderTarget)t.setRenderTarget(O.map,sA),t.clear();else{sA===0&&(t.setRenderTarget(O.map),t.clear());const fA=O.getViewport(sA);C.set(I.x*fA.x,I.y*fA.y,I.x*fA.z,I.y*fA.w),U.viewport(C)}if(H.isPointLight){const fA=O.camera,JA=O.matrix,vA=H.distance||fA.far;vA!==fA.far&&(fA.far=vA,fA.updateProjectionMatrix()),fC.setFromMatrixPosition(H.matrixWorld),fA.position.copy(fC),fs.copy(fA.position),fs.add(Ew[sA]),fA.up.copy(rw[sA]),fA.lookAt(fs),fA.updateMatrixWorld(),JA.makeTranslation(-fC.x,-fC.y,-fC.z),cc.multiplyMatrices(fA.projectionMatrix,fA.matrixWorldInverse),O._frustum.setFromProjectionMatrix(cc,fA.coordinateSystem,fA.reversedDepth)}else O.updateMatrices(H);g=O.getFrustum(),l(y,k,O.camera,H,this.type)}O.isPointLightShadow!==!0&&this.type===iC&&f(O,k),O.needsUpdate=!1}r=this.type,h.needsUpdate=!1,t.setRenderTarget(x,w,N)};function f(p,y){const k=A.update(c);B.defines.VSM_SAMPLES!==p.blurSamples&&(B.defines.VSM_SAMPLES=p.blurSamples,E.defines.VSM_SAMPLES=p.blurSamples,B.needsUpdate=!0,E.needsUpdate=!0),p.mapPass===null&&(p.mapPass=new st(i.x,i.y,{format:nI,type:Rt})),B.uniforms.shadow_pass.value=p.map.depthTexture,B.uniforms.resolution.value=p.mapSize,B.uniforms.radius.value=p.radius,t.setRenderTarget(p.mapPass),t.clear(),t.renderBufferDirect(y,null,k,B,c,null),E.uniforms.shadow_pass.value=p.mapPass.texture,E.uniforms.resolution.value=p.mapSize,E.uniforms.radius.value=p.radius,t.setRenderTarget(p.map),t.clear(),t.renderBufferDirect(y,null,k,E,c,null)}function _(p,y,k,x){let w=null;const N=k.isPointLight===!0?p.customDistanceMaterial:p.customDepthMaterial;if(N!==void 0)w=N;else if(w=k.isPointLight===!0?a:o,t.localClippingEnabled&&y.clipShadows===!0&&Array.isArray(y.clippingPlanes)&&y.clippingPlanes.length!==0||y.displacementMap&&y.displacementScale!==0||y.alphaMap&&y.alphaTest>0||y.map&&y.alphaTest>0||y.alphaToCoverage===!0){const U=w.uuid,K=y.uuid;let P=Q[U];P===void 0&&(P={},Q[U]=P);let j=P[K];j===void 0&&(j=w.clone(),P[K]=j,y.addEventListener("dispose",D)),w=j}if(w.visible=y.visible,w.wireframe=y.wireframe,x===iC?w.side=y.shadowSide!==null?y.shadowSide:y.side:w.side=y.shadowSide!==null?y.shadowSide:s[y.side],w.alphaMap=y.alphaMap,w.alphaTest=y.alphaToCoverage===!0?.5:y.alphaTest,w.map=y.map,w.clipShadows=y.clipShadows,w.clippingPlanes=y.clippingPlanes,w.clipIntersection=y.clipIntersection,w.displacementMap=y.displacementMap,w.displacementScale=y.displacementScale,w.displacementBias=y.displacementBias,w.wireframeLinewidth=y.wireframeLinewidth,w.linewidth=y.linewidth,k.isPointLight===!0&&w.isMeshDistanceMaterial===!0){const U=t.properties.get(w);U.light=k}return w}function l(p,y,k,x,w){if(p.visible===!1)return;if(p.layers.test(y.layers)&&(p.isMesh||p.isLine||p.isPoints)&&(p.castShadow||p.receiveShadow&&w===iC)&&(!p.frustumCulled||g.intersectsObject(p))){p.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,p.matrixWorld);const K=A.update(p),P=p.material;if(Array.isArray(P)){const j=K.groups;for(let H=0,O=j.length;H<O;H++){const z=j[H],xA=P[z.materialIndex];if(xA&&xA.visible){const sA=_(p,xA,x,w);p.onBeforeShadow(t,p,y,k,K,sA,z),t.renderBufferDirect(k,null,K,sA,p,z),p.onAfterShadow(t,p,y,k,K,sA,z)}}}else if(P.visible){const j=_(p,P,x,w);p.onBeforeShadow(t,p,y,k,K,j,null),t.renderBufferDirect(k,null,K,j,p,null),p.onAfterShadow(t,p,y,k,K,j,null)}}const U=p.children;for(let K=0,P=U.length;K<P;K++)l(U[K],y,k,x,w)}function D(p){p.target.removeEventListener("dispose",D);for(const k in Q){const x=Q[k],w=p.target.uuid;w in x&&(x[w].dispose(),delete x[w])}}}const hw={[KQ]:vQ,[JQ]:qQ,[YQ]:HQ,[aI]:TQ,[vQ]:KQ,[qQ]:JQ,[HQ]:YQ,[TQ]:aI};function dw(t,A){function e(){let G=!1;const uA=new Ke;let aA=null;const DA=new Ke(0,0,0,0);return{setMask:function(IA){aA!==IA&&!G&&(t.colorMask(IA,IA,IA,IA),aA=IA)},setLocked:function(IA){G=IA},setClear:function(IA,eA,BA,KA,pe){pe===!0&&(IA*=KA,eA*=KA,BA*=KA),uA.set(IA,eA,BA,KA),DA.equals(uA)===!1&&(t.clearColor(IA,eA,BA,KA),DA.copy(uA))},reset:function(){G=!1,aA=null,DA.set(-1,0,0,0)}}}function g(){let G=!1,uA=!1,aA=null,DA=null,IA=null;return{setReversed:function(eA){if(uA!==eA){const BA=A.get("EXT_clip_control");eA?BA.clipControlEXT(BA.LOWER_LEFT_EXT,BA.ZERO_TO_ONE_EXT):BA.clipControlEXT(BA.LOWER_LEFT_EXT,BA.NEGATIVE_ONE_TO_ONE_EXT),uA=eA;const KA=IA;IA=null,this.setClear(KA)}},getReversed:function(){return uA},setTest:function(eA){eA?iA(t.DEPTH_TEST):wA(t.DEPTH_TEST)},setMask:function(eA){aA!==eA&&!G&&(t.depthMask(eA),aA=eA)},setFunc:function(eA){if(uA&&(eA=hw[eA]),DA!==eA){switch(eA){case KQ:t.depthFunc(t.NEVER);break;case vQ:t.depthFunc(t.ALWAYS);break;case JQ:t.depthFunc(t.LESS);break;case aI:t.depthFunc(t.LEQUAL);break;case YQ:t.depthFunc(t.EQUAL);break;case TQ:t.depthFunc(t.GEQUAL);break;case qQ:t.depthFunc(t.GREATER);break;case HQ:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}DA=eA}},setLocked:function(eA){G=eA},setClear:function(eA){IA!==eA&&(uA&&(eA=1-eA),t.clearDepth(eA),IA=eA)},reset:function(){G=!1,aA=null,DA=null,IA=null,uA=!1}}}function i(){let G=!1,uA=null,aA=null,DA=null,IA=null,eA=null,BA=null,KA=null,pe=null;return{setTest:function(he){G||(he?iA(t.STENCIL_TEST):wA(t.STENCIL_TEST))},setMask:function(he){uA!==he&&!G&&(t.stencilMask(he),uA=he)},setFunc:function(he,ht,Yt){(aA!==he||DA!==ht||IA!==Yt)&&(t.stencilFunc(he,ht,Yt),aA=he,DA=ht,IA=Yt)},setOp:function(he,ht,Yt){(eA!==he||BA!==ht||KA!==Yt)&&(t.stencilOp(he,ht,Yt),eA=he,BA=ht,KA=Yt)},setLocked:function(he){G=he},setClear:function(he){pe!==he&&(t.clearStencil(he),pe=he)},reset:function(){G=!1,uA=null,aA=null,DA=null,IA=null,eA=null,BA=null,KA=null,pe=null}}}const I=new e,C=new g,o=new i,a=new WeakMap,Q=new WeakMap;let n={},s={},B=new WeakMap,E=[],d=null,c=!1,h=null,r=null,f=null,_=null,l=null,D=null,p=null,y=new Ie(0,0,0),k=0,x=!1,w=null,N=null,U=null,K=null,P=null;const j=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,O=0;const z=t.getParameter(t.VERSION);z.indexOf("WebGL")!==-1?(O=parseFloat(/^WebGL (\d)/.exec(z)[1]),H=O>=1):z.indexOf("OpenGL ES")!==-1&&(O=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),H=O>=2);let xA=null,sA={};const fA=t.getParameter(t.SCISSOR_BOX),JA=t.getParameter(t.VIEWPORT),vA=new Ke().fromArray(fA),be=new Ke().fromArray(JA);function le(G,uA,aA,DA){const IA=new Uint8Array(4),eA=t.createTexture();t.bindTexture(G,eA),t.texParameteri(G,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(G,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let BA=0;BA<aA;BA++)G===t.TEXTURE_3D||G===t.TEXTURE_2D_ARRAY?t.texImage3D(uA,0,t.RGBA,1,1,DA,0,t.RGBA,t.UNSIGNED_BYTE,IA):t.texImage2D(uA+BA,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,IA);return eA}const Z={};Z[t.TEXTURE_2D]=le(t.TEXTURE_2D,t.TEXTURE_2D,1),Z[t.TEXTURE_CUBE_MAP]=le(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),Z[t.TEXTURE_2D_ARRAY]=le(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),Z[t.TEXTURE_3D]=le(t.TEXTURE_3D,t.TEXTURE_3D,1,1),I.setClear(0,0,0,1),C.setClear(1),o.setClear(0),iA(t.DEPTH_TEST),C.setFunc(aI),OA(!1),qe(Yr),iA(t.CULL_FACE),ce(St);function iA(G){n[G]!==!0&&(t.enable(G),n[G]=!0)}function wA(G){n[G]!==!1&&(t.disable(G),n[G]=!1)}function TA(G,uA){return s[G]!==uA?(t.bindFramebuffer(G,uA),s[G]=uA,G===t.DRAW_FRAMEBUFFER&&(s[t.FRAMEBUFFER]=uA),G===t.FRAMEBUFFER&&(s[t.DRAW_FRAMEBUFFER]=uA),!0):!1}function yA(G,uA){let aA=E,DA=!1;if(G){aA=B.get(uA),aA===void 0&&(aA=[],B.set(uA,aA));const IA=G.textures;if(aA.length!==IA.length||aA[0]!==t.COLOR_ATTACHMENT0){for(let eA=0,BA=IA.length;eA<BA;eA++)aA[eA]=t.COLOR_ATTACHMENT0+eA;aA.length=IA.length,DA=!0}}else aA[0]!==t.BACK&&(aA[0]=t.BACK,DA=!0);DA&&t.drawBuffers(aA)}function Qe(G){return d!==G?(t.useProgram(G),d=G,!0):!1}const Ze={[pi]:t.FUNC_ADD,[Af]:t.FUNC_SUBTRACT,[ef]:t.FUNC_REVERSE_SUBTRACT};Ze[gf]=t.MIN,Ze[tf]=t.MAX;const oe={[If]:t.ZERO,[Cf]:t.ONE,[of]:t.SRC_COLOR,[UQ]:t.SRC_ALPHA,[Ef]:t.SRC_ALPHA_SATURATE,[sf]:t.DST_COLOR,[Qf]:t.DST_ALPHA,[af]:t.ONE_MINUS_SRC_COLOR,[LQ]:t.ONE_MINUS_SRC_ALPHA,[Bf]:t.ONE_MINUS_DST_COLOR,[nf]:t.ONE_MINUS_DST_ALPHA,[rf]:t.CONSTANT_COLOR,[cf]:t.ONE_MINUS_CONSTANT_COLOR,[hf]:t.CONSTANT_ALPHA,[df]:t.ONE_MINUS_CONSTANT_ALPHA};function ce(G,uA,aA,DA,IA,eA,BA,KA,pe,he){if(G===St){c===!0&&(wA(t.BLEND),c=!1);return}if(c===!1&&(iA(t.BLEND),c=!0),G!==$l){if(G!==h||he!==x){if((r!==pi||l!==pi)&&(t.blendEquation(t.FUNC_ADD),r=pi,l=pi),he)switch(G){case oI:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FQ:t.blendFunc(t.ONE,t.ONE);break;case Tr:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case qr:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:ae("WebGLState: Invalid blending: ",G);break}else switch(G){case oI:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FQ:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case Tr:ae("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case qr:ae("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ae("WebGLState: Invalid blending: ",G);break}f=null,_=null,D=null,p=null,y.set(0,0,0),k=0,h=G,x=he}return}IA=IA||uA,eA=eA||aA,BA=BA||DA,(uA!==r||IA!==l)&&(t.blendEquationSeparate(Ze[uA],Ze[IA]),r=uA,l=IA),(aA!==f||DA!==_||eA!==D||BA!==p)&&(t.blendFuncSeparate(oe[aA],oe[DA],oe[eA],oe[BA]),f=aA,_=DA,D=eA,p=BA),(KA.equals(y)===!1||pe!==k)&&(t.blendColor(KA.r,KA.g,KA.b,pe),y.copy(KA),k=pe),h=G,x=!1}function De(G,uA){G.side===Nt?wA(t.CULL_FACE):iA(t.CULL_FACE);let aA=G.side===tg;uA&&(aA=!aA),OA(aA),G.blending===oI&&G.transparent===!1?ce(St):ce(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.blendColor,G.blendAlpha,G.premultipliedAlpha),C.setFunc(G.depthFunc),C.setTest(G.depthTest),C.setMask(G.depthWrite),I.setMask(G.colorWrite);const DA=G.stencilWrite;o.setTest(DA),DA&&(o.setMask(G.stencilWriteMask),o.setFunc(G.stencilFunc,G.stencilRef,G.stencilFuncMask),o.setOp(G.stencilFail,G.stencilZFail,G.stencilZPass)),He(G.polygonOffset,G.polygonOffsetFactor,G.polygonOffsetUnits),G.alphaToCoverage===!0?iA(t.SAMPLE_ALPHA_TO_COVERAGE):wA(t.SAMPLE_ALPHA_TO_COVERAGE)}function OA(G){w!==G&&(G?t.frontFace(t.CW):t.frontFace(t.CCW),w=G)}function qe(G){G!==Xl?(iA(t.CULL_FACE),G!==N&&(G===Yr?t.cullFace(t.BACK):G===Zl?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):wA(t.CULL_FACE),N=G}function R(G){G!==U&&(H&&t.lineWidth(G),U=G)}function He(G,uA,aA){G?(iA(t.POLYGON_OFFSET_FILL),(K!==uA||P!==aA)&&(t.polygonOffset(uA,aA),K=uA,P=aA)):wA(t.POLYGON_OFFSET_FILL)}function Ee(G){G?iA(t.SCISSOR_TEST):wA(t.SCISSOR_TEST)}function we(G){G===void 0&&(G=t.TEXTURE0+j-1),xA!==G&&(t.activeTexture(G),xA=G)}function NA(G,uA,aA){aA===void 0&&(xA===null?aA=t.TEXTURE0+j-1:aA=xA);let DA=sA[aA];DA===void 0&&(DA={type:void 0,texture:void 0},sA[aA]=DA),(DA.type!==G||DA.texture!==uA)&&(xA!==aA&&(t.activeTexture(aA),xA=aA),t.bindTexture(G,uA||Z[G]),DA.type=G,DA.texture=uA)}function b(){const G=sA[xA];G!==void 0&&G.type!==void 0&&(t.bindTexture(G.type,null),G.type=void 0,G.texture=void 0)}function u(){try{t.compressedTexImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function M(){try{t.compressedTexImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function X(){try{t.texSubImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function gA(){try{t.texSubImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function V(){try{t.compressedTexSubImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function kA(){try{t.compressedTexSubImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function EA(){try{t.texStorage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function bA(){try{t.texStorage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function UA(){try{t.texImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function CA(){try{t.texImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function cA(G){vA.equals(G)===!1&&(t.scissor(G.x,G.y,G.z,G.w),vA.copy(G))}function mA(G){be.equals(G)===!1&&(t.viewport(G.x,G.y,G.z,G.w),be.copy(G))}function SA(G,uA){let aA=Q.get(uA);aA===void 0&&(aA=new WeakMap,Q.set(uA,aA));let DA=aA.get(G);DA===void 0&&(DA=t.getUniformBlockIndex(uA,G.name),aA.set(G,DA))}function rA(G,uA){const DA=Q.get(uA).get(G);a.get(uA)!==DA&&(t.uniformBlockBinding(uA,DA,G.__bindingPointIndex),a.set(uA,DA))}function VA(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),C.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),n={},xA=null,sA={},s={},B=new WeakMap,E=[],d=null,c=!1,h=null,r=null,f=null,_=null,l=null,D=null,p=null,y=new Ie(0,0,0),k=0,x=!1,w=null,N=null,U=null,K=null,P=null,vA.set(0,0,t.canvas.width,t.canvas.height),be.set(0,0,t.canvas.width,t.canvas.height),I.reset(),C.reset(),o.reset()}return{buffers:{color:I,depth:C,stencil:o},enable:iA,disable:wA,bindFramebuffer:TA,drawBuffers:yA,useProgram:Qe,setBlending:ce,setMaterial:De,setFlipSided:OA,setCullFace:qe,setLineWidth:R,setPolygonOffset:He,setScissorTest:Ee,activeTexture:we,bindTexture:NA,unbindTexture:b,compressedTexImage2D:u,compressedTexImage3D:M,texImage2D:UA,texImage3D:CA,updateUBOMapping:SA,uniformBlockBinding:rA,texStorage2D:EA,texStorage3D:bA,texSubImage2D:X,texSubImage3D:gA,compressedTexSubImage2D:V,compressedTexSubImage3D:kA,scissor:cA,viewport:mA,reset:VA}}function xw(t,A,e,g,i,I,C){const o=A.has("WEBGL_multisampled_render_to_texture")?A.get("WEBGL_multisampled_render_to_texture"):null,a=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),Q=new Be,n=new WeakMap;let s;const B=new WeakMap;let E=!1;try{E=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function d(b,u){return E?new OffscreenCanvas(b,u):Do("canvas")}function c(b,u,M){let X=1;const gA=NA(b);if((gA.width>M||gA.height>M)&&(X=M/Math.max(gA.width,gA.height)),X<1)if(typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&b instanceof ImageBitmap||typeof VideoFrame<"u"&&b instanceof VideoFrame){const V=Math.floor(X*gA.width),kA=Math.floor(X*gA.height);s===void 0&&(s=d(V,kA));const EA=u?d(V,kA):s;return EA.width=V,EA.height=kA,EA.getContext("2d").drawImage(b,0,0,V,kA),LA("WebGLRenderer: Texture has been resized from ("+gA.width+"x"+gA.height+") to ("+V+"x"+kA+")."),EA}else return"data"in b&&LA("WebGLRenderer: Image in DataTexture is too big ("+gA.width+"x"+gA.height+")."),b;return b}function h(b){return b.generateMipmaps}function r(b){t.generateMipmap(b)}function f(b){return b.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:b.isWebGL3DRenderTarget?t.TEXTURE_3D:b.isWebGLArrayRenderTarget||b.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function _(b,u,M,X,gA=!1){if(b!==null){if(t[b]!==void 0)return t[b];LA("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+b+"'")}let V=u;if(u===t.RED&&(M===t.FLOAT&&(V=t.R32F),M===t.HALF_FLOAT&&(V=t.R16F),M===t.UNSIGNED_BYTE&&(V=t.R8)),u===t.RED_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.R8UI),M===t.UNSIGNED_SHORT&&(V=t.R16UI),M===t.UNSIGNED_INT&&(V=t.R32UI),M===t.BYTE&&(V=t.R8I),M===t.SHORT&&(V=t.R16I),M===t.INT&&(V=t.R32I)),u===t.RG&&(M===t.FLOAT&&(V=t.RG32F),M===t.HALF_FLOAT&&(V=t.RG16F),M===t.UNSIGNED_BYTE&&(V=t.RG8)),u===t.RG_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RG8UI),M===t.UNSIGNED_SHORT&&(V=t.RG16UI),M===t.UNSIGNED_INT&&(V=t.RG32UI),M===t.BYTE&&(V=t.RG8I),M===t.SHORT&&(V=t.RG16I),M===t.INT&&(V=t.RG32I)),u===t.RGB_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RGB8UI),M===t.UNSIGNED_SHORT&&(V=t.RGB16UI),M===t.UNSIGNED_INT&&(V=t.RGB32UI),M===t.BYTE&&(V=t.RGB8I),M===t.SHORT&&(V=t.RGB16I),M===t.INT&&(V=t.RGB32I)),u===t.RGBA_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RGBA8UI),M===t.UNSIGNED_SHORT&&(V=t.RGBA16UI),M===t.UNSIGNED_INT&&(V=t.RGBA32UI),M===t.BYTE&&(V=t.RGBA8I),M===t.SHORT&&(V=t.RGBA16I),M===t.INT&&(V=t.RGBA32I)),u===t.RGB&&(M===t.UNSIGNED_INT_5_9_9_9_REV&&(V=t.RGB9_E5),M===t.UNSIGNED_INT_10F_11F_11F_REV&&(V=t.R11F_G11F_B10F)),u===t.RGBA){const kA=gA?fo:Ce.getTransfer(X);M===t.FLOAT&&(V=t.RGBA32F),M===t.HALF_FLOAT&&(V=t.RGBA16F),M===t.UNSIGNED_BYTE&&(V=kA===re?t.SRGB8_ALPHA8:t.RGBA8),M===t.UNSIGNED_SHORT_4_4_4_4&&(V=t.RGBA4),M===t.UNSIGNED_SHORT_5_5_5_1&&(V=t.RGB5_A1)}return(V===t.R16F||V===t.R32F||V===t.RG16F||V===t.RG32F||V===t.RGBA16F||V===t.RGBA32F)&&A.get("EXT_color_buffer_float"),V}function l(b,u){let M;return b?u===null||u===at||u===CC?M=t.DEPTH24_STENCIL8:u===Qt?M=t.DEPTH32F_STENCIL8:u===IC&&(M=t.DEPTH24_STENCIL8,LA("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):u===null||u===at||u===CC?M=t.DEPTH_COMPONENT24:u===Qt?M=t.DEPTH_COMPONENT32F:u===IC&&(M=t.DEPTH_COMPONENT16),M}function D(b,u){return h(b)===!0||b.isFramebufferTexture&&b.minFilter!==$e&&b.minFilter!==Ag?Math.log2(Math.max(u.width,u.height))+1:b.mipmaps!==void 0&&b.mipmaps.length>0?b.mipmaps.length:b.isCompressedTexture&&Array.isArray(b.image)?u.mipmaps.length:1}function p(b){const u=b.target;u.removeEventListener("dispose",p),k(u),u.isVideoTexture&&n.delete(u)}function y(b){const u=b.target;u.removeEventListener("dispose",y),w(u)}function k(b){const u=g.get(b);if(u.__webglInit===void 0)return;const M=b.source,X=B.get(M);if(X){const gA=X[u.__cacheKey];gA.usedTimes--,gA.usedTimes===0&&x(b),Object.keys(X).length===0&&B.delete(M)}g.remove(b)}function x(b){const u=g.get(b);t.deleteTexture(u.__webglTexture);const M=b.source,X=B.get(M);delete X[u.__cacheKey],C.memory.textures--}function w(b){const u=g.get(b);if(b.depthTexture&&(b.depthTexture.dispose(),g.remove(b.depthTexture)),b.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(u.__webglFramebuffer[X]))for(let gA=0;gA<u.__webglFramebuffer[X].length;gA++)t.deleteFramebuffer(u.__webglFramebuffer[X][gA]);else t.deleteFramebuffer(u.__webglFramebuffer[X]);u.__webglDepthbuffer&&t.deleteRenderbuffer(u.__webglDepthbuffer[X])}else{if(Array.isArray(u.__webglFramebuffer))for(let X=0;X<u.__webglFramebuffer.length;X++)t.deleteFramebuffer(u.__webglFramebuffer[X]);else t.deleteFramebuffer(u.__webglFramebuffer);if(u.__webglDepthbuffer&&t.deleteRenderbuffer(u.__webglDepthbuffer),u.__webglMultisampledFramebuffer&&t.deleteFramebuffer(u.__webglMultisampledFramebuffer),u.__webglColorRenderbuffer)for(let X=0;X<u.__webglColorRenderbuffer.length;X++)u.__webglColorRenderbuffer[X]&&t.deleteRenderbuffer(u.__webglColorRenderbuffer[X]);u.__webglDepthRenderbuffer&&t.deleteRenderbuffer(u.__webglDepthRenderbuffer)}const M=b.textures;for(let X=0,gA=M.length;X<gA;X++){const V=g.get(M[X]);V.__webglTexture&&(t.deleteTexture(V.__webglTexture),C.memory.textures--),g.remove(M[X])}g.remove(b)}let N=0;function U(){N=0}function K(){const b=N;return b>=i.maxTextures&&LA("WebGLTextures: Trying to use "+b+" texture units while this GPU supports only "+i.maxTextures),N+=1,b}function P(b){const u=[];return u.push(b.wrapS),u.push(b.wrapT),u.push(b.wrapR||0),u.push(b.magFilter),u.push(b.minFilter),u.push(b.anisotropy),u.push(b.internalFormat),u.push(b.format),u.push(b.type),u.push(b.generateMipmaps),u.push(b.premultiplyAlpha),u.push(b.flipY),u.push(b.unpackAlignment),u.push(b.colorSpace),u.join()}function j(b,u){const M=g.get(b);if(b.isVideoTexture&&Ee(b),b.isRenderTargetTexture===!1&&b.isExternalTexture!==!0&&b.version>0&&M.__version!==b.version){const X=b.image;if(X===null)LA("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)LA("WebGLRenderer: Texture marked for update but image is incomplete");else{Z(M,b,u);return}}else b.isExternalTexture&&(M.__webglTexture=b.sourceTexture?b.sourceTexture:null);e.bindTexture(t.TEXTURE_2D,M.__webglTexture,t.TEXTURE0+u)}function H(b,u){const M=g.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&M.__version!==b.version){Z(M,b,u);return}else b.isExternalTexture&&(M.__webglTexture=b.sourceTexture?b.sourceTexture:null);e.bindTexture(t.TEXTURE_2D_ARRAY,M.__webglTexture,t.TEXTURE0+u)}function O(b,u){const M=g.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&M.__version!==b.version){Z(M,b,u);return}e.bindTexture(t.TEXTURE_3D,M.__webglTexture,t.TEXTURE0+u)}function z(b,u){const M=g.get(b);if(b.isCubeDepthTexture!==!0&&b.version>0&&M.__version!==b.version){iA(M,b,u);return}e.bindTexture(t.TEXTURE_CUBE_MAP,M.__webglTexture,t.TEXTURE0+u)}const xA={[VQ]:t.REPEAT,[kt]:t.CLAMP_TO_EDGE,[jQ]:t.MIRRORED_REPEAT},sA={[$e]:t.NEAREST,[ff]:t.NEAREST_MIPMAP_NEAREST,[ro]:t.NEAREST_MIPMAP_LINEAR,[Ag]:t.LINEAR,[WQ]:t.LINEAR_MIPMAP_NEAREST,[yi]:t.LINEAR_MIPMAP_LINEAR},fA={[wf]:t.NEVER,[Nf]:t.ALWAYS,[pf]:t.LESS,[Fn]:t.LEQUAL,[mf]:t.EQUAL,[Un]:t.GEQUAL,[yf]:t.GREATER,[bf]:t.NOTEQUAL};function JA(b,u){if(u.type===Qt&&A.has("OES_texture_float_linear")===!1&&(u.magFilter===Ag||u.magFilter===WQ||u.magFilter===ro||u.magFilter===yi||u.minFilter===Ag||u.minFilter===WQ||u.minFilter===ro||u.minFilter===yi)&&LA("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(b,t.TEXTURE_WRAP_S,xA[u.wrapS]),t.texParameteri(b,t.TEXTURE_WRAP_T,xA[u.wrapT]),(b===t.TEXTURE_3D||b===t.TEXTURE_2D_ARRAY)&&t.texParameteri(b,t.TEXTURE_WRAP_R,xA[u.wrapR]),t.texParameteri(b,t.TEXTURE_MAG_FILTER,sA[u.magFilter]),t.texParameteri(b,t.TEXTURE_MIN_FILTER,sA[u.minFilter]),u.compareFunction&&(t.texParameteri(b,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(b,t.TEXTURE_COMPARE_FUNC,fA[u.compareFunction])),A.has("EXT_texture_filter_anisotropic")===!0){if(u.magFilter===$e||u.minFilter!==ro&&u.minFilter!==yi||u.type===Qt&&A.has("OES_texture_float_linear")===!1)return;if(u.anisotropy>1||g.get(u).__currentAnisotropy){const M=A.get("EXT_texture_filter_anisotropic");t.texParameterf(b,M.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(u.anisotropy,i.getMaxAnisotropy())),g.get(u).__currentAnisotropy=u.anisotropy}}}function vA(b,u){let M=!1;b.__webglInit===void 0&&(b.__webglInit=!0,u.addEventListener("dispose",p));const X=u.source;let gA=B.get(X);gA===void 0&&(gA={},B.set(X,gA));const V=P(u);if(V!==b.__cacheKey){gA[V]===void 0&&(gA[V]={texture:t.createTexture(),usedTimes:0},C.memory.textures++,M=!0),gA[V].usedTimes++;const kA=gA[b.__cacheKey];kA!==void 0&&(gA[b.__cacheKey].usedTimes--,kA.usedTimes===0&&x(u)),b.__cacheKey=V,b.__webglTexture=gA[V].texture}return M}function be(b,u,M){return Math.floor(Math.floor(b/M)/u)}function le(b,u,M,X){const V=b.updateRanges;if(V.length===0)e.texSubImage2D(t.TEXTURE_2D,0,0,0,u.width,u.height,M,X,u.data);else{V.sort((CA,cA)=>CA.start-cA.start);let kA=0;for(let CA=1;CA<V.length;CA++){const cA=V[kA],mA=V[CA],SA=cA.start+cA.count,rA=be(mA.start,u.width,4),VA=be(cA.start,u.width,4);mA.start<=SA+1&&rA===VA&&be(mA.start+mA.count-1,u.width,4)===rA?cA.count=Math.max(cA.count,mA.start+mA.count-cA.start):(++kA,V[kA]=mA)}V.length=kA+1;const EA=t.getParameter(t.UNPACK_ROW_LENGTH),bA=t.getParameter(t.UNPACK_SKIP_PIXELS),UA=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,u.width);for(let CA=0,cA=V.length;CA<cA;CA++){const mA=V[CA],SA=Math.floor(mA.start/4),rA=Math.ceil(mA.count/4),VA=SA%u.width,G=Math.floor(SA/u.width),uA=rA,aA=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,VA),t.pixelStorei(t.UNPACK_SKIP_ROWS,G),e.texSubImage2D(t.TEXTURE_2D,0,VA,G,uA,aA,M,X,u.data)}b.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,EA),t.pixelStorei(t.UNPACK_SKIP_PIXELS,bA),t.pixelStorei(t.UNPACK_SKIP_ROWS,UA)}}function Z(b,u,M){let X=t.TEXTURE_2D;(u.isDataArrayTexture||u.isCompressedArrayTexture)&&(X=t.TEXTURE_2D_ARRAY),u.isData3DTexture&&(X=t.TEXTURE_3D);const gA=vA(b,u),V=u.source;e.bindTexture(X,b.__webglTexture,t.TEXTURE0+M);const kA=g.get(V);if(V.version!==kA.__version||gA===!0){e.activeTexture(t.TEXTURE0+M);const EA=Ce.getPrimaries(Ce.workingColorSpace),bA=u.colorSpace===ii?null:Ce.getPrimaries(u.colorSpace),UA=u.colorSpace===ii||EA===bA?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,u.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,u.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,UA);let CA=c(u.image,!1,i.maxTextureSize);CA=we(u,CA);const cA=I.convert(u.format,u.colorSpace),mA=I.convert(u.type);let SA=_(u.internalFormat,cA,mA,u.colorSpace,u.isVideoTexture);JA(X,u);let rA;const VA=u.mipmaps,G=u.isVideoTexture!==!0,uA=kA.__version===void 0||gA===!0,aA=V.dataReady,DA=D(u,CA);if(u.isDepthTexture)SA=l(u.format===bi,u.type),uA&&(G?e.texStorage2D(t.TEXTURE_2D,1,SA,CA.width,CA.height):e.texImage2D(t.TEXTURE_2D,0,SA,CA.width,CA.height,0,cA,mA,null));else if(u.isDataTexture)if(VA.length>0){G&&uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,VA[0].width,VA[0].height);for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,mA,rA.data):e.texImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,cA,mA,rA.data);u.generateMipmaps=!1}else G?(uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,CA.width,CA.height),aA&&le(u,CA,cA,mA)):e.texImage2D(t.TEXTURE_2D,0,SA,CA.width,CA.height,0,cA,mA,CA.data);else if(u.isCompressedTexture)if(u.isCompressedArrayTexture){G&&uA&&e.texStorage3D(t.TEXTURE_2D_ARRAY,DA,SA,VA[0].width,VA[0].height,CA.depth);for(let IA=0,eA=VA.length;IA<eA;IA++)if(rA=VA[IA],u.format!==Hg)if(cA!==null)if(G){if(aA)if(u.layerUpdates.size>0){const BA=Y0(rA.width,rA.height,u.format,u.type);for(const KA of u.layerUpdates){const pe=rA.data.subarray(KA*BA/rA.data.BYTES_PER_ELEMENT,(KA+1)*BA/rA.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,KA,rA.width,rA.height,1,cA,pe)}u.clearLayerUpdates()}else e.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,0,rA.width,rA.height,CA.depth,cA,rA.data)}else e.compressedTexImage3D(t.TEXTURE_2D_ARRAY,IA,SA,rA.width,rA.height,CA.depth,0,rA.data,0,0);else LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else G?aA&&e.texSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,0,rA.width,rA.height,CA.depth,cA,mA,rA.data):e.texImage3D(t.TEXTURE_2D_ARRAY,IA,SA,rA.width,rA.height,CA.depth,0,cA,mA,rA.data)}else{G&&uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,VA[0].width,VA[0].height);for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],u.format!==Hg?cA!==null?G?aA&&e.compressedTexSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,rA.data):e.compressedTexImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,rA.data):LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,mA,rA.data):e.texImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,cA,mA,rA.data)}else if(u.isDataArrayTexture)if(G){if(uA&&e.texStorage3D(t.TEXTURE_2D_ARRAY,DA,SA,CA.width,CA.height,CA.depth),aA)if(u.layerUpdates.size>0){const IA=Y0(CA.width,CA.height,u.format,u.type);for(const eA of u.layerUpdates){const BA=CA.data.subarray(eA*IA/CA.data.BYTES_PER_ELEMENT,(eA+1)*IA/CA.data.BYTES_PER_ELEMENT);e.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,eA,CA.width,CA.height,1,cA,mA,BA)}u.clearLayerUpdates()}else e.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,CA.width,CA.height,CA.depth,cA,mA,CA.data)}else e.texImage3D(t.TEXTURE_2D_ARRAY,0,SA,CA.width,CA.height,CA.depth,0,cA,mA,CA.data);else if(u.isData3DTexture)G?(uA&&e.texStorage3D(t.TEXTURE_3D,DA,SA,CA.width,CA.height,CA.depth),aA&&e.texSubImage3D(t.TEXTURE_3D,0,0,0,0,CA.width,CA.height,CA.depth,cA,mA,CA.data)):e.texImage3D(t.TEXTURE_3D,0,SA,CA.width,CA.height,CA.depth,0,cA,mA,CA.data);else if(u.isFramebufferTexture){if(uA)if(G)e.texStorage2D(t.TEXTURE_2D,DA,SA,CA.width,CA.height);else{let IA=CA.width,eA=CA.height;for(let BA=0;BA<DA;BA++)e.texImage2D(t.TEXTURE_2D,BA,SA,IA,eA,0,cA,mA,null),IA>>=1,eA>>=1}}else if(VA.length>0){if(G&&uA){const IA=NA(VA[0]);e.texStorage2D(t.TEXTURE_2D,DA,SA,IA.width,IA.height)}for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,cA,mA,rA):e.texImage2D(t.TEXTURE_2D,IA,SA,cA,mA,rA);u.generateMipmaps=!1}else if(G){if(uA){const IA=NA(CA);e.texStorage2D(t.TEXTURE_2D,DA,SA,IA.width,IA.height)}aA&&e.texSubImage2D(t.TEXTURE_2D,0,0,0,cA,mA,CA)}else e.texImage2D(t.TEXTURE_2D,0,SA,cA,mA,CA);h(u)&&r(X),kA.__version=V.version,u.onUpdate&&u.onUpdate(u)}b.__version=u.version}function iA(b,u,M){if(u.image.length!==6)return;const X=vA(b,u),gA=u.source;e.bindTexture(t.TEXTURE_CUBE_MAP,b.__webglTexture,t.TEXTURE0+M);const V=g.get(gA);if(gA.version!==V.__version||X===!0){e.activeTexture(t.TEXTURE0+M);const kA=Ce.getPrimaries(Ce.workingColorSpace),EA=u.colorSpace===ii?null:Ce.getPrimaries(u.colorSpace),bA=u.colorSpace===ii||kA===EA?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,u.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,u.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,bA);const UA=u.isCompressedTexture||u.image[0].isCompressedTexture,CA=u.image[0]&&u.image[0].isDataTexture,cA=[];for(let eA=0;eA<6;eA++)!UA&&!CA?cA[eA]=c(u.image[eA],!0,i.maxCubemapSize):cA[eA]=CA?u.image[eA].image:u.image[eA],cA[eA]=we(u,cA[eA]);const mA=cA[0],SA=I.convert(u.format,u.colorSpace),rA=I.convert(u.type),VA=_(u.internalFormat,SA,rA,u.colorSpace),G=u.isVideoTexture!==!0,uA=V.__version===void 0||X===!0,aA=gA.dataReady;let DA=D(u,mA);JA(t.TEXTURE_CUBE_MAP,u);let IA;if(UA){G&&uA&&e.texStorage2D(t.TEXTURE_CUBE_MAP,DA,VA,mA.width,mA.height);for(let eA=0;eA<6;eA++){IA=cA[eA].mipmaps;for(let BA=0;BA<IA.length;BA++){const KA=IA[BA];u.format!==Hg?SA!==null?G?aA&&e.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,0,0,KA.width,KA.height,SA,KA.data):e.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,VA,KA.width,KA.height,0,KA.data):LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,0,0,KA.width,KA.height,SA,rA,KA.data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,VA,KA.width,KA.height,0,SA,rA,KA.data)}}}else{if(IA=u.mipmaps,G&&uA){IA.length>0&&DA++;const eA=NA(cA[0]);e.texStorage2D(t.TEXTURE_CUBE_MAP,DA,VA,eA.width,eA.height)}for(let eA=0;eA<6;eA++)if(CA){G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,0,0,cA[eA].width,cA[eA].height,SA,rA,cA[eA].data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,VA,cA[eA].width,cA[eA].height,0,SA,rA,cA[eA].data);for(let BA=0;BA<IA.length;BA++){const pe=IA[BA].image[eA].image;G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,0,0,pe.width,pe.height,SA,rA,pe.data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,VA,pe.width,pe.height,0,SA,rA,pe.data)}}else{G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,0,0,SA,rA,cA[eA]):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,VA,SA,rA,cA[eA]);for(let BA=0;BA<IA.length;BA++){const KA=IA[BA];G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,0,0,SA,rA,KA.image[eA]):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,VA,SA,rA,KA.image[eA])}}}h(u)&&r(t.TEXTURE_CUBE_MAP),V.__version=gA.version,u.onUpdate&&u.onUpdate(u)}b.__version=u.version}function wA(b,u,M,X,gA,V){const kA=I.convert(M.format,M.colorSpace),EA=I.convert(M.type),bA=_(M.internalFormat,kA,EA,M.colorSpace),UA=g.get(u),CA=g.get(M);if(CA.__renderTarget=u,!UA.__hasExternalTextures){const cA=Math.max(1,u.width>>V),mA=Math.max(1,u.height>>V);gA===t.TEXTURE_3D||gA===t.TEXTURE_2D_ARRAY?e.texImage3D(gA,V,bA,cA,mA,u.depth,0,kA,EA,null):e.texImage2D(gA,V,bA,cA,mA,0,kA,EA,null)}e.bindFramebuffer(t.FRAMEBUFFER,b),He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,X,gA,CA.__webglTexture,0,R(u)):(gA===t.TEXTURE_2D||gA>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&gA<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,X,gA,CA.__webglTexture,V),e.bindFramebuffer(t.FRAMEBUFFER,null)}function TA(b,u,M){if(t.bindRenderbuffer(t.RENDERBUFFER,b),u.depthBuffer){const X=u.depthTexture,gA=X&&X.isDepthTexture?X.type:null,V=l(u.stencilBuffer,gA),kA=u.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;He(u)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,R(u),V,u.width,u.height):M?t.renderbufferStorageMultisample(t.RENDERBUFFER,R(u),V,u.width,u.height):t.renderbufferStorage(t.RENDERBUFFER,V,u.width,u.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,kA,t.RENDERBUFFER,b)}else{const X=u.textures;for(let gA=0;gA<X.length;gA++){const V=X[gA],kA=I.convert(V.format,V.colorSpace),EA=I.convert(V.type),bA=_(V.internalFormat,kA,EA,V.colorSpace);He(u)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,R(u),bA,u.width,u.height):M?t.renderbufferStorageMultisample(t.RENDERBUFFER,R(u),bA,u.width,u.height):t.renderbufferStorage(t.RENDERBUFFER,bA,u.width,u.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function yA(b,u,M){const X=u.isWebGLCubeRenderTarget===!0;if(e.bindFramebuffer(t.FRAMEBUFFER,b),!(u.depthTexture&&u.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const gA=g.get(u.depthTexture);if(gA.__renderTarget=u,(!gA.__webglTexture||u.depthTexture.image.width!==u.width||u.depthTexture.image.height!==u.height)&&(u.depthTexture.image.width=u.width,u.depthTexture.image.height=u.height,u.depthTexture.needsUpdate=!0),X){if(gA.__webglInit===void 0&&(gA.__webglInit=!0,u.depthTexture.addEventListener("dispose",p)),gA.__webglTexture===void 0){gA.__webglTexture=t.createTexture(),e.bindTexture(t.TEXTURE_CUBE_MAP,gA.__webglTexture),JA(t.TEXTURE_CUBE_MAP,u.depthTexture);const UA=I.convert(u.depthTexture.format),CA=I.convert(u.depthTexture.type);let cA;u.depthTexture.format===Gt?cA=t.DEPTH_COMPONENT24:u.depthTexture.format===bi&&(cA=t.DEPTH24_STENCIL8);for(let mA=0;mA<6;mA++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+mA,0,cA,u.width,u.height,0,UA,CA,null)}}else j(u.depthTexture,0);const V=gA.__webglTexture,kA=R(u),EA=X?t.TEXTURE_CUBE_MAP_POSITIVE_X+M:t.TEXTURE_2D,bA=u.depthTexture.format===bi?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(u.depthTexture.format===Gt)He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,bA,EA,V,0,kA):t.framebufferTexture2D(t.FRAMEBUFFER,bA,EA,V,0);else if(u.depthTexture.format===bi)He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,bA,EA,V,0,kA):t.framebufferTexture2D(t.FRAMEBUFFER,bA,EA,V,0);else throw new Error("Unknown depthTexture format")}function Qe(b){const u=g.get(b),M=b.isWebGLCubeRenderTarget===!0;if(u.__boundDepthTexture!==b.depthTexture){const X=b.depthTexture;if(u.__depthDisposeCallback&&u.__depthDisposeCallback(),X){const gA=()=>{delete u.__boundDepthTexture,delete u.__depthDisposeCallback,X.removeEventListener("dispose",gA)};X.addEventListener("dispose",gA),u.__depthDisposeCallback=gA}u.__boundDepthTexture=X}if(b.depthTexture&&!u.__autoAllocateDepthBuffer)if(M)for(let X=0;X<6;X++)yA(u.__webglFramebuffer[X],b,X);else{const X=b.texture.mipmaps;X&&X.length>0?yA(u.__webglFramebuffer[0],b,0):yA(u.__webglFramebuffer,b,0)}else if(M){u.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer[X]),u.__webglDepthbuffer[X]===void 0)u.__webglDepthbuffer[X]=t.createRenderbuffer(),TA(u.__webglDepthbuffer[X],b,!1);else{const gA=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,V=u.__webglDepthbuffer[X];t.bindRenderbuffer(t.RENDERBUFFER,V),t.framebufferRenderbuffer(t.FRAMEBUFFER,gA,t.RENDERBUFFER,V)}}else{const X=b.texture.mipmaps;if(X&&X.length>0?e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer[0]):e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer),u.__webglDepthbuffer===void 0)u.__webglDepthbuffer=t.createRenderbuffer(),TA(u.__webglDepthbuffer,b,!1);else{const gA=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,V=u.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,V),t.framebufferRenderbuffer(t.FRAMEBUFFER,gA,t.RENDERBUFFER,V)}}e.bindFramebuffer(t.FRAMEBUFFER,null)}function Ze(b,u,M){const X=g.get(b);u!==void 0&&wA(X.__webglFramebuffer,b,b.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),M!==void 0&&Qe(b)}function oe(b){const u=b.texture,M=g.get(b),X=g.get(u);b.addEventListener("dispose",y);const gA=b.textures,V=b.isWebGLCubeRenderTarget===!0,kA=gA.length>1;if(kA||(X.__webglTexture===void 0&&(X.__webglTexture=t.createTexture()),X.__version=u.version,C.memory.textures++),V){M.__webglFramebuffer=[];for(let EA=0;EA<6;EA++)if(u.mipmaps&&u.mipmaps.length>0){M.__webglFramebuffer[EA]=[];for(let bA=0;bA<u.mipmaps.length;bA++)M.__webglFramebuffer[EA][bA]=t.createFramebuffer()}else M.__webglFramebuffer[EA]=t.createFramebuffer()}else{if(u.mipmaps&&u.mipmaps.length>0){M.__webglFramebuffer=[];for(let EA=0;EA<u.mipmaps.length;EA++)M.__webglFramebuffer[EA]=t.createFramebuffer()}else M.__webglFramebuffer=t.createFramebuffer();if(kA)for(let EA=0,bA=gA.length;EA<bA;EA++){const UA=g.get(gA[EA]);UA.__webglTexture===void 0&&(UA.__webglTexture=t.createTexture(),C.memory.textures++)}if(b.samples>0&&He(b)===!1){M.__webglMultisampledFramebuffer=t.createFramebuffer(),M.__webglColorRenderbuffer=[],e.bindFramebuffer(t.FRAMEBUFFER,M.__webglMultisampledFramebuffer);for(let EA=0;EA<gA.length;EA++){const bA=gA[EA];M.__webglColorRenderbuffer[EA]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,M.__webglColorRenderbuffer[EA]);const UA=I.convert(bA.format,bA.colorSpace),CA=I.convert(bA.type),cA=_(bA.internalFormat,UA,CA,bA.colorSpace,b.isXRRenderTarget===!0),mA=R(b);t.renderbufferStorageMultisample(t.RENDERBUFFER,mA,cA,b.width,b.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+EA,t.RENDERBUFFER,M.__webglColorRenderbuffer[EA])}t.bindRenderbuffer(t.RENDERBUFFER,null),b.depthBuffer&&(M.__webglDepthRenderbuffer=t.createRenderbuffer(),TA(M.__webglDepthRenderbuffer,b,!0)),e.bindFramebuffer(t.FRAMEBUFFER,null)}}if(V){e.bindTexture(t.TEXTURE_CUBE_MAP,X.__webglTexture),JA(t.TEXTURE_CUBE_MAP,u);for(let EA=0;EA<6;EA++)if(u.mipmaps&&u.mipmaps.length>0)for(let bA=0;bA<u.mipmaps.length;bA++)wA(M.__webglFramebuffer[EA][bA],b,u,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+EA,bA);else wA(M.__webglFramebuffer[EA],b,u,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+EA,0);h(u)&&r(t.TEXTURE_CUBE_MAP),e.unbindTexture()}else if(kA){for(let EA=0,bA=gA.length;EA<bA;EA++){const UA=gA[EA],CA=g.get(UA);let cA=t.TEXTURE_2D;(b.isWebGL3DRenderTarget||b.isWebGLArrayRenderTarget)&&(cA=b.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),e.bindTexture(cA,CA.__webglTexture),JA(cA,UA),wA(M.__webglFramebuffer,b,UA,t.COLOR_ATTACHMENT0+EA,cA,0),h(UA)&&r(cA)}e.unbindTexture()}else{let EA=t.TEXTURE_2D;if((b.isWebGL3DRenderTarget||b.isWebGLArrayRenderTarget)&&(EA=b.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),e.bindTexture(EA,X.__webglTexture),JA(EA,u),u.mipmaps&&u.mipmaps.length>0)for(let bA=0;bA<u.mipmaps.length;bA++)wA(M.__webglFramebuffer[bA],b,u,t.COLOR_ATTACHMENT0,EA,bA);else wA(M.__webglFramebuffer,b,u,t.COLOR_ATTACHMENT0,EA,0);h(u)&&r(EA),e.unbindTexture()}b.depthBuffer&&Qe(b)}function ce(b){const u=b.textures;for(let M=0,X=u.length;M<X;M++){const gA=u[M];if(h(gA)){const V=f(b),kA=g.get(gA).__webglTexture;e.bindTexture(V,kA),r(V),e.unbindTexture()}}}const De=[],OA=[];function qe(b){if(b.samples>0){if(He(b)===!1){const u=b.textures,M=b.width,X=b.height;let gA=t.COLOR_BUFFER_BIT;const V=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,kA=g.get(b),EA=u.length>1;if(EA)for(let UA=0;UA<u.length;UA++)e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.RENDERBUFFER,null),e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.TEXTURE_2D,null,0);e.bindFramebuffer(t.READ_FRAMEBUFFER,kA.__webglMultisampledFramebuffer);const bA=b.texture.mipmaps;bA&&bA.length>0?e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglFramebuffer[0]):e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglFramebuffer);for(let UA=0;UA<u.length;UA++){if(b.resolveDepthBuffer&&(b.depthBuffer&&(gA|=t.DEPTH_BUFFER_BIT),b.stencilBuffer&&b.resolveStencilBuffer&&(gA|=t.STENCIL_BUFFER_BIT)),EA){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,kA.__webglColorRenderbuffer[UA]);const CA=g.get(u[UA]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,CA,0)}t.blitFramebuffer(0,0,M,X,0,0,M,X,gA,t.NEAREST),a===!0&&(De.length=0,OA.length=0,De.push(t.COLOR_ATTACHMENT0+UA),b.depthBuffer&&b.resolveDepthBuffer===!1&&(De.push(V),OA.push(V),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,OA)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,De))}if(e.bindFramebuffer(t.READ_FRAMEBUFFER,null),e.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),EA)for(let UA=0;UA<u.length;UA++){e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.RENDERBUFFER,kA.__webglColorRenderbuffer[UA]);const CA=g.get(u[UA]).__webglTexture;e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.TEXTURE_2D,CA,0)}e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglMultisampledFramebuffer)}else if(b.depthBuffer&&b.resolveDepthBuffer===!1&&a){const u=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[u])}}}function R(b){return Math.min(i.maxSamples,b.samples)}function He(b){const u=g.get(b);return b.samples>0&&A.has("WEBGL_multisampled_render_to_texture")===!0&&u.__useRenderToTexture!==!1}function Ee(b){const u=C.render.frame;n.get(b)!==u&&(n.set(b,u),b.update())}function we(b,u){const M=b.colorSpace,X=b.format,gA=b.type;return b.isCompressedTexture===!0||b.isVideoTexture===!0||M!==sI&&M!==ii&&(Ce.getTransfer(M)===re?(X!==Hg||gA!==Sg)&&LA("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ae("WebGLTextures: Unsupported texture color space:",M)),u}function NA(b){return typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement?(Q.width=b.naturalWidth||b.width,Q.height=b.naturalHeight||b.height):typeof VideoFrame<"u"&&b instanceof VideoFrame?(Q.width=b.displayWidth,Q.height=b.displayHeight):(Q.width=b.width,Q.height=b.height),Q}this.allocateTextureUnit=K,this.resetTextureUnits=U,this.setTexture2D=j,this.setTexture2DArray=H,this.setTexture3D=O,this.setTextureCube=z,this.rebindTextures=Ze,this.setupRenderTarget=oe,this.updateRenderTargetMipmap=ce,this.updateMultisampleRenderTarget=qe,this.setupDepthRenderbuffer=Qe,this.setupFrameBufferTexture=wA,this.useMultisampledRTT=He,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function lw(t,A){function e(g,i=ii){let I;const C=Ce.getTransfer(i);if(g===Sg)return t.UNSIGNED_BYTE;if(g===ZQ)return t.UNSIGNED_SHORT_4_4_4_4;if(g===zQ)return t.UNSIGNED_SHORT_5_5_5_1;if(g===e0)return t.UNSIGNED_INT_5_9_9_9_REV;if(g===g0)return t.UNSIGNED_INT_10F_11F_11F_REV;if(g===$r)return t.BYTE;if(g===A0)return t.SHORT;if(g===IC)return t.UNSIGNED_SHORT;if(g===XQ)return t.INT;if(g===at)return t.UNSIGNED_INT;if(g===Qt)return t.FLOAT;if(g===Rt)return t.HALF_FLOAT;if(g===t0)return t.ALPHA;if(g===i0)return t.RGB;if(g===Hg)return t.RGBA;if(g===Gt)return t.DEPTH_COMPONENT;if(g===bi)return t.DEPTH_STENCIL;if(g===I0)return t.RED;if(g===$Q)return t.RED_INTEGER;if(g===nI)return t.RG;if(g===An)return t.RG_INTEGER;if(g===en)return t.RGBA_INTEGER;if(g===co||g===ho||g===xo||g===lo)if(C===re)if(I=A.get("WEBGL_compressed_texture_s3tc_srgb"),I!==null){if(g===co)return I.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(g===ho)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(g===xo)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(g===lo)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(I=A.get("WEBGL_compressed_texture_s3tc"),I!==null){if(g===co)return I.COMPRESSED_RGB_S3TC_DXT1_EXT;if(g===ho)return I.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(g===xo)return I.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(g===lo)return I.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(g===gn||g===tn||g===In||g===Cn)if(I=A.get("WEBGL_compressed_texture_pvrtc"),I!==null){if(g===gn)return I.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(g===tn)return I.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(g===In)return I.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(g===Cn)return I.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(g===on||g===an||g===Qn||g===nn||g===sn||g===Bn||g===En)if(I=A.get("WEBGL_compressed_texture_etc"),I!==null){if(g===on||g===an)return C===re?I.COMPRESSED_SRGB8_ETC2:I.COMPRESSED_RGB8_ETC2;if(g===Qn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:I.COMPRESSED_RGBA8_ETC2_EAC;if(g===nn)return I.COMPRESSED_R11_EAC;if(g===sn)return I.COMPRESSED_SIGNED_R11_EAC;if(g===Bn)return I.COMPRESSED_RG11_EAC;if(g===En)return I.COMPRESSED_SIGNED_RG11_EAC}else return null;if(g===rn||g===cn||g===hn||g===dn||g===xn||g===ln||g===fn||g===un||g===Dn||g===_n||g===wn||g===pn||g===mn||g===yn)if(I=A.get("WEBGL_compressed_texture_astc"),I!==null){if(g===rn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:I.COMPRESSED_RGBA_ASTC_4x4_KHR;if(g===cn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:I.COMPRESSED_RGBA_ASTC_5x4_KHR;if(g===hn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:I.COMPRESSED_RGBA_ASTC_5x5_KHR;if(g===dn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:I.COMPRESSED_RGBA_ASTC_6x5_KHR;if(g===xn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:I.COMPRESSED_RGBA_ASTC_6x6_KHR;if(g===ln)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:I.COMPRESSED_RGBA_ASTC_8x5_KHR;if(g===fn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:I.COMPRESSED_RGBA_ASTC_8x6_KHR;if(g===un)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:I.COMPRESSED_RGBA_ASTC_8x8_KHR;if(g===Dn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:I.COMPRESSED_RGBA_ASTC_10x5_KHR;if(g===_n)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:I.COMPRESSED_RGBA_ASTC_10x6_KHR;if(g===wn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:I.COMPRESSED_RGBA_ASTC_10x8_KHR;if(g===pn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:I.COMPRESSED_RGBA_ASTC_10x10_KHR;if(g===mn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:I.COMPRESSED_RGBA_ASTC_12x10_KHR;if(g===yn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:I.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(g===bn||g===Nn||g===Sn)if(I=A.get("EXT_texture_compression_bptc"),I!==null){if(g===bn)return C===re?I.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:I.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(g===Nn)return I.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(g===Sn)return I.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(g===kn||g===Rn||g===Gn||g===Mn)if(I=A.get("EXT_texture_compression_rgtc"),I!==null){if(g===kn)return I.COMPRESSED_RED_RGTC1_EXT;if(g===Rn)return I.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(g===Gn)return I.COMPRESSED_RED_GREEN_RGTC2_EXT;if(g===Mn)return I.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return g===CC?t.UNSIGNED_INT_24_8:t[g]!==void 0?t[g]:null}return{convert:e}}const fw=`
|
|
4141
|
+
}`,Ew=[new J(1,0,0),new J(-1,0,0),new J(0,1,0),new J(0,-1,0),new J(0,0,1),new J(0,0,-1)],rw=[new J(0,-1,0),new J(0,-1,0),new J(0,0,1),new J(0,0,-1),new J(0,-1,0),new J(0,-1,0)],cc=new Ye,fC=new J,fs=new J;function cw(t,A,e){let g=new K0;const i=new Be,I=new Be,C=new Ke,o=new nu,a=new su,Q={},n=e.maxTextureSize,s={[bt]:tg,[tg]:bt,[Nt]:Nt},B=new Gg({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Be},radius:{value:4}},vertexShader:sw,fragmentShader:Bw}),E=B.clone();E.defines.HORIZONTAL_PASS=1;const d=new Wg;d.setAttribute("position",new Bt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const c=new Xg(d,B),h=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Bo;let r=this.type;this.render=function(p,y,k){if(h.enabled===!1||h.autoUpdate===!1&&h.needsUpdate===!1||p.length===0)return;p.type===zl&&(LA("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),p.type=Bo);const x=t.getRenderTarget(),w=t.getActiveCubeFace(),N=t.getActiveMipmapLevel(),U=t.state;U.setBlending(St),U.buffers.depth.getReversed()===!0?U.buffers.color.setClear(0,0,0,0):U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const K=r!==this.type;K&&y.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(j=>j.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,j=p.length;P<j;P++){const H=p[P],O=H.shadow;if(O===void 0){LA("WebGLShadowMap:",H,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;i.copy(O.mapSize);const z=O.getFrameExtents();if(i.multiply(z),I.copy(O.mapSize),(i.x>n||i.y>n)&&(i.x>n&&(I.x=Math.floor(n/z.x),i.x=I.x*z.x,O.mapSize.x=I.x),i.y>n&&(I.y=Math.floor(n/z.y),i.y=I.y*z.y,O.mapSize.y=I.y)),O.map===null||K===!0){if(O.map!==null&&(O.map.depthTexture!==null&&(O.map.depthTexture.dispose(),O.map.depthTexture=null),O.map.dispose()),this.type===iC){if(H.isPointLight){LA("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new st(i.x,i.y,{format:nI,type:Rt,minFilter:Ag,magFilter:Ag,generateMipmaps:!1}),O.map.texture.name=H.name+".shadowMap",O.map.depthTexture=new dC(i.x,i.y,Qt),O.map.depthTexture.name=H.name+".shadowMapDepth",O.map.depthTexture.format=Gt,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=$e,O.map.depthTexture.magFilter=$e}else{H.isPointLight?(O.map=new L0(i.x),O.map.depthTexture=new au(i.x,at)):(O.map=new st(i.x,i.y),O.map.depthTexture=new dC(i.x,i.y,at)),O.map.depthTexture.name=H.name+".shadowMap",O.map.depthTexture.format=Gt;const sA=t.state.buffers.depth.getReversed();this.type===Bo?(O.map.depthTexture.compareFunction=sA?Un:Fn,O.map.depthTexture.minFilter=Ag,O.map.depthTexture.magFilter=Ag):(O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=$e,O.map.depthTexture.magFilter=$e)}O.camera.updateProjectionMatrix()}const xA=O.map.isWebGLCubeRenderTarget?6:1;for(let sA=0;sA<xA;sA++){if(O.map.isWebGLCubeRenderTarget)t.setRenderTarget(O.map,sA),t.clear();else{sA===0&&(t.setRenderTarget(O.map),t.clear());const fA=O.getViewport(sA);C.set(I.x*fA.x,I.y*fA.y,I.x*fA.z,I.y*fA.w),U.viewport(C)}if(H.isPointLight){const fA=O.camera,JA=O.matrix,vA=H.distance||fA.far;vA!==fA.far&&(fA.far=vA,fA.updateProjectionMatrix()),fC.setFromMatrixPosition(H.matrixWorld),fA.position.copy(fC),fs.copy(fA.position),fs.add(Ew[sA]),fA.up.copy(rw[sA]),fA.lookAt(fs),fA.updateMatrixWorld(),JA.makeTranslation(-fC.x,-fC.y,-fC.z),cc.multiplyMatrices(fA.projectionMatrix,fA.matrixWorldInverse),O._frustum.setFromProjectionMatrix(cc,fA.coordinateSystem,fA.reversedDepth)}else O.updateMatrices(H);g=O.getFrustum(),l(y,k,O.camera,H,this.type)}O.isPointLightShadow!==!0&&this.type===iC&&f(O,k),O.needsUpdate=!1}r=this.type,h.needsUpdate=!1,t.setRenderTarget(x,w,N)};function f(p,y){const k=A.update(c);B.defines.VSM_SAMPLES!==p.blurSamples&&(B.defines.VSM_SAMPLES=p.blurSamples,E.defines.VSM_SAMPLES=p.blurSamples,B.needsUpdate=!0,E.needsUpdate=!0),p.mapPass===null&&(p.mapPass=new st(i.x,i.y,{format:nI,type:Rt})),B.uniforms.shadow_pass.value=p.map.depthTexture,B.uniforms.resolution.value=p.mapSize,B.uniforms.radius.value=p.radius,t.setRenderTarget(p.mapPass),t.clear(),t.renderBufferDirect(y,null,k,B,c,null),E.uniforms.shadow_pass.value=p.mapPass.texture,E.uniforms.resolution.value=p.mapSize,E.uniforms.radius.value=p.radius,t.setRenderTarget(p.map),t.clear(),t.renderBufferDirect(y,null,k,E,c,null)}function _(p,y,k,x){let w=null;const N=k.isPointLight===!0?p.customDistanceMaterial:p.customDepthMaterial;if(N!==void 0)w=N;else if(w=k.isPointLight===!0?a:o,t.localClippingEnabled&&y.clipShadows===!0&&Array.isArray(y.clippingPlanes)&&y.clippingPlanes.length!==0||y.displacementMap&&y.displacementScale!==0||y.alphaMap&&y.alphaTest>0||y.map&&y.alphaTest>0||y.alphaToCoverage===!0){const U=w.uuid,K=y.uuid;let P=Q[U];P===void 0&&(P={},Q[U]=P);let j=P[K];j===void 0&&(j=w.clone(),P[K]=j,y.addEventListener("dispose",D)),w=j}if(w.visible=y.visible,w.wireframe=y.wireframe,x===iC?w.side=y.shadowSide!==null?y.shadowSide:y.side:w.side=y.shadowSide!==null?y.shadowSide:s[y.side],w.alphaMap=y.alphaMap,w.alphaTest=y.alphaToCoverage===!0?.5:y.alphaTest,w.map=y.map,w.clipShadows=y.clipShadows,w.clippingPlanes=y.clippingPlanes,w.clipIntersection=y.clipIntersection,w.displacementMap=y.displacementMap,w.displacementScale=y.displacementScale,w.displacementBias=y.displacementBias,w.wireframeLinewidth=y.wireframeLinewidth,w.linewidth=y.linewidth,k.isPointLight===!0&&w.isMeshDistanceMaterial===!0){const U=t.properties.get(w);U.light=k}return w}function l(p,y,k,x,w){if(p.visible===!1)return;if(p.layers.test(y.layers)&&(p.isMesh||p.isLine||p.isPoints)&&(p.castShadow||p.receiveShadow&&w===iC)&&(!p.frustumCulled||g.intersectsObject(p))){p.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,p.matrixWorld);const K=A.update(p),P=p.material;if(Array.isArray(P)){const j=K.groups;for(let H=0,O=j.length;H<O;H++){const z=j[H],xA=P[z.materialIndex];if(xA&&xA.visible){const sA=_(p,xA,x,w);p.onBeforeShadow(t,p,y,k,K,sA,z),t.renderBufferDirect(k,null,K,sA,p,z),p.onAfterShadow(t,p,y,k,K,sA,z)}}}else if(P.visible){const j=_(p,P,x,w);p.onBeforeShadow(t,p,y,k,K,j,null),t.renderBufferDirect(k,null,K,j,p,null),p.onAfterShadow(t,p,y,k,K,j,null)}}const U=p.children;for(let K=0,P=U.length;K<P;K++)l(U[K],y,k,x,w)}function D(p){p.target.removeEventListener("dispose",D);for(const k in Q){const x=Q[k],w=p.target.uuid;w in x&&(x[w].dispose(),delete x[w])}}}const hw={[KQ]:vQ,[JQ]:qQ,[YQ]:HQ,[aI]:TQ,[vQ]:KQ,[qQ]:JQ,[HQ]:YQ,[TQ]:aI};function dw(t,A){function e(){let G=!1;const uA=new Ke;let aA=null;const DA=new Ke(0,0,0,0);return{setMask:function(IA){aA!==IA&&!G&&(t.colorMask(IA,IA,IA,IA),aA=IA)},setLocked:function(IA){G=IA},setClear:function(IA,eA,BA,KA,pe){pe===!0&&(IA*=KA,eA*=KA,BA*=KA),uA.set(IA,eA,BA,KA),DA.equals(uA)===!1&&(t.clearColor(IA,eA,BA,KA),DA.copy(uA))},reset:function(){G=!1,aA=null,DA.set(-1,0,0,0)}}}function g(){let G=!1,uA=!1,aA=null,DA=null,IA=null;return{setReversed:function(eA){if(uA!==eA){const BA=A.get("EXT_clip_control");eA?BA.clipControlEXT(BA.LOWER_LEFT_EXT,BA.ZERO_TO_ONE_EXT):BA.clipControlEXT(BA.LOWER_LEFT_EXT,BA.NEGATIVE_ONE_TO_ONE_EXT),uA=eA;const KA=IA;IA=null,this.setClear(KA)}},getReversed:function(){return uA},setTest:function(eA){eA?iA(t.DEPTH_TEST):wA(t.DEPTH_TEST)},setMask:function(eA){aA!==eA&&!G&&(t.depthMask(eA),aA=eA)},setFunc:function(eA){if(uA&&(eA=hw[eA]),DA!==eA){switch(eA){case KQ:t.depthFunc(t.NEVER);break;case vQ:t.depthFunc(t.ALWAYS);break;case JQ:t.depthFunc(t.LESS);break;case aI:t.depthFunc(t.LEQUAL);break;case YQ:t.depthFunc(t.EQUAL);break;case TQ:t.depthFunc(t.GEQUAL);break;case qQ:t.depthFunc(t.GREATER);break;case HQ:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}DA=eA}},setLocked:function(eA){G=eA},setClear:function(eA){IA!==eA&&(uA&&(eA=1-eA),t.clearDepth(eA),IA=eA)},reset:function(){G=!1,aA=null,DA=null,IA=null,uA=!1}}}function i(){let G=!1,uA=null,aA=null,DA=null,IA=null,eA=null,BA=null,KA=null,pe=null;return{setTest:function(he){G||(he?iA(t.STENCIL_TEST):wA(t.STENCIL_TEST))},setMask:function(he){uA!==he&&!G&&(t.stencilMask(he),uA=he)},setFunc:function(he,ht,Yt){(aA!==he||DA!==ht||IA!==Yt)&&(t.stencilFunc(he,ht,Yt),aA=he,DA=ht,IA=Yt)},setOp:function(he,ht,Yt){(eA!==he||BA!==ht||KA!==Yt)&&(t.stencilOp(he,ht,Yt),eA=he,BA=ht,KA=Yt)},setLocked:function(he){G=he},setClear:function(he){pe!==he&&(t.clearStencil(he),pe=he)},reset:function(){G=!1,uA=null,aA=null,DA=null,IA=null,eA=null,BA=null,KA=null,pe=null}}}const I=new e,C=new g,o=new i,a=new WeakMap,Q=new WeakMap;let n={},s={},B=new WeakMap,E=[],d=null,c=!1,h=null,r=null,f=null,_=null,l=null,D=null,p=null,y=new Ie(0,0,0),k=0,x=!1,w=null,N=null,U=null,K=null,P=null;const j=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,O=0;const z=t.getParameter(t.VERSION);z.indexOf("WebGL")!==-1?(O=parseFloat(/^WebGL (\d)/.exec(z)[1]),H=O>=1):z.indexOf("OpenGL ES")!==-1&&(O=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),H=O>=2);let xA=null,sA={};const fA=t.getParameter(t.SCISSOR_BOX),JA=t.getParameter(t.VIEWPORT),vA=new Ke().fromArray(fA),be=new Ke().fromArray(JA);function le(G,uA,aA,DA){const IA=new Uint8Array(4),eA=t.createTexture();t.bindTexture(G,eA),t.texParameteri(G,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(G,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let BA=0;BA<aA;BA++)G===t.TEXTURE_3D||G===t.TEXTURE_2D_ARRAY?t.texImage3D(uA,0,t.RGBA,1,1,DA,0,t.RGBA,t.UNSIGNED_BYTE,IA):t.texImage2D(uA+BA,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,IA);return eA}const Z={};Z[t.TEXTURE_2D]=le(t.TEXTURE_2D,t.TEXTURE_2D,1),Z[t.TEXTURE_CUBE_MAP]=le(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),Z[t.TEXTURE_2D_ARRAY]=le(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),Z[t.TEXTURE_3D]=le(t.TEXTURE_3D,t.TEXTURE_3D,1,1),I.setClear(0,0,0,1),C.setClear(1),o.setClear(0),iA(t.DEPTH_TEST),C.setFunc(aI),OA(!1),qe(Yr),iA(t.CULL_FACE),ce(St);function iA(G){n[G]!==!0&&(t.enable(G),n[G]=!0)}function wA(G){n[G]!==!1&&(t.disable(G),n[G]=!1)}function TA(G,uA){return s[G]!==uA?(t.bindFramebuffer(G,uA),s[G]=uA,G===t.DRAW_FRAMEBUFFER&&(s[t.FRAMEBUFFER]=uA),G===t.FRAMEBUFFER&&(s[t.DRAW_FRAMEBUFFER]=uA),!0):!1}function yA(G,uA){let aA=E,DA=!1;if(G){aA=B.get(uA),aA===void 0&&(aA=[],B.set(uA,aA));const IA=G.textures;if(aA.length!==IA.length||aA[0]!==t.COLOR_ATTACHMENT0){for(let eA=0,BA=IA.length;eA<BA;eA++)aA[eA]=t.COLOR_ATTACHMENT0+eA;aA.length=IA.length,DA=!0}}else aA[0]!==t.BACK&&(aA[0]=t.BACK,DA=!0);DA&&t.drawBuffers(aA)}function Qe(G){return d!==G?(t.useProgram(G),d=G,!0):!1}const Ze={[mi]:t.FUNC_ADD,[Af]:t.FUNC_SUBTRACT,[ef]:t.FUNC_REVERSE_SUBTRACT};Ze[gf]=t.MIN,Ze[tf]=t.MAX;const oe={[If]:t.ZERO,[Cf]:t.ONE,[of]:t.SRC_COLOR,[UQ]:t.SRC_ALPHA,[Ef]:t.SRC_ALPHA_SATURATE,[sf]:t.DST_COLOR,[Qf]:t.DST_ALPHA,[af]:t.ONE_MINUS_SRC_COLOR,[LQ]:t.ONE_MINUS_SRC_ALPHA,[Bf]:t.ONE_MINUS_DST_COLOR,[nf]:t.ONE_MINUS_DST_ALPHA,[rf]:t.CONSTANT_COLOR,[cf]:t.ONE_MINUS_CONSTANT_COLOR,[hf]:t.CONSTANT_ALPHA,[df]:t.ONE_MINUS_CONSTANT_ALPHA};function ce(G,uA,aA,DA,IA,eA,BA,KA,pe,he){if(G===St){c===!0&&(wA(t.BLEND),c=!1);return}if(c===!1&&(iA(t.BLEND),c=!0),G!==$l){if(G!==h||he!==x){if((r!==mi||l!==mi)&&(t.blendEquation(t.FUNC_ADD),r=mi,l=mi),he)switch(G){case oI:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FQ:t.blendFunc(t.ONE,t.ONE);break;case Tr:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case qr:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:ae("WebGLState: Invalid blending: ",G);break}else switch(G){case oI:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FQ:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case Tr:ae("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case qr:ae("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ae("WebGLState: Invalid blending: ",G);break}f=null,_=null,D=null,p=null,y.set(0,0,0),k=0,h=G,x=he}return}IA=IA||uA,eA=eA||aA,BA=BA||DA,(uA!==r||IA!==l)&&(t.blendEquationSeparate(Ze[uA],Ze[IA]),r=uA,l=IA),(aA!==f||DA!==_||eA!==D||BA!==p)&&(t.blendFuncSeparate(oe[aA],oe[DA],oe[eA],oe[BA]),f=aA,_=DA,D=eA,p=BA),(KA.equals(y)===!1||pe!==k)&&(t.blendColor(KA.r,KA.g,KA.b,pe),y.copy(KA),k=pe),h=G,x=!1}function De(G,uA){G.side===Nt?wA(t.CULL_FACE):iA(t.CULL_FACE);let aA=G.side===tg;uA&&(aA=!aA),OA(aA),G.blending===oI&&G.transparent===!1?ce(St):ce(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.blendColor,G.blendAlpha,G.premultipliedAlpha),C.setFunc(G.depthFunc),C.setTest(G.depthTest),C.setMask(G.depthWrite),I.setMask(G.colorWrite);const DA=G.stencilWrite;o.setTest(DA),DA&&(o.setMask(G.stencilWriteMask),o.setFunc(G.stencilFunc,G.stencilRef,G.stencilFuncMask),o.setOp(G.stencilFail,G.stencilZFail,G.stencilZPass)),He(G.polygonOffset,G.polygonOffsetFactor,G.polygonOffsetUnits),G.alphaToCoverage===!0?iA(t.SAMPLE_ALPHA_TO_COVERAGE):wA(t.SAMPLE_ALPHA_TO_COVERAGE)}function OA(G){w!==G&&(G?t.frontFace(t.CW):t.frontFace(t.CCW),w=G)}function qe(G){G!==Xl?(iA(t.CULL_FACE),G!==N&&(G===Yr?t.cullFace(t.BACK):G===Zl?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):wA(t.CULL_FACE),N=G}function R(G){G!==U&&(H&&t.lineWidth(G),U=G)}function He(G,uA,aA){G?(iA(t.POLYGON_OFFSET_FILL),(K!==uA||P!==aA)&&(t.polygonOffset(uA,aA),K=uA,P=aA)):wA(t.POLYGON_OFFSET_FILL)}function Ee(G){G?iA(t.SCISSOR_TEST):wA(t.SCISSOR_TEST)}function we(G){G===void 0&&(G=t.TEXTURE0+j-1),xA!==G&&(t.activeTexture(G),xA=G)}function NA(G,uA,aA){aA===void 0&&(xA===null?aA=t.TEXTURE0+j-1:aA=xA);let DA=sA[aA];DA===void 0&&(DA={type:void 0,texture:void 0},sA[aA]=DA),(DA.type!==G||DA.texture!==uA)&&(xA!==aA&&(t.activeTexture(aA),xA=aA),t.bindTexture(G,uA||Z[G]),DA.type=G,DA.texture=uA)}function b(){const G=sA[xA];G!==void 0&&G.type!==void 0&&(t.bindTexture(G.type,null),G.type=void 0,G.texture=void 0)}function u(){try{t.compressedTexImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function M(){try{t.compressedTexImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function X(){try{t.texSubImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function gA(){try{t.texSubImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function V(){try{t.compressedTexSubImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function kA(){try{t.compressedTexSubImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function EA(){try{t.texStorage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function bA(){try{t.texStorage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function UA(){try{t.texImage2D(...arguments)}catch(G){ae("WebGLState:",G)}}function CA(){try{t.texImage3D(...arguments)}catch(G){ae("WebGLState:",G)}}function cA(G){vA.equals(G)===!1&&(t.scissor(G.x,G.y,G.z,G.w),vA.copy(G))}function mA(G){be.equals(G)===!1&&(t.viewport(G.x,G.y,G.z,G.w),be.copy(G))}function SA(G,uA){let aA=Q.get(uA);aA===void 0&&(aA=new WeakMap,Q.set(uA,aA));let DA=aA.get(G);DA===void 0&&(DA=t.getUniformBlockIndex(uA,G.name),aA.set(G,DA))}function rA(G,uA){const DA=Q.get(uA).get(G);a.get(uA)!==DA&&(t.uniformBlockBinding(uA,DA,G.__bindingPointIndex),a.set(uA,DA))}function VA(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),C.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),n={},xA=null,sA={},s={},B=new WeakMap,E=[],d=null,c=!1,h=null,r=null,f=null,_=null,l=null,D=null,p=null,y=new Ie(0,0,0),k=0,x=!1,w=null,N=null,U=null,K=null,P=null,vA.set(0,0,t.canvas.width,t.canvas.height),be.set(0,0,t.canvas.width,t.canvas.height),I.reset(),C.reset(),o.reset()}return{buffers:{color:I,depth:C,stencil:o},enable:iA,disable:wA,bindFramebuffer:TA,drawBuffers:yA,useProgram:Qe,setBlending:ce,setMaterial:De,setFlipSided:OA,setCullFace:qe,setLineWidth:R,setPolygonOffset:He,setScissorTest:Ee,activeTexture:we,bindTexture:NA,unbindTexture:b,compressedTexImage2D:u,compressedTexImage3D:M,texImage2D:UA,texImage3D:CA,updateUBOMapping:SA,uniformBlockBinding:rA,texStorage2D:EA,texStorage3D:bA,texSubImage2D:X,texSubImage3D:gA,compressedTexSubImage2D:V,compressedTexSubImage3D:kA,scissor:cA,viewport:mA,reset:VA}}function xw(t,A,e,g,i,I,C){const o=A.has("WEBGL_multisampled_render_to_texture")?A.get("WEBGL_multisampled_render_to_texture"):null,a=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),Q=new Be,n=new WeakMap;let s;const B=new WeakMap;let E=!1;try{E=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function d(b,u){return E?new OffscreenCanvas(b,u):Do("canvas")}function c(b,u,M){let X=1;const gA=NA(b);if((gA.width>M||gA.height>M)&&(X=M/Math.max(gA.width,gA.height)),X<1)if(typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&b instanceof ImageBitmap||typeof VideoFrame<"u"&&b instanceof VideoFrame){const V=Math.floor(X*gA.width),kA=Math.floor(X*gA.height);s===void 0&&(s=d(V,kA));const EA=u?d(V,kA):s;return EA.width=V,EA.height=kA,EA.getContext("2d").drawImage(b,0,0,V,kA),LA("WebGLRenderer: Texture has been resized from ("+gA.width+"x"+gA.height+") to ("+V+"x"+kA+")."),EA}else return"data"in b&&LA("WebGLRenderer: Image in DataTexture is too big ("+gA.width+"x"+gA.height+")."),b;return b}function h(b){return b.generateMipmaps}function r(b){t.generateMipmap(b)}function f(b){return b.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:b.isWebGL3DRenderTarget?t.TEXTURE_3D:b.isWebGLArrayRenderTarget||b.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function _(b,u,M,X,gA=!1){if(b!==null){if(t[b]!==void 0)return t[b];LA("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+b+"'")}let V=u;if(u===t.RED&&(M===t.FLOAT&&(V=t.R32F),M===t.HALF_FLOAT&&(V=t.R16F),M===t.UNSIGNED_BYTE&&(V=t.R8)),u===t.RED_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.R8UI),M===t.UNSIGNED_SHORT&&(V=t.R16UI),M===t.UNSIGNED_INT&&(V=t.R32UI),M===t.BYTE&&(V=t.R8I),M===t.SHORT&&(V=t.R16I),M===t.INT&&(V=t.R32I)),u===t.RG&&(M===t.FLOAT&&(V=t.RG32F),M===t.HALF_FLOAT&&(V=t.RG16F),M===t.UNSIGNED_BYTE&&(V=t.RG8)),u===t.RG_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RG8UI),M===t.UNSIGNED_SHORT&&(V=t.RG16UI),M===t.UNSIGNED_INT&&(V=t.RG32UI),M===t.BYTE&&(V=t.RG8I),M===t.SHORT&&(V=t.RG16I),M===t.INT&&(V=t.RG32I)),u===t.RGB_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RGB8UI),M===t.UNSIGNED_SHORT&&(V=t.RGB16UI),M===t.UNSIGNED_INT&&(V=t.RGB32UI),M===t.BYTE&&(V=t.RGB8I),M===t.SHORT&&(V=t.RGB16I),M===t.INT&&(V=t.RGB32I)),u===t.RGBA_INTEGER&&(M===t.UNSIGNED_BYTE&&(V=t.RGBA8UI),M===t.UNSIGNED_SHORT&&(V=t.RGBA16UI),M===t.UNSIGNED_INT&&(V=t.RGBA32UI),M===t.BYTE&&(V=t.RGBA8I),M===t.SHORT&&(V=t.RGBA16I),M===t.INT&&(V=t.RGBA32I)),u===t.RGB&&(M===t.UNSIGNED_INT_5_9_9_9_REV&&(V=t.RGB9_E5),M===t.UNSIGNED_INT_10F_11F_11F_REV&&(V=t.R11F_G11F_B10F)),u===t.RGBA){const kA=gA?fo:Ce.getTransfer(X);M===t.FLOAT&&(V=t.RGBA32F),M===t.HALF_FLOAT&&(V=t.RGBA16F),M===t.UNSIGNED_BYTE&&(V=kA===re?t.SRGB8_ALPHA8:t.RGBA8),M===t.UNSIGNED_SHORT_4_4_4_4&&(V=t.RGBA4),M===t.UNSIGNED_SHORT_5_5_5_1&&(V=t.RGB5_A1)}return(V===t.R16F||V===t.R32F||V===t.RG16F||V===t.RG32F||V===t.RGBA16F||V===t.RGBA32F)&&A.get("EXT_color_buffer_float"),V}function l(b,u){let M;return b?u===null||u===at||u===CC?M=t.DEPTH24_STENCIL8:u===Qt?M=t.DEPTH32F_STENCIL8:u===IC&&(M=t.DEPTH24_STENCIL8,LA("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):u===null||u===at||u===CC?M=t.DEPTH_COMPONENT24:u===Qt?M=t.DEPTH_COMPONENT32F:u===IC&&(M=t.DEPTH_COMPONENT16),M}function D(b,u){return h(b)===!0||b.isFramebufferTexture&&b.minFilter!==$e&&b.minFilter!==Ag?Math.log2(Math.max(u.width,u.height))+1:b.mipmaps!==void 0&&b.mipmaps.length>0?b.mipmaps.length:b.isCompressedTexture&&Array.isArray(b.image)?u.mipmaps.length:1}function p(b){const u=b.target;u.removeEventListener("dispose",p),k(u),u.isVideoTexture&&n.delete(u)}function y(b){const u=b.target;u.removeEventListener("dispose",y),w(u)}function k(b){const u=g.get(b);if(u.__webglInit===void 0)return;const M=b.source,X=B.get(M);if(X){const gA=X[u.__cacheKey];gA.usedTimes--,gA.usedTimes===0&&x(b),Object.keys(X).length===0&&B.delete(M)}g.remove(b)}function x(b){const u=g.get(b);t.deleteTexture(u.__webglTexture);const M=b.source,X=B.get(M);delete X[u.__cacheKey],C.memory.textures--}function w(b){const u=g.get(b);if(b.depthTexture&&(b.depthTexture.dispose(),g.remove(b.depthTexture)),b.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(u.__webglFramebuffer[X]))for(let gA=0;gA<u.__webglFramebuffer[X].length;gA++)t.deleteFramebuffer(u.__webglFramebuffer[X][gA]);else t.deleteFramebuffer(u.__webglFramebuffer[X]);u.__webglDepthbuffer&&t.deleteRenderbuffer(u.__webglDepthbuffer[X])}else{if(Array.isArray(u.__webglFramebuffer))for(let X=0;X<u.__webglFramebuffer.length;X++)t.deleteFramebuffer(u.__webglFramebuffer[X]);else t.deleteFramebuffer(u.__webglFramebuffer);if(u.__webglDepthbuffer&&t.deleteRenderbuffer(u.__webglDepthbuffer),u.__webglMultisampledFramebuffer&&t.deleteFramebuffer(u.__webglMultisampledFramebuffer),u.__webglColorRenderbuffer)for(let X=0;X<u.__webglColorRenderbuffer.length;X++)u.__webglColorRenderbuffer[X]&&t.deleteRenderbuffer(u.__webglColorRenderbuffer[X]);u.__webglDepthRenderbuffer&&t.deleteRenderbuffer(u.__webglDepthRenderbuffer)}const M=b.textures;for(let X=0,gA=M.length;X<gA;X++){const V=g.get(M[X]);V.__webglTexture&&(t.deleteTexture(V.__webglTexture),C.memory.textures--),g.remove(M[X])}g.remove(b)}let N=0;function U(){N=0}function K(){const b=N;return b>=i.maxTextures&&LA("WebGLTextures: Trying to use "+b+" texture units while this GPU supports only "+i.maxTextures),N+=1,b}function P(b){const u=[];return u.push(b.wrapS),u.push(b.wrapT),u.push(b.wrapR||0),u.push(b.magFilter),u.push(b.minFilter),u.push(b.anisotropy),u.push(b.internalFormat),u.push(b.format),u.push(b.type),u.push(b.generateMipmaps),u.push(b.premultiplyAlpha),u.push(b.flipY),u.push(b.unpackAlignment),u.push(b.colorSpace),u.join()}function j(b,u){const M=g.get(b);if(b.isVideoTexture&&Ee(b),b.isRenderTargetTexture===!1&&b.isExternalTexture!==!0&&b.version>0&&M.__version!==b.version){const X=b.image;if(X===null)LA("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)LA("WebGLRenderer: Texture marked for update but image is incomplete");else{Z(M,b,u);return}}else b.isExternalTexture&&(M.__webglTexture=b.sourceTexture?b.sourceTexture:null);e.bindTexture(t.TEXTURE_2D,M.__webglTexture,t.TEXTURE0+u)}function H(b,u){const M=g.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&M.__version!==b.version){Z(M,b,u);return}else b.isExternalTexture&&(M.__webglTexture=b.sourceTexture?b.sourceTexture:null);e.bindTexture(t.TEXTURE_2D_ARRAY,M.__webglTexture,t.TEXTURE0+u)}function O(b,u){const M=g.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&M.__version!==b.version){Z(M,b,u);return}e.bindTexture(t.TEXTURE_3D,M.__webglTexture,t.TEXTURE0+u)}function z(b,u){const M=g.get(b);if(b.isCubeDepthTexture!==!0&&b.version>0&&M.__version!==b.version){iA(M,b,u);return}e.bindTexture(t.TEXTURE_CUBE_MAP,M.__webglTexture,t.TEXTURE0+u)}const xA={[VQ]:t.REPEAT,[kt]:t.CLAMP_TO_EDGE,[jQ]:t.MIRRORED_REPEAT},sA={[$e]:t.NEAREST,[ff]:t.NEAREST_MIPMAP_NEAREST,[ro]:t.NEAREST_MIPMAP_LINEAR,[Ag]:t.LINEAR,[WQ]:t.LINEAR_MIPMAP_NEAREST,[bi]:t.LINEAR_MIPMAP_LINEAR},fA={[wf]:t.NEVER,[Nf]:t.ALWAYS,[pf]:t.LESS,[Fn]:t.LEQUAL,[mf]:t.EQUAL,[Un]:t.GEQUAL,[yf]:t.GREATER,[bf]:t.NOTEQUAL};function JA(b,u){if(u.type===Qt&&A.has("OES_texture_float_linear")===!1&&(u.magFilter===Ag||u.magFilter===WQ||u.magFilter===ro||u.magFilter===bi||u.minFilter===Ag||u.minFilter===WQ||u.minFilter===ro||u.minFilter===bi)&&LA("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(b,t.TEXTURE_WRAP_S,xA[u.wrapS]),t.texParameteri(b,t.TEXTURE_WRAP_T,xA[u.wrapT]),(b===t.TEXTURE_3D||b===t.TEXTURE_2D_ARRAY)&&t.texParameteri(b,t.TEXTURE_WRAP_R,xA[u.wrapR]),t.texParameteri(b,t.TEXTURE_MAG_FILTER,sA[u.magFilter]),t.texParameteri(b,t.TEXTURE_MIN_FILTER,sA[u.minFilter]),u.compareFunction&&(t.texParameteri(b,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(b,t.TEXTURE_COMPARE_FUNC,fA[u.compareFunction])),A.has("EXT_texture_filter_anisotropic")===!0){if(u.magFilter===$e||u.minFilter!==ro&&u.minFilter!==bi||u.type===Qt&&A.has("OES_texture_float_linear")===!1)return;if(u.anisotropy>1||g.get(u).__currentAnisotropy){const M=A.get("EXT_texture_filter_anisotropic");t.texParameterf(b,M.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(u.anisotropy,i.getMaxAnisotropy())),g.get(u).__currentAnisotropy=u.anisotropy}}}function vA(b,u){let M=!1;b.__webglInit===void 0&&(b.__webglInit=!0,u.addEventListener("dispose",p));const X=u.source;let gA=B.get(X);gA===void 0&&(gA={},B.set(X,gA));const V=P(u);if(V!==b.__cacheKey){gA[V]===void 0&&(gA[V]={texture:t.createTexture(),usedTimes:0},C.memory.textures++,M=!0),gA[V].usedTimes++;const kA=gA[b.__cacheKey];kA!==void 0&&(gA[b.__cacheKey].usedTimes--,kA.usedTimes===0&&x(u)),b.__cacheKey=V,b.__webglTexture=gA[V].texture}return M}function be(b,u,M){return Math.floor(Math.floor(b/M)/u)}function le(b,u,M,X){const V=b.updateRanges;if(V.length===0)e.texSubImage2D(t.TEXTURE_2D,0,0,0,u.width,u.height,M,X,u.data);else{V.sort((CA,cA)=>CA.start-cA.start);let kA=0;for(let CA=1;CA<V.length;CA++){const cA=V[kA],mA=V[CA],SA=cA.start+cA.count,rA=be(mA.start,u.width,4),VA=be(cA.start,u.width,4);mA.start<=SA+1&&rA===VA&&be(mA.start+mA.count-1,u.width,4)===rA?cA.count=Math.max(cA.count,mA.start+mA.count-cA.start):(++kA,V[kA]=mA)}V.length=kA+1;const EA=t.getParameter(t.UNPACK_ROW_LENGTH),bA=t.getParameter(t.UNPACK_SKIP_PIXELS),UA=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,u.width);for(let CA=0,cA=V.length;CA<cA;CA++){const mA=V[CA],SA=Math.floor(mA.start/4),rA=Math.ceil(mA.count/4),VA=SA%u.width,G=Math.floor(SA/u.width),uA=rA,aA=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,VA),t.pixelStorei(t.UNPACK_SKIP_ROWS,G),e.texSubImage2D(t.TEXTURE_2D,0,VA,G,uA,aA,M,X,u.data)}b.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,EA),t.pixelStorei(t.UNPACK_SKIP_PIXELS,bA),t.pixelStorei(t.UNPACK_SKIP_ROWS,UA)}}function Z(b,u,M){let X=t.TEXTURE_2D;(u.isDataArrayTexture||u.isCompressedArrayTexture)&&(X=t.TEXTURE_2D_ARRAY),u.isData3DTexture&&(X=t.TEXTURE_3D);const gA=vA(b,u),V=u.source;e.bindTexture(X,b.__webglTexture,t.TEXTURE0+M);const kA=g.get(V);if(V.version!==kA.__version||gA===!0){e.activeTexture(t.TEXTURE0+M);const EA=Ce.getPrimaries(Ce.workingColorSpace),bA=u.colorSpace===ii?null:Ce.getPrimaries(u.colorSpace),UA=u.colorSpace===ii||EA===bA?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,u.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,u.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,UA);let CA=c(u.image,!1,i.maxTextureSize);CA=we(u,CA);const cA=I.convert(u.format,u.colorSpace),mA=I.convert(u.type);let SA=_(u.internalFormat,cA,mA,u.colorSpace,u.isVideoTexture);JA(X,u);let rA;const VA=u.mipmaps,G=u.isVideoTexture!==!0,uA=kA.__version===void 0||gA===!0,aA=V.dataReady,DA=D(u,CA);if(u.isDepthTexture)SA=l(u.format===Ni,u.type),uA&&(G?e.texStorage2D(t.TEXTURE_2D,1,SA,CA.width,CA.height):e.texImage2D(t.TEXTURE_2D,0,SA,CA.width,CA.height,0,cA,mA,null));else if(u.isDataTexture)if(VA.length>0){G&&uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,VA[0].width,VA[0].height);for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,mA,rA.data):e.texImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,cA,mA,rA.data);u.generateMipmaps=!1}else G?(uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,CA.width,CA.height),aA&&le(u,CA,cA,mA)):e.texImage2D(t.TEXTURE_2D,0,SA,CA.width,CA.height,0,cA,mA,CA.data);else if(u.isCompressedTexture)if(u.isCompressedArrayTexture){G&&uA&&e.texStorage3D(t.TEXTURE_2D_ARRAY,DA,SA,VA[0].width,VA[0].height,CA.depth);for(let IA=0,eA=VA.length;IA<eA;IA++)if(rA=VA[IA],u.format!==Hg)if(cA!==null)if(G){if(aA)if(u.layerUpdates.size>0){const BA=Y0(rA.width,rA.height,u.format,u.type);for(const KA of u.layerUpdates){const pe=rA.data.subarray(KA*BA/rA.data.BYTES_PER_ELEMENT,(KA+1)*BA/rA.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,KA,rA.width,rA.height,1,cA,pe)}u.clearLayerUpdates()}else e.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,0,rA.width,rA.height,CA.depth,cA,rA.data)}else e.compressedTexImage3D(t.TEXTURE_2D_ARRAY,IA,SA,rA.width,rA.height,CA.depth,0,rA.data,0,0);else LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else G?aA&&e.texSubImage3D(t.TEXTURE_2D_ARRAY,IA,0,0,0,rA.width,rA.height,CA.depth,cA,mA,rA.data):e.texImage3D(t.TEXTURE_2D_ARRAY,IA,SA,rA.width,rA.height,CA.depth,0,cA,mA,rA.data)}else{G&&uA&&e.texStorage2D(t.TEXTURE_2D,DA,SA,VA[0].width,VA[0].height);for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],u.format!==Hg?cA!==null?G?aA&&e.compressedTexSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,rA.data):e.compressedTexImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,rA.data):LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,rA.width,rA.height,cA,mA,rA.data):e.texImage2D(t.TEXTURE_2D,IA,SA,rA.width,rA.height,0,cA,mA,rA.data)}else if(u.isDataArrayTexture)if(G){if(uA&&e.texStorage3D(t.TEXTURE_2D_ARRAY,DA,SA,CA.width,CA.height,CA.depth),aA)if(u.layerUpdates.size>0){const IA=Y0(CA.width,CA.height,u.format,u.type);for(const eA of u.layerUpdates){const BA=CA.data.subarray(eA*IA/CA.data.BYTES_PER_ELEMENT,(eA+1)*IA/CA.data.BYTES_PER_ELEMENT);e.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,eA,CA.width,CA.height,1,cA,mA,BA)}u.clearLayerUpdates()}else e.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,CA.width,CA.height,CA.depth,cA,mA,CA.data)}else e.texImage3D(t.TEXTURE_2D_ARRAY,0,SA,CA.width,CA.height,CA.depth,0,cA,mA,CA.data);else if(u.isData3DTexture)G?(uA&&e.texStorage3D(t.TEXTURE_3D,DA,SA,CA.width,CA.height,CA.depth),aA&&e.texSubImage3D(t.TEXTURE_3D,0,0,0,0,CA.width,CA.height,CA.depth,cA,mA,CA.data)):e.texImage3D(t.TEXTURE_3D,0,SA,CA.width,CA.height,CA.depth,0,cA,mA,CA.data);else if(u.isFramebufferTexture){if(uA)if(G)e.texStorage2D(t.TEXTURE_2D,DA,SA,CA.width,CA.height);else{let IA=CA.width,eA=CA.height;for(let BA=0;BA<DA;BA++)e.texImage2D(t.TEXTURE_2D,BA,SA,IA,eA,0,cA,mA,null),IA>>=1,eA>>=1}}else if(VA.length>0){if(G&&uA){const IA=NA(VA[0]);e.texStorage2D(t.TEXTURE_2D,DA,SA,IA.width,IA.height)}for(let IA=0,eA=VA.length;IA<eA;IA++)rA=VA[IA],G?aA&&e.texSubImage2D(t.TEXTURE_2D,IA,0,0,cA,mA,rA):e.texImage2D(t.TEXTURE_2D,IA,SA,cA,mA,rA);u.generateMipmaps=!1}else if(G){if(uA){const IA=NA(CA);e.texStorage2D(t.TEXTURE_2D,DA,SA,IA.width,IA.height)}aA&&e.texSubImage2D(t.TEXTURE_2D,0,0,0,cA,mA,CA)}else e.texImage2D(t.TEXTURE_2D,0,SA,cA,mA,CA);h(u)&&r(X),kA.__version=V.version,u.onUpdate&&u.onUpdate(u)}b.__version=u.version}function iA(b,u,M){if(u.image.length!==6)return;const X=vA(b,u),gA=u.source;e.bindTexture(t.TEXTURE_CUBE_MAP,b.__webglTexture,t.TEXTURE0+M);const V=g.get(gA);if(gA.version!==V.__version||X===!0){e.activeTexture(t.TEXTURE0+M);const kA=Ce.getPrimaries(Ce.workingColorSpace),EA=u.colorSpace===ii?null:Ce.getPrimaries(u.colorSpace),bA=u.colorSpace===ii||kA===EA?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,u.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,u.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,bA);const UA=u.isCompressedTexture||u.image[0].isCompressedTexture,CA=u.image[0]&&u.image[0].isDataTexture,cA=[];for(let eA=0;eA<6;eA++)!UA&&!CA?cA[eA]=c(u.image[eA],!0,i.maxCubemapSize):cA[eA]=CA?u.image[eA].image:u.image[eA],cA[eA]=we(u,cA[eA]);const mA=cA[0],SA=I.convert(u.format,u.colorSpace),rA=I.convert(u.type),VA=_(u.internalFormat,SA,rA,u.colorSpace),G=u.isVideoTexture!==!0,uA=V.__version===void 0||X===!0,aA=gA.dataReady;let DA=D(u,mA);JA(t.TEXTURE_CUBE_MAP,u);let IA;if(UA){G&&uA&&e.texStorage2D(t.TEXTURE_CUBE_MAP,DA,VA,mA.width,mA.height);for(let eA=0;eA<6;eA++){IA=cA[eA].mipmaps;for(let BA=0;BA<IA.length;BA++){const KA=IA[BA];u.format!==Hg?SA!==null?G?aA&&e.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,0,0,KA.width,KA.height,SA,KA.data):e.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,VA,KA.width,KA.height,0,KA.data):LA("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,0,0,KA.width,KA.height,SA,rA,KA.data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA,VA,KA.width,KA.height,0,SA,rA,KA.data)}}}else{if(IA=u.mipmaps,G&&uA){IA.length>0&&DA++;const eA=NA(cA[0]);e.texStorage2D(t.TEXTURE_CUBE_MAP,DA,VA,eA.width,eA.height)}for(let eA=0;eA<6;eA++)if(CA){G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,0,0,cA[eA].width,cA[eA].height,SA,rA,cA[eA].data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,VA,cA[eA].width,cA[eA].height,0,SA,rA,cA[eA].data);for(let BA=0;BA<IA.length;BA++){const pe=IA[BA].image[eA].image;G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,0,0,pe.width,pe.height,SA,rA,pe.data):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,VA,pe.width,pe.height,0,SA,rA,pe.data)}}else{G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,0,0,SA,rA,cA[eA]):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,0,VA,SA,rA,cA[eA]);for(let BA=0;BA<IA.length;BA++){const KA=IA[BA];G?aA&&e.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,0,0,SA,rA,KA.image[eA]):e.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+eA,BA+1,VA,SA,rA,KA.image[eA])}}}h(u)&&r(t.TEXTURE_CUBE_MAP),V.__version=gA.version,u.onUpdate&&u.onUpdate(u)}b.__version=u.version}function wA(b,u,M,X,gA,V){const kA=I.convert(M.format,M.colorSpace),EA=I.convert(M.type),bA=_(M.internalFormat,kA,EA,M.colorSpace),UA=g.get(u),CA=g.get(M);if(CA.__renderTarget=u,!UA.__hasExternalTextures){const cA=Math.max(1,u.width>>V),mA=Math.max(1,u.height>>V);gA===t.TEXTURE_3D||gA===t.TEXTURE_2D_ARRAY?e.texImage3D(gA,V,bA,cA,mA,u.depth,0,kA,EA,null):e.texImage2D(gA,V,bA,cA,mA,0,kA,EA,null)}e.bindFramebuffer(t.FRAMEBUFFER,b),He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,X,gA,CA.__webglTexture,0,R(u)):(gA===t.TEXTURE_2D||gA>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&gA<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,X,gA,CA.__webglTexture,V),e.bindFramebuffer(t.FRAMEBUFFER,null)}function TA(b,u,M){if(t.bindRenderbuffer(t.RENDERBUFFER,b),u.depthBuffer){const X=u.depthTexture,gA=X&&X.isDepthTexture?X.type:null,V=l(u.stencilBuffer,gA),kA=u.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;He(u)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,R(u),V,u.width,u.height):M?t.renderbufferStorageMultisample(t.RENDERBUFFER,R(u),V,u.width,u.height):t.renderbufferStorage(t.RENDERBUFFER,V,u.width,u.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,kA,t.RENDERBUFFER,b)}else{const X=u.textures;for(let gA=0;gA<X.length;gA++){const V=X[gA],kA=I.convert(V.format,V.colorSpace),EA=I.convert(V.type),bA=_(V.internalFormat,kA,EA,V.colorSpace);He(u)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,R(u),bA,u.width,u.height):M?t.renderbufferStorageMultisample(t.RENDERBUFFER,R(u),bA,u.width,u.height):t.renderbufferStorage(t.RENDERBUFFER,bA,u.width,u.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function yA(b,u,M){const X=u.isWebGLCubeRenderTarget===!0;if(e.bindFramebuffer(t.FRAMEBUFFER,b),!(u.depthTexture&&u.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const gA=g.get(u.depthTexture);if(gA.__renderTarget=u,(!gA.__webglTexture||u.depthTexture.image.width!==u.width||u.depthTexture.image.height!==u.height)&&(u.depthTexture.image.width=u.width,u.depthTexture.image.height=u.height,u.depthTexture.needsUpdate=!0),X){if(gA.__webglInit===void 0&&(gA.__webglInit=!0,u.depthTexture.addEventListener("dispose",p)),gA.__webglTexture===void 0){gA.__webglTexture=t.createTexture(),e.bindTexture(t.TEXTURE_CUBE_MAP,gA.__webglTexture),JA(t.TEXTURE_CUBE_MAP,u.depthTexture);const UA=I.convert(u.depthTexture.format),CA=I.convert(u.depthTexture.type);let cA;u.depthTexture.format===Gt?cA=t.DEPTH_COMPONENT24:u.depthTexture.format===Ni&&(cA=t.DEPTH24_STENCIL8);for(let mA=0;mA<6;mA++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+mA,0,cA,u.width,u.height,0,UA,CA,null)}}else j(u.depthTexture,0);const V=gA.__webglTexture,kA=R(u),EA=X?t.TEXTURE_CUBE_MAP_POSITIVE_X+M:t.TEXTURE_2D,bA=u.depthTexture.format===Ni?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(u.depthTexture.format===Gt)He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,bA,EA,V,0,kA):t.framebufferTexture2D(t.FRAMEBUFFER,bA,EA,V,0);else if(u.depthTexture.format===Ni)He(u)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,bA,EA,V,0,kA):t.framebufferTexture2D(t.FRAMEBUFFER,bA,EA,V,0);else throw new Error("Unknown depthTexture format")}function Qe(b){const u=g.get(b),M=b.isWebGLCubeRenderTarget===!0;if(u.__boundDepthTexture!==b.depthTexture){const X=b.depthTexture;if(u.__depthDisposeCallback&&u.__depthDisposeCallback(),X){const gA=()=>{delete u.__boundDepthTexture,delete u.__depthDisposeCallback,X.removeEventListener("dispose",gA)};X.addEventListener("dispose",gA),u.__depthDisposeCallback=gA}u.__boundDepthTexture=X}if(b.depthTexture&&!u.__autoAllocateDepthBuffer)if(M)for(let X=0;X<6;X++)yA(u.__webglFramebuffer[X],b,X);else{const X=b.texture.mipmaps;X&&X.length>0?yA(u.__webglFramebuffer[0],b,0):yA(u.__webglFramebuffer,b,0)}else if(M){u.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer[X]),u.__webglDepthbuffer[X]===void 0)u.__webglDepthbuffer[X]=t.createRenderbuffer(),TA(u.__webglDepthbuffer[X],b,!1);else{const gA=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,V=u.__webglDepthbuffer[X];t.bindRenderbuffer(t.RENDERBUFFER,V),t.framebufferRenderbuffer(t.FRAMEBUFFER,gA,t.RENDERBUFFER,V)}}else{const X=b.texture.mipmaps;if(X&&X.length>0?e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer[0]):e.bindFramebuffer(t.FRAMEBUFFER,u.__webglFramebuffer),u.__webglDepthbuffer===void 0)u.__webglDepthbuffer=t.createRenderbuffer(),TA(u.__webglDepthbuffer,b,!1);else{const gA=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,V=u.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,V),t.framebufferRenderbuffer(t.FRAMEBUFFER,gA,t.RENDERBUFFER,V)}}e.bindFramebuffer(t.FRAMEBUFFER,null)}function Ze(b,u,M){const X=g.get(b);u!==void 0&&wA(X.__webglFramebuffer,b,b.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),M!==void 0&&Qe(b)}function oe(b){const u=b.texture,M=g.get(b),X=g.get(u);b.addEventListener("dispose",y);const gA=b.textures,V=b.isWebGLCubeRenderTarget===!0,kA=gA.length>1;if(kA||(X.__webglTexture===void 0&&(X.__webglTexture=t.createTexture()),X.__version=u.version,C.memory.textures++),V){M.__webglFramebuffer=[];for(let EA=0;EA<6;EA++)if(u.mipmaps&&u.mipmaps.length>0){M.__webglFramebuffer[EA]=[];for(let bA=0;bA<u.mipmaps.length;bA++)M.__webglFramebuffer[EA][bA]=t.createFramebuffer()}else M.__webglFramebuffer[EA]=t.createFramebuffer()}else{if(u.mipmaps&&u.mipmaps.length>0){M.__webglFramebuffer=[];for(let EA=0;EA<u.mipmaps.length;EA++)M.__webglFramebuffer[EA]=t.createFramebuffer()}else M.__webglFramebuffer=t.createFramebuffer();if(kA)for(let EA=0,bA=gA.length;EA<bA;EA++){const UA=g.get(gA[EA]);UA.__webglTexture===void 0&&(UA.__webglTexture=t.createTexture(),C.memory.textures++)}if(b.samples>0&&He(b)===!1){M.__webglMultisampledFramebuffer=t.createFramebuffer(),M.__webglColorRenderbuffer=[],e.bindFramebuffer(t.FRAMEBUFFER,M.__webglMultisampledFramebuffer);for(let EA=0;EA<gA.length;EA++){const bA=gA[EA];M.__webglColorRenderbuffer[EA]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,M.__webglColorRenderbuffer[EA]);const UA=I.convert(bA.format,bA.colorSpace),CA=I.convert(bA.type),cA=_(bA.internalFormat,UA,CA,bA.colorSpace,b.isXRRenderTarget===!0),mA=R(b);t.renderbufferStorageMultisample(t.RENDERBUFFER,mA,cA,b.width,b.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+EA,t.RENDERBUFFER,M.__webglColorRenderbuffer[EA])}t.bindRenderbuffer(t.RENDERBUFFER,null),b.depthBuffer&&(M.__webglDepthRenderbuffer=t.createRenderbuffer(),TA(M.__webglDepthRenderbuffer,b,!0)),e.bindFramebuffer(t.FRAMEBUFFER,null)}}if(V){e.bindTexture(t.TEXTURE_CUBE_MAP,X.__webglTexture),JA(t.TEXTURE_CUBE_MAP,u);for(let EA=0;EA<6;EA++)if(u.mipmaps&&u.mipmaps.length>0)for(let bA=0;bA<u.mipmaps.length;bA++)wA(M.__webglFramebuffer[EA][bA],b,u,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+EA,bA);else wA(M.__webglFramebuffer[EA],b,u,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+EA,0);h(u)&&r(t.TEXTURE_CUBE_MAP),e.unbindTexture()}else if(kA){for(let EA=0,bA=gA.length;EA<bA;EA++){const UA=gA[EA],CA=g.get(UA);let cA=t.TEXTURE_2D;(b.isWebGL3DRenderTarget||b.isWebGLArrayRenderTarget)&&(cA=b.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),e.bindTexture(cA,CA.__webglTexture),JA(cA,UA),wA(M.__webglFramebuffer,b,UA,t.COLOR_ATTACHMENT0+EA,cA,0),h(UA)&&r(cA)}e.unbindTexture()}else{let EA=t.TEXTURE_2D;if((b.isWebGL3DRenderTarget||b.isWebGLArrayRenderTarget)&&(EA=b.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),e.bindTexture(EA,X.__webglTexture),JA(EA,u),u.mipmaps&&u.mipmaps.length>0)for(let bA=0;bA<u.mipmaps.length;bA++)wA(M.__webglFramebuffer[bA],b,u,t.COLOR_ATTACHMENT0,EA,bA);else wA(M.__webglFramebuffer,b,u,t.COLOR_ATTACHMENT0,EA,0);h(u)&&r(EA),e.unbindTexture()}b.depthBuffer&&Qe(b)}function ce(b){const u=b.textures;for(let M=0,X=u.length;M<X;M++){const gA=u[M];if(h(gA)){const V=f(b),kA=g.get(gA).__webglTexture;e.bindTexture(V,kA),r(V),e.unbindTexture()}}}const De=[],OA=[];function qe(b){if(b.samples>0){if(He(b)===!1){const u=b.textures,M=b.width,X=b.height;let gA=t.COLOR_BUFFER_BIT;const V=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,kA=g.get(b),EA=u.length>1;if(EA)for(let UA=0;UA<u.length;UA++)e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.RENDERBUFFER,null),e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.TEXTURE_2D,null,0);e.bindFramebuffer(t.READ_FRAMEBUFFER,kA.__webglMultisampledFramebuffer);const bA=b.texture.mipmaps;bA&&bA.length>0?e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglFramebuffer[0]):e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglFramebuffer);for(let UA=0;UA<u.length;UA++){if(b.resolveDepthBuffer&&(b.depthBuffer&&(gA|=t.DEPTH_BUFFER_BIT),b.stencilBuffer&&b.resolveStencilBuffer&&(gA|=t.STENCIL_BUFFER_BIT)),EA){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,kA.__webglColorRenderbuffer[UA]);const CA=g.get(u[UA]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,CA,0)}t.blitFramebuffer(0,0,M,X,0,0,M,X,gA,t.NEAREST),a===!0&&(De.length=0,OA.length=0,De.push(t.COLOR_ATTACHMENT0+UA),b.depthBuffer&&b.resolveDepthBuffer===!1&&(De.push(V),OA.push(V),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,OA)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,De))}if(e.bindFramebuffer(t.READ_FRAMEBUFFER,null),e.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),EA)for(let UA=0;UA<u.length;UA++){e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.RENDERBUFFER,kA.__webglColorRenderbuffer[UA]);const CA=g.get(u[UA]).__webglTexture;e.bindFramebuffer(t.FRAMEBUFFER,kA.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+UA,t.TEXTURE_2D,CA,0)}e.bindFramebuffer(t.DRAW_FRAMEBUFFER,kA.__webglMultisampledFramebuffer)}else if(b.depthBuffer&&b.resolveDepthBuffer===!1&&a){const u=b.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[u])}}}function R(b){return Math.min(i.maxSamples,b.samples)}function He(b){const u=g.get(b);return b.samples>0&&A.has("WEBGL_multisampled_render_to_texture")===!0&&u.__useRenderToTexture!==!1}function Ee(b){const u=C.render.frame;n.get(b)!==u&&(n.set(b,u),b.update())}function we(b,u){const M=b.colorSpace,X=b.format,gA=b.type;return b.isCompressedTexture===!0||b.isVideoTexture===!0||M!==sI&&M!==ii&&(Ce.getTransfer(M)===re?(X!==Hg||gA!==Sg)&&LA("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ae("WebGLTextures: Unsupported texture color space:",M)),u}function NA(b){return typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement?(Q.width=b.naturalWidth||b.width,Q.height=b.naturalHeight||b.height):typeof VideoFrame<"u"&&b instanceof VideoFrame?(Q.width=b.displayWidth,Q.height=b.displayHeight):(Q.width=b.width,Q.height=b.height),Q}this.allocateTextureUnit=K,this.resetTextureUnits=U,this.setTexture2D=j,this.setTexture2DArray=H,this.setTexture3D=O,this.setTextureCube=z,this.rebindTextures=Ze,this.setupRenderTarget=oe,this.updateRenderTargetMipmap=ce,this.updateMultisampleRenderTarget=qe,this.setupDepthRenderbuffer=Qe,this.setupFrameBufferTexture=wA,this.useMultisampledRTT=He,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function lw(t,A){function e(g,i=ii){let I;const C=Ce.getTransfer(i);if(g===Sg)return t.UNSIGNED_BYTE;if(g===ZQ)return t.UNSIGNED_SHORT_4_4_4_4;if(g===zQ)return t.UNSIGNED_SHORT_5_5_5_1;if(g===e0)return t.UNSIGNED_INT_5_9_9_9_REV;if(g===g0)return t.UNSIGNED_INT_10F_11F_11F_REV;if(g===$r)return t.BYTE;if(g===A0)return t.SHORT;if(g===IC)return t.UNSIGNED_SHORT;if(g===XQ)return t.INT;if(g===at)return t.UNSIGNED_INT;if(g===Qt)return t.FLOAT;if(g===Rt)return t.HALF_FLOAT;if(g===t0)return t.ALPHA;if(g===i0)return t.RGB;if(g===Hg)return t.RGBA;if(g===Gt)return t.DEPTH_COMPONENT;if(g===Ni)return t.DEPTH_STENCIL;if(g===I0)return t.RED;if(g===$Q)return t.RED_INTEGER;if(g===nI)return t.RG;if(g===An)return t.RG_INTEGER;if(g===en)return t.RGBA_INTEGER;if(g===co||g===ho||g===xo||g===lo)if(C===re)if(I=A.get("WEBGL_compressed_texture_s3tc_srgb"),I!==null){if(g===co)return I.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(g===ho)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(g===xo)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(g===lo)return I.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(I=A.get("WEBGL_compressed_texture_s3tc"),I!==null){if(g===co)return I.COMPRESSED_RGB_S3TC_DXT1_EXT;if(g===ho)return I.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(g===xo)return I.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(g===lo)return I.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(g===gn||g===tn||g===In||g===Cn)if(I=A.get("WEBGL_compressed_texture_pvrtc"),I!==null){if(g===gn)return I.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(g===tn)return I.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(g===In)return I.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(g===Cn)return I.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(g===on||g===an||g===Qn||g===nn||g===sn||g===Bn||g===En)if(I=A.get("WEBGL_compressed_texture_etc"),I!==null){if(g===on||g===an)return C===re?I.COMPRESSED_SRGB8_ETC2:I.COMPRESSED_RGB8_ETC2;if(g===Qn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:I.COMPRESSED_RGBA8_ETC2_EAC;if(g===nn)return I.COMPRESSED_R11_EAC;if(g===sn)return I.COMPRESSED_SIGNED_R11_EAC;if(g===Bn)return I.COMPRESSED_RG11_EAC;if(g===En)return I.COMPRESSED_SIGNED_RG11_EAC}else return null;if(g===rn||g===cn||g===hn||g===dn||g===xn||g===ln||g===fn||g===un||g===Dn||g===_n||g===wn||g===pn||g===mn||g===yn)if(I=A.get("WEBGL_compressed_texture_astc"),I!==null){if(g===rn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:I.COMPRESSED_RGBA_ASTC_4x4_KHR;if(g===cn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:I.COMPRESSED_RGBA_ASTC_5x4_KHR;if(g===hn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:I.COMPRESSED_RGBA_ASTC_5x5_KHR;if(g===dn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:I.COMPRESSED_RGBA_ASTC_6x5_KHR;if(g===xn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:I.COMPRESSED_RGBA_ASTC_6x6_KHR;if(g===ln)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:I.COMPRESSED_RGBA_ASTC_8x5_KHR;if(g===fn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:I.COMPRESSED_RGBA_ASTC_8x6_KHR;if(g===un)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:I.COMPRESSED_RGBA_ASTC_8x8_KHR;if(g===Dn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:I.COMPRESSED_RGBA_ASTC_10x5_KHR;if(g===_n)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:I.COMPRESSED_RGBA_ASTC_10x6_KHR;if(g===wn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:I.COMPRESSED_RGBA_ASTC_10x8_KHR;if(g===pn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:I.COMPRESSED_RGBA_ASTC_10x10_KHR;if(g===mn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:I.COMPRESSED_RGBA_ASTC_12x10_KHR;if(g===yn)return C===re?I.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:I.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(g===bn||g===Nn||g===Sn)if(I=A.get("EXT_texture_compression_bptc"),I!==null){if(g===bn)return C===re?I.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:I.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(g===Nn)return I.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(g===Sn)return I.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(g===kn||g===Rn||g===Gn||g===Mn)if(I=A.get("EXT_texture_compression_rgtc"),I!==null){if(g===kn)return I.COMPRESSED_RED_RGTC1_EXT;if(g===Rn)return I.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(g===Gn)return I.COMPRESSED_RED_GREEN_RGTC2_EXT;if(g===Mn)return I.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return g===CC?t.UNSIGNED_INT_24_8:t[g]!==void 0?t[g]:null}return{convert:e}}const fw=`
|
|
4142
4142
|
void main() {
|
|
4143
4143
|
|
|
4144
4144
|
gl_Position = vec4( position, 1.0 );
|
|
@@ -4162,7 +4162,7 @@ void main() {
|
|
|
4162
4162
|
|
|
4163
4163
|
}
|
|
4164
4164
|
|
|
4165
|
-
}`;class Dw{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,e){if(this.texture===null){const g=new v0(A.texture);(A.depthNear!==e.depthNear||A.depthFar!==e.depthFar)&&(this.depthNear=A.depthNear,this.depthFar=A.depthFar),this.texture=g}}getMesh(A){if(this.texture!==null&&this.mesh===null){const e=A.cameras[0].viewport,g=new Gg({vertexShader:fw,fragmentShader:uw,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Xg(new To(20,20),g)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class _w extends EI{constructor(A,e){super();const g=this;let i=null,I=1,C=null,o="local-floor",a=1,Q=null,n=null,s=null,B=null,E=null,d=null;const c=typeof XRWebGLBinding<"u",h=new Dw,r={},f=e.getContextAttributes();let _=null,l=null;const D=[],p=[],y=new Be;let k=null;const x=new Mg;x.viewport=new Ke;const w=new Mg;w.viewport=new Ke;const N=[x,w],U=new Bu;let K=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getTargetRaySpace()},this.getControllerGrip=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getGripSpace()},this.getHand=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getHandSpace()};function j(Z){const iA=p.indexOf(Z.inputSource);if(iA===-1)return;const wA=D[iA];wA!==void 0&&(wA.update(Z.inputSource,Z.frame,Q||C),wA.dispatchEvent({type:Z.type,data:Z.inputSource}))}function H(){i.removeEventListener("select",j),i.removeEventListener("selectstart",j),i.removeEventListener("selectend",j),i.removeEventListener("squeeze",j),i.removeEventListener("squeezestart",j),i.removeEventListener("squeezeend",j),i.removeEventListener("end",H),i.removeEventListener("inputsourceschange",O);for(let Z=0;Z<D.length;Z++){const iA=p[Z];iA!==null&&(p[Z]=null,D[Z].disconnect(iA))}K=null,P=null,h.reset();for(const Z in r)delete r[Z];A.setRenderTarget(_),E=null,B=null,s=null,i=null,l=null,le.stop(),g.isPresenting=!1,A.setPixelRatio(k),A.setSize(y.width,y.height,!1),g.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){I=Z,g.isPresenting===!0&&LA("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){o=Z,g.isPresenting===!0&&LA("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return Q||C},this.setReferenceSpace=function(Z){Q=Z},this.getBaseLayer=function(){return B!==null?B:E},this.getBinding=function(){return s===null&&c&&(s=new XRWebGLBinding(i,e)),s},this.getFrame=function(){return d},this.getSession=function(){return i},this.setSession=async function(Z){if(i=Z,i!==null){if(_=A.getRenderTarget(),i.addEventListener("select",j),i.addEventListener("selectstart",j),i.addEventListener("selectend",j),i.addEventListener("squeeze",j),i.addEventListener("squeezestart",j),i.addEventListener("squeezeend",j),i.addEventListener("end",H),i.addEventListener("inputsourceschange",O),f.xrCompatible!==!0&&await e.makeXRCompatible(),k=A.getPixelRatio(),A.getSize(y),c&&"createProjectionLayer"in XRWebGLBinding.prototype){let wA=null,TA=null,yA=null;f.depth&&(yA=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,wA=f.stencil?bi:Gt,TA=f.stencil?CC:at);const Qe={colorFormat:e.RGBA8,depthFormat:yA,scaleFactor:I};s=this.getBinding(),B=s.createProjectionLayer(Qe),i.updateRenderState({layers:[B]}),A.setPixelRatio(1),A.setSize(B.textureWidth,B.textureHeight,!1),l=new st(B.textureWidth,B.textureHeight,{format:Hg,type:Sg,depthTexture:new dC(B.textureWidth,B.textureHeight,TA,void 0,void 0,void 0,void 0,void 0,void 0,wA),stencilBuffer:f.stencil,colorSpace:A.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1})}else{const wA={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:I};E=new XRWebGLLayer(i,e,wA),i.updateRenderState({baseLayer:E}),A.setPixelRatio(1),A.setSize(E.framebufferWidth,E.framebufferHeight,!1),l=new st(E.framebufferWidth,E.framebufferHeight,{format:Hg,type:Sg,colorSpace:A.outputColorSpace,stencilBuffer:f.stencil,resolveDepthBuffer:E.ignoreDepthValues===!1,resolveStencilBuffer:E.ignoreDepthValues===!1})}l.isXRRenderTarget=!0,this.setFoveation(a),Q=null,C=await i.requestReferenceSpace(o),le.setContext(i),le.start(),g.isPresenting=!0,g.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function O(Z){for(let iA=0;iA<Z.removed.length;iA++){const wA=Z.removed[iA],TA=p.indexOf(wA);TA>=0&&(p[TA]=null,D[TA].disconnect(wA))}for(let iA=0;iA<Z.added.length;iA++){const wA=Z.added[iA];let TA=p.indexOf(wA);if(TA===-1){for(let Qe=0;Qe<D.length;Qe++)if(Qe>=p.length){p.push(wA),TA=Qe;break}else if(p[Qe]===null){p[Qe]=wA,TA=Qe;break}if(TA===-1)break}const yA=D[TA];yA&&yA.connect(wA)}}const z=new J,xA=new J;function sA(Z,iA,wA){z.setFromMatrixPosition(iA.matrixWorld),xA.setFromMatrixPosition(wA.matrixWorld);const TA=z.distanceTo(xA),yA=iA.projectionMatrix.elements,Qe=wA.projectionMatrix.elements,Ze=yA[14]/(yA[10]-1),oe=yA[14]/(yA[10]+1),ce=(yA[9]+1)/yA[5],De=(yA[9]-1)/yA[5],OA=(yA[8]-1)/yA[0],qe=(Qe[8]+1)/Qe[0],R=Ze*OA,He=Ze*qe,Ee=TA/(-OA+qe),we=Ee*-OA;if(iA.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(we),Z.translateZ(Ee),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),yA[10]===-1)Z.projectionMatrix.copy(iA.projectionMatrix),Z.projectionMatrixInverse.copy(iA.projectionMatrixInverse);else{const NA=Ze+Ee,b=oe+Ee,u=R-we,M=He+(TA-we),X=ce*oe/b*NA,gA=De*oe/b*NA;Z.projectionMatrix.makePerspective(u,M,X,gA,NA,b),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function fA(Z,iA){iA===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(iA.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;let iA=Z.near,wA=Z.far;h.texture!==null&&(h.depthNear>0&&(iA=h.depthNear),h.depthFar>0&&(wA=h.depthFar)),U.near=w.near=x.near=iA,U.far=w.far=x.far=wA,(K!==U.near||P!==U.far)&&(i.updateRenderState({depthNear:U.near,depthFar:U.far}),K=U.near,P=U.far),U.layers.mask=Z.layers.mask|6,x.layers.mask=U.layers.mask&3,w.layers.mask=U.layers.mask&5;const TA=Z.parent,yA=U.cameras;fA(U,TA);for(let Qe=0;Qe<yA.length;Qe++)fA(yA[Qe],TA);yA.length===2?sA(U,x,w):U.projectionMatrix.copy(x.projectionMatrix),JA(Z,U,TA)};function JA(Z,iA,wA){wA===null?Z.matrix.copy(iA.matrixWorld):(Z.matrix.copy(wA.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(iA.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(iA.projectionMatrix),Z.projectionMatrixInverse.copy(iA.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=Kn*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return U},this.getFoveation=function(){if(!(B===null&&E===null))return a},this.setFoveation=function(Z){a=Z,B!==null&&(B.fixedFoveation=Z),E!==null&&E.fixedFoveation!==void 0&&(E.fixedFoveation=Z)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(U)},this.getCameraTexture=function(Z){return r[Z]};let vA=null;function be(Z,iA){if(n=iA.getViewerPose(Q||C),d=iA,n!==null){const wA=n.views;E!==null&&(A.setRenderTargetFramebuffer(l,E.framebuffer),A.setRenderTarget(l));let TA=!1;wA.length!==U.cameras.length&&(U.cameras.length=0,TA=!0);for(let oe=0;oe<wA.length;oe++){const ce=wA[oe];let De=null;if(E!==null)De=E.getViewport(ce);else{const qe=s.getViewSubImage(B,ce);De=qe.viewport,oe===0&&(A.setRenderTargetTextures(l,qe.colorTexture,qe.depthStencilTexture),A.setRenderTarget(l))}let OA=N[oe];OA===void 0&&(OA=new Mg,OA.layers.enable(oe),OA.viewport=new Ke,N[oe]=OA),OA.matrix.fromArray(ce.transform.matrix),OA.matrix.decompose(OA.position,OA.quaternion,OA.scale),OA.projectionMatrix.fromArray(ce.projectionMatrix),OA.projectionMatrixInverse.copy(OA.projectionMatrix).invert(),OA.viewport.set(De.x,De.y,De.width,De.height),oe===0&&(U.matrix.copy(OA.matrix),U.matrix.decompose(U.position,U.quaternion,U.scale)),TA===!0&&U.cameras.push(OA)}const yA=i.enabledFeatures;if(yA&&yA.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&c){s=g.getBinding();const oe=s.getDepthInformation(wA[0]);oe&&oe.isValid&&oe.texture&&h.init(oe,i.renderState)}if(yA&&yA.includes("camera-access")&&c){A.state.unbindTexture(),s=g.getBinding();for(let oe=0;oe<wA.length;oe++){const ce=wA[oe].camera;if(ce){let De=r[ce];De||(De=new v0,r[ce]=De);const OA=s.getCameraImage(ce);De.sourceTexture=OA}}}}for(let wA=0;wA<D.length;wA++){const TA=p[wA],yA=D[wA];TA!==null&&yA!==void 0&&yA.update(TA,iA,Q||C)}vA&&vA(Z,iA),iA.detectedPlanes&&g.dispatchEvent({type:"planesdetected",data:iA}),d=null}const le=new T0;le.setAnimationLoop(be),this.setAnimationLoop=function(Z){vA=Z},this.dispose=function(){}}}const Ui=new Lt,ww=new Ye;function pw(t,A){function e(h,r){h.matrixAutoUpdate===!0&&h.updateMatrix(),r.value.copy(h.matrix)}function g(h,r){r.color.getRGB(h.fogColor.value,R0(t)),r.isFog?(h.fogNear.value=r.near,h.fogFar.value=r.far):r.isFogExp2&&(h.fogDensity.value=r.density)}function i(h,r,f,_,l){r.isMeshBasicMaterial||r.isMeshLambertMaterial?I(h,r):r.isMeshToonMaterial?(I(h,r),s(h,r)):r.isMeshPhongMaterial?(I(h,r),n(h,r)):r.isMeshStandardMaterial?(I(h,r),B(h,r),r.isMeshPhysicalMaterial&&E(h,r,l)):r.isMeshMatcapMaterial?(I(h,r),d(h,r)):r.isMeshDepthMaterial?I(h,r):r.isMeshDistanceMaterial?(I(h,r),c(h,r)):r.isMeshNormalMaterial?I(h,r):r.isLineBasicMaterial?(C(h,r),r.isLineDashedMaterial&&o(h,r)):r.isPointsMaterial?a(h,r,f,_):r.isSpriteMaterial?Q(h,r):r.isShadowMaterial?(h.color.value.copy(r.color),h.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}function I(h,r){h.opacity.value=r.opacity,r.color&&h.diffuse.value.copy(r.color),r.emissive&&h.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(h.map.value=r.map,e(r.map,h.mapTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.bumpMap&&(h.bumpMap.value=r.bumpMap,e(r.bumpMap,h.bumpMapTransform),h.bumpScale.value=r.bumpScale,r.side===tg&&(h.bumpScale.value*=-1)),r.normalMap&&(h.normalMap.value=r.normalMap,e(r.normalMap,h.normalMapTransform),h.normalScale.value.copy(r.normalScale),r.side===tg&&h.normalScale.value.negate()),r.displacementMap&&(h.displacementMap.value=r.displacementMap,e(r.displacementMap,h.displacementMapTransform),h.displacementScale.value=r.displacementScale,h.displacementBias.value=r.displacementBias),r.emissiveMap&&(h.emissiveMap.value=r.emissiveMap,e(r.emissiveMap,h.emissiveMapTransform)),r.specularMap&&(h.specularMap.value=r.specularMap,e(r.specularMap,h.specularMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest);const f=A.get(r),_=f.envMap,l=f.envMapRotation;_&&(h.envMap.value=_,Ui.copy(l),Ui.x*=-1,Ui.y*=-1,Ui.z*=-1,_.isCubeTexture&&_.isRenderTargetTexture===!1&&(Ui.y*=-1,Ui.z*=-1),h.envMapRotation.value.setFromMatrix4(ww.makeRotationFromEuler(Ui)),h.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,h.reflectivity.value=r.reflectivity,h.ior.value=r.ior,h.refractionRatio.value=r.refractionRatio),r.lightMap&&(h.lightMap.value=r.lightMap,h.lightMapIntensity.value=r.lightMapIntensity,e(r.lightMap,h.lightMapTransform)),r.aoMap&&(h.aoMap.value=r.aoMap,h.aoMapIntensity.value=r.aoMapIntensity,e(r.aoMap,h.aoMapTransform))}function C(h,r){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,r.map&&(h.map.value=r.map,e(r.map,h.mapTransform))}function o(h,r){h.dashSize.value=r.dashSize,h.totalSize.value=r.dashSize+r.gapSize,h.scale.value=r.scale}function a(h,r,f,_){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,h.size.value=r.size*f,h.scale.value=_*.5,r.map&&(h.map.value=r.map,e(r.map,h.uvTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest)}function Q(h,r){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,h.rotation.value=r.rotation,r.map&&(h.map.value=r.map,e(r.map,h.mapTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest)}function n(h,r){h.specular.value.copy(r.specular),h.shininess.value=Math.max(r.shininess,1e-4)}function s(h,r){r.gradientMap&&(h.gradientMap.value=r.gradientMap)}function B(h,r){h.metalness.value=r.metalness,r.metalnessMap&&(h.metalnessMap.value=r.metalnessMap,e(r.metalnessMap,h.metalnessMapTransform)),h.roughness.value=r.roughness,r.roughnessMap&&(h.roughnessMap.value=r.roughnessMap,e(r.roughnessMap,h.roughnessMapTransform)),r.envMap&&(h.envMapIntensity.value=r.envMapIntensity)}function E(h,r,f){h.ior.value=r.ior,r.sheen>0&&(h.sheenColor.value.copy(r.sheenColor).multiplyScalar(r.sheen),h.sheenRoughness.value=r.sheenRoughness,r.sheenColorMap&&(h.sheenColorMap.value=r.sheenColorMap,e(r.sheenColorMap,h.sheenColorMapTransform)),r.sheenRoughnessMap&&(h.sheenRoughnessMap.value=r.sheenRoughnessMap,e(r.sheenRoughnessMap,h.sheenRoughnessMapTransform))),r.clearcoat>0&&(h.clearcoat.value=r.clearcoat,h.clearcoatRoughness.value=r.clearcoatRoughness,r.clearcoatMap&&(h.clearcoatMap.value=r.clearcoatMap,e(r.clearcoatMap,h.clearcoatMapTransform)),r.clearcoatRoughnessMap&&(h.clearcoatRoughnessMap.value=r.clearcoatRoughnessMap,e(r.clearcoatRoughnessMap,h.clearcoatRoughnessMapTransform)),r.clearcoatNormalMap&&(h.clearcoatNormalMap.value=r.clearcoatNormalMap,e(r.clearcoatNormalMap,h.clearcoatNormalMapTransform),h.clearcoatNormalScale.value.copy(r.clearcoatNormalScale),r.side===tg&&h.clearcoatNormalScale.value.negate())),r.dispersion>0&&(h.dispersion.value=r.dispersion),r.iridescence>0&&(h.iridescence.value=r.iridescence,h.iridescenceIOR.value=r.iridescenceIOR,h.iridescenceThicknessMinimum.value=r.iridescenceThicknessRange[0],h.iridescenceThicknessMaximum.value=r.iridescenceThicknessRange[1],r.iridescenceMap&&(h.iridescenceMap.value=r.iridescenceMap,e(r.iridescenceMap,h.iridescenceMapTransform)),r.iridescenceThicknessMap&&(h.iridescenceThicknessMap.value=r.iridescenceThicknessMap,e(r.iridescenceThicknessMap,h.iridescenceThicknessMapTransform))),r.transmission>0&&(h.transmission.value=r.transmission,h.transmissionSamplerMap.value=f.texture,h.transmissionSamplerSize.value.set(f.width,f.height),r.transmissionMap&&(h.transmissionMap.value=r.transmissionMap,e(r.transmissionMap,h.transmissionMapTransform)),h.thickness.value=r.thickness,r.thicknessMap&&(h.thicknessMap.value=r.thicknessMap,e(r.thicknessMap,h.thicknessMapTransform)),h.attenuationDistance.value=r.attenuationDistance,h.attenuationColor.value.copy(r.attenuationColor)),r.anisotropy>0&&(h.anisotropyVector.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation)),r.anisotropyMap&&(h.anisotropyMap.value=r.anisotropyMap,e(r.anisotropyMap,h.anisotropyMapTransform))),h.specularIntensity.value=r.specularIntensity,h.specularColor.value.copy(r.specularColor),r.specularColorMap&&(h.specularColorMap.value=r.specularColorMap,e(r.specularColorMap,h.specularColorMapTransform)),r.specularIntensityMap&&(h.specularIntensityMap.value=r.specularIntensityMap,e(r.specularIntensityMap,h.specularIntensityMapTransform))}function d(h,r){r.matcap&&(h.matcap.value=r.matcap)}function c(h,r){const f=A.get(r).light;h.referencePosition.value.setFromMatrixPosition(f.matrixWorld),h.nearDistance.value=f.shadow.camera.near,h.farDistance.value=f.shadow.camera.far}return{refreshFogUniforms:g,refreshMaterialUniforms:i}}function mw(t,A,e,g){let i={},I={},C=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function a(f,_){const l=_.program;g.uniformBlockBinding(f,l)}function Q(f,_){let l=i[f.id];l===void 0&&(d(f),l=n(f),i[f.id]=l,f.addEventListener("dispose",h));const D=_.program;g.updateUBOMapping(f,D);const p=A.render.frame;I[f.id]!==p&&(B(f),I[f.id]=p)}function n(f){const _=s();f.__bindingPointIndex=_;const l=t.createBuffer(),D=f.__size,p=f.usage;return t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,D,p),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,_,l),l}function s(){for(let f=0;f<o;f++)if(C.indexOf(f)===-1)return C.push(f),f;return ae("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function B(f){const _=i[f.id],l=f.uniforms,D=f.__cache;t.bindBuffer(t.UNIFORM_BUFFER,_);for(let p=0,y=l.length;p<y;p++){const k=Array.isArray(l[p])?l[p]:[l[p]];for(let x=0,w=k.length;x<w;x++){const N=k[x];if(E(N,p,x,D)===!0){const U=N.__offset,K=Array.isArray(N.value)?N.value:[N.value];let P=0;for(let j=0;j<K.length;j++){const H=K[j],O=c(H);typeof H=="number"||typeof H=="boolean"?(N.__data[0]=H,t.bufferSubData(t.UNIFORM_BUFFER,U+P,N.__data)):H.isMatrix3?(N.__data[0]=H.elements[0],N.__data[1]=H.elements[1],N.__data[2]=H.elements[2],N.__data[3]=0,N.__data[4]=H.elements[3],N.__data[5]=H.elements[4],N.__data[6]=H.elements[5],N.__data[7]=0,N.__data[8]=H.elements[6],N.__data[9]=H.elements[7],N.__data[10]=H.elements[8],N.__data[11]=0):(H.toArray(N.__data,P),P+=O.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,U,N.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function E(f,_,l,D){const p=f.value,y=_+"_"+l;if(D[y]===void 0)return typeof p=="number"||typeof p=="boolean"?D[y]=p:D[y]=p.clone(),!0;{const k=D[y];if(typeof p=="number"||typeof p=="boolean"){if(k!==p)return D[y]=p,!0}else if(k.equals(p)===!1)return k.copy(p),!0}return!1}function d(f){const _=f.uniforms;let l=0;const D=16;for(let y=0,k=_.length;y<k;y++){const x=Array.isArray(_[y])?_[y]:[_[y]];for(let w=0,N=x.length;w<N;w++){const U=x[w],K=Array.isArray(U.value)?U.value:[U.value];for(let P=0,j=K.length;P<j;P++){const H=K[P],O=c(H),z=l%D,xA=z%O.boundary,sA=z+xA;l+=xA,sA!==0&&D-sA<O.storage&&(l+=D-sA),U.__data=new Float32Array(O.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=l,l+=O.storage}}}const p=l%D;return p>0&&(l+=D-p),f.__size=l,f.__cache={},this}function c(f){const _={boundary:0,storage:0};return typeof f=="number"||typeof f=="boolean"?(_.boundary=4,_.storage=4):f.isVector2?(_.boundary=8,_.storage=8):f.isVector3||f.isColor?(_.boundary=16,_.storage=12):f.isVector4?(_.boundary=16,_.storage=16):f.isMatrix3?(_.boundary=48,_.storage=48):f.isMatrix4?(_.boundary=64,_.storage=64):f.isTexture?LA("WebGLRenderer: Texture samplers can not be part of an uniforms group."):LA("WebGLRenderer: Unsupported uniform value type.",f),_}function h(f){const _=f.target;_.removeEventListener("dispose",h);const l=C.indexOf(_.__bindingPointIndex);C.splice(l,1),t.deleteBuffer(i[_.id]),delete i[_.id],delete I[_.id]}function r(){for(const f in i)t.deleteBuffer(i[f]);C=[],i={},I={}}return{bind:a,update:Q,dispose:r}}const yw=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 rt=null;function bw(){return rt===null&&(rt=new iu(yw,16,16,nI,Rt),rt.name="DFG_LUT",rt.minFilter=Ag,rt.magFilter=Ag,rt.wrapS=kt,rt.wrapT=kt,rt.generateMipmaps=!1,rt.needsUpdate=!0),rt}class Nw{constructor(A={}){const{canvas:e=Sf(),context:g=null,depth:i=!0,stencil:I=!1,alpha:C=!1,antialias:o=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:Q=!1,powerPreference:n="default",failIfMajorPerformanceCaveat:s=!1,reversedDepthBuffer:B=!1,outputBufferType:E=Sg}=A;this.isWebGLRenderer=!0;let d;if(g!==null){if(typeof WebGLRenderingContext<"u"&&g instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=g.getContextAttributes().alpha}else d=C;const c=E,h=new Set([en,An,$Q]),r=new Set([Sg,at,IC,CC,ZQ,zQ]),f=new Uint32Array(4),_=new Int32Array(4);let l=null,D=null;const p=[],y=[];let k=null;this.domElement=e,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=ot,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const x=this;let w=!1;this._outputColorSpace=kg;let N=0,U=0,K=null,P=-1,j=null;const H=new Ke,O=new Ke;let z=null;const xA=new Ie(0);let sA=0,fA=e.width,JA=e.height,vA=1,be=null,le=null;const Z=new Ke(0,0,fA,JA),iA=new Ke(0,0,fA,JA);let wA=!1;const TA=new K0;let yA=!1,Qe=!1;const Ze=new Ye,oe=new J,ce=new Ke,De={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let OA=!1;function qe(){return K===null?vA:1}let R=g;function He(m,L){return e.getContext(m,L)}try{const m={alpha:!0,depth:i,stencil:I,antialias:o,premultipliedAlpha:a,preserveDrawingBuffer:Q,powerPreference:n,failIfMajorPerformanceCaveat:s};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${MQ}`),e.addEventListener("webglcontextlost",KA,!1),e.addEventListener("webglcontextrestored",pe,!1),e.addEventListener("webglcontextcreationerror",he,!1),R===null){const L="webgl2";if(R=He(L,m),R===null)throw He(L)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(m){throw ae("WebGLRenderer: "+m.message),m}let Ee,we,NA,b,u,M,X,gA,V,kA,EA,bA,UA,CA,cA,mA,SA,rA,VA,G,uA,aA,DA,IA;function eA(){Ee=new b_(R),Ee.init(),aA=new lw(R,Ee),we=new l_(R,Ee,A,aA),NA=new dw(R,Ee),we.reversedDepthBuffer&&B&&NA.buffers.depth.setReversed(!0),b=new k_(R),u=new gw,M=new xw(R,Ee,NA,u,we,aA,b),X=new u_(x),gA=new y_(x),V=new cu(R),DA=new d_(R,V),kA=new N_(R,V,b,DA),EA=new G_(R,kA,V,b),VA=new R_(R,we,M),mA=new f_(u),bA=new ew(x,X,gA,Ee,we,DA,mA),UA=new pw(x,u),CA=new iw,cA=new nw(Ee),rA=new h_(x,X,gA,NA,EA,d,a),SA=new cw(x,EA,we),IA=new mw(R,b,we,NA),G=new x_(R,Ee,b),uA=new S_(R,Ee,b),b.programs=bA.programs,x.capabilities=we,x.extensions=Ee,x.properties=u,x.renderLists=CA,x.shadowMap=SA,x.state=NA,x.info=b}eA(),c!==Sg&&(k=new F_(c,e.width,e.height,i,I));const BA=new _w(x,R);this.xr=BA,this.getContext=function(){return R},this.getContextAttributes=function(){return R.getContextAttributes()},this.forceContextLoss=function(){const m=Ee.get("WEBGL_lose_context");m&&m.loseContext()},this.forceContextRestore=function(){const m=Ee.get("WEBGL_lose_context");m&&m.restoreContext()},this.getPixelRatio=function(){return vA},this.setPixelRatio=function(m){m!==void 0&&(vA=m,this.setSize(fA,JA,!1))},this.getSize=function(m){return m.set(fA,JA)},this.setSize=function(m,L,q=!0){if(BA.isPresenting){LA("WebGLRenderer: Can't change size while VR device is presenting.");return}fA=m,JA=L,e.width=Math.floor(m*vA),e.height=Math.floor(L*vA),q===!0&&(e.style.width=m+"px",e.style.height=L+"px"),k!==null&&k.setSize(e.width,e.height),this.setViewport(0,0,m,L)},this.getDrawingBufferSize=function(m){return m.set(fA*vA,JA*vA).floor()},this.setDrawingBufferSize=function(m,L,q){fA=m,JA=L,vA=q,e.width=Math.floor(m*q),e.height=Math.floor(L*q),this.setViewport(0,0,m,L)},this.setEffects=function(m){if(c===Sg){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(m){for(let L=0;L<m.length;L++)if(m[L].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(H)},this.getViewport=function(m){return m.copy(Z)},this.setViewport=function(m,L,q,Y){m.isVector4?Z.set(m.x,m.y,m.z,m.w):Z.set(m,L,q,Y),NA.viewport(H.copy(Z).multiplyScalar(vA).round())},this.getScissor=function(m){return m.copy(iA)},this.setScissor=function(m,L,q,Y){m.isVector4?iA.set(m.x,m.y,m.z,m.w):iA.set(m,L,q,Y),NA.scissor(O.copy(iA).multiplyScalar(vA).round())},this.getScissorTest=function(){return wA},this.setScissorTest=function(m){NA.setScissorTest(wA=m)},this.setOpaqueSort=function(m){be=m},this.setTransparentSort=function(m){le=m},this.getClearColor=function(m){return m.copy(rA.getClearColor())},this.setClearColor=function(){rA.setClearColor(...arguments)},this.getClearAlpha=function(){return rA.getClearAlpha()},this.setClearAlpha=function(){rA.setClearAlpha(...arguments)},this.clear=function(m=!0,L=!0,q=!0){let Y=0;if(m){let v=!1;if(K!==null){const hA=K.texture.format;v=h.has(hA)}if(v){const hA=K.texture.type,_A=r.has(hA),lA=rA.getClearColor(),pA=rA.getClearAlpha(),RA=lA.r,FA=lA.g,GA=lA.b;_A?(f[0]=RA,f[1]=FA,f[2]=GA,f[3]=pA,R.clearBufferuiv(R.COLOR,0,f)):(_[0]=RA,_[1]=FA,_[2]=GA,_[3]=pA,R.clearBufferiv(R.COLOR,0,_))}else Y|=R.COLOR_BUFFER_BIT}L&&(Y|=R.DEPTH_BUFFER_BIT),q&&(Y|=R.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),R.clear(Y)},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(){e.removeEventListener("webglcontextlost",KA,!1),e.removeEventListener("webglcontextrestored",pe,!1),e.removeEventListener("webglcontextcreationerror",he,!1),rA.dispose(),CA.dispose(),cA.dispose(),u.dispose(),X.dispose(),gA.dispose(),EA.dispose(),DA.dispose(),IA.dispose(),bA.dispose(),BA.dispose(),BA.removeEventListener("sessionstart",lc),BA.removeEventListener("sessionend",fc),vi.stop()};function KA(m){m.preventDefault(),s0("WebGLRenderer: Context Lost."),w=!0}function pe(){s0("WebGLRenderer: Context Restored."),w=!1;const m=b.autoReset,L=SA.enabled,q=SA.autoUpdate,Y=SA.needsUpdate,v=SA.type;eA(),b.autoReset=m,SA.enabled=L,SA.autoUpdate=q,SA.needsUpdate=Y,SA.type=v}function he(m){ae("WebGLRenderer: A WebGL context could not be created. Reason: ",m.statusMessage)}function ht(m){const L=m.target;L.removeEventListener("dispose",ht),Yt(L)}function Yt(m){ip(m),u.remove(m)}function ip(m){const L=u.get(m).programs;L!==void 0&&(L.forEach(function(q){bA.releaseProgram(q)}),m.isShaderMaterial&&bA.releaseShaderCache(m))}this.renderBufferDirect=function(m,L,q,Y,v,hA){L===null&&(L=De);const _A=v.isMesh&&v.matrixWorld.determinant()<0,lA=Cp(m,L,q,Y,v);NA.setMaterial(Y,_A);let pA=q.index,RA=1;if(Y.wireframe===!0){if(pA=kA.getWireframeAttribute(q),pA===void 0)return;RA=2}const FA=q.drawRange,GA=q.attributes.position;let jA=FA.start*RA,fe=(FA.start+FA.count)*RA;hA!==null&&(jA=Math.max(jA,hA.start*RA),fe=Math.min(fe,(hA.start+hA.count)*RA)),pA!==null?(jA=Math.max(jA,0),fe=Math.min(fe,pA.count)):GA!=null&&(jA=Math.max(jA,0),fe=Math.min(fe,GA.count));const Fe=fe-jA;if(Fe<0||Fe===1/0)return;DA.setup(v,Y,lA,q,pA);let Ue,_e=G;if(pA!==null&&(Ue=V.get(pA),_e=uA,_e.setIndex(Ue)),v.isMesh)Y.wireframe===!0?(NA.setLineWidth(Y.wireframeLinewidth*qe()),_e.setMode(R.LINES)):_e.setMode(R.TRIANGLES);else if(v.isLine){let MA=Y.linewidth;MA===void 0&&(MA=1),NA.setLineWidth(MA*qe()),v.isLineSegments?_e.setMode(R.LINES):v.isLineLoop?_e.setMode(R.LINE_LOOP):_e.setMode(R.LINE_STRIP)}else v.isPoints?_e.setMode(R.POINTS):v.isSprite&&_e.setMode(R.TRIANGLES);if(v.isBatchedMesh)if(v._multiDrawInstances!==null)oC("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_e.renderMultiDrawInstances(v._multiDrawStarts,v._multiDrawCounts,v._multiDrawCount,v._multiDrawInstances);else if(Ee.get("WEBGL_multi_draw"))_e.renderMultiDraw(v._multiDrawStarts,v._multiDrawCounts,v._multiDrawCount);else{const MA=v._multiDrawStarts,de=v._multiDrawCounts,ne=v._multiDrawCount,yg=pA?V.get(pA).bytesPerElement:1,RI=u.get(Y).currentProgram.getUniforms();for(let bg=0;bg<ne;bg++)RI.setValue(R,"_gl_DrawID",bg),_e.render(MA[bg]/yg,de[bg])}else if(v.isInstancedMesh)_e.renderInstances(jA,Fe,v.count);else if(q.isInstancedBufferGeometry){const MA=q._maxInstanceCount!==void 0?q._maxInstanceCount:1/0,de=Math.min(q.instanceCount,MA);_e.renderInstances(jA,Fe,de)}else _e.render(jA,Fe)};function xc(m,L,q){m.transparent===!0&&m.side===Nt&&m.forceSinglePass===!1?(m.side=tg,m.needsUpdate=!0,ga(m,L,q),m.side=bt,m.needsUpdate=!0,ga(m,L,q),m.side=Nt):ga(m,L,q)}this.compile=function(m,L,q=null){q===null&&(q=m),D=cA.get(q),D.init(L),y.push(D),q.traverseVisible(function(v){v.isLight&&v.layers.test(L.layers)&&(D.pushLight(v),v.castShadow&&D.pushShadow(v))}),m!==q&&m.traverseVisible(function(v){v.isLight&&v.layers.test(L.layers)&&(D.pushLight(v),v.castShadow&&D.pushShadow(v))}),D.setupLights();const Y=new Set;return m.traverse(function(v){if(!(v.isMesh||v.isPoints||v.isLine||v.isSprite))return;const hA=v.material;if(hA)if(Array.isArray(hA))for(let _A=0;_A<hA.length;_A++){const lA=hA[_A];xc(lA,q,v),Y.add(lA)}else xc(hA,q,v),Y.add(hA)}),D=y.pop(),Y},this.compileAsync=function(m,L,q=null){const Y=this.compile(m,L,q);return new Promise(v=>{function hA(){if(Y.forEach(function(_A){u.get(_A).currentProgram.isReady()&&Y.delete(_A)}),Y.size===0){v(m);return}setTimeout(hA,10)}Ee.get("KHR_parallel_shader_compile")!==null?hA():setTimeout(hA,10)})};let Ds=null;function Ip(m){Ds&&Ds(m)}function lc(){vi.stop()}function fc(){vi.start()}const vi=new T0;vi.setAnimationLoop(Ip),typeof self<"u"&&vi.setContext(self),this.setAnimationLoop=function(m){Ds=m,BA.setAnimationLoop(m),m===null?vi.stop():vi.start()},BA.addEventListener("sessionstart",lc),BA.addEventListener("sessionend",fc),this.render=function(m,L){if(L!==void 0&&L.isCamera!==!0){ae("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(w===!0)return;const q=BA.enabled===!0&&BA.isPresenting===!0,Y=k!==null&&(K===null||q)&&k.begin(x,K);if(m.matrixWorldAutoUpdate===!0&&m.updateMatrixWorld(),L.parent===null&&L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),BA.enabled===!0&&BA.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(BA.cameraAutoUpdate===!0&&BA.updateCamera(L),L=BA.getCamera()),m.isScene===!0&&m.onBeforeRender(x,m,L,K),D=cA.get(m,y.length),D.init(L),y.push(D),Ze.multiplyMatrices(L.projectionMatrix,L.matrixWorldInverse),TA.setFromProjectionMatrix(Ze,nt,L.reversedDepth),Qe=this.localClippingEnabled,yA=mA.init(this.clippingPlanes,Qe),l=CA.get(m,p.length),l.init(),p.push(l),BA.enabled===!0&&BA.isPresenting===!0){const _A=x.xr.getDepthSensingMesh();_A!==null&&_s(_A,L,-1/0,x.sortObjects)}_s(m,L,0,x.sortObjects),l.finish(),x.sortObjects===!0&&l.sort(be,le),OA=BA.enabled===!1||BA.isPresenting===!1||BA.hasDepthSensing()===!1,OA&&rA.addToRenderList(l,m),this.info.render.frame++,yA===!0&&mA.beginShadows();const v=D.state.shadowsArray;if(SA.render(v,m,L),yA===!0&&mA.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Y&&k.hasRenderPass())===!1){const _A=l.opaque,lA=l.transmissive;if(D.setupLights(),L.isArrayCamera){const pA=L.cameras;if(lA.length>0)for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA];Dc(_A,lA,m,GA)}OA&&rA.render(m);for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA];uc(l,m,GA,GA.viewport)}}else lA.length>0&&Dc(_A,lA,m,L),OA&&rA.render(m),uc(l,m,L)}K!==null&&U===0&&(M.updateMultisampleRenderTarget(K),M.updateRenderTargetMipmap(K)),Y&&k.end(x),m.isScene===!0&&m.onAfterRender(x,m,L),DA.resetDefaultState(),P=-1,j=null,y.pop(),y.length>0?(D=y[y.length-1],yA===!0&&mA.setGlobalState(x.clippingPlanes,D.state.camera)):D=null,p.pop(),p.length>0?l=p[p.length-1]:l=null};function _s(m,L,q,Y){if(m.visible===!1)return;if(m.layers.test(L.layers)){if(m.isGroup)q=m.renderOrder;else if(m.isLOD)m.autoUpdate===!0&&m.update(L);else if(m.isLight)D.pushLight(m),m.castShadow&&D.pushShadow(m);else if(m.isSprite){if(!m.frustumCulled||TA.intersectsSprite(m)){Y&&ce.setFromMatrixPosition(m.matrixWorld).applyMatrix4(Ze);const _A=EA.update(m),lA=m.material;lA.visible&&l.push(m,_A,lA,q,ce.z,null)}}else if((m.isMesh||m.isLine||m.isPoints)&&(!m.frustumCulled||TA.intersectsObject(m))){const _A=EA.update(m),lA=m.material;if(Y&&(m.boundingSphere!==void 0?(m.boundingSphere===null&&m.computeBoundingSphere(),ce.copy(m.boundingSphere.center)):(_A.boundingSphere===null&&_A.computeBoundingSphere(),ce.copy(_A.boundingSphere.center)),ce.applyMatrix4(m.matrixWorld).applyMatrix4(Ze)),Array.isArray(lA)){const pA=_A.groups;for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA],jA=lA[GA.materialIndex];jA&&jA.visible&&l.push(m,_A,jA,q,ce.z,GA)}}else lA.visible&&l.push(m,_A,lA,q,ce.z,null)}}const hA=m.children;for(let _A=0,lA=hA.length;_A<lA;_A++)_s(hA[_A],L,q,Y)}function uc(m,L,q,Y){const{opaque:v,transmissive:hA,transparent:_A}=m;D.setupLightsView(q),yA===!0&&mA.setGlobalState(x.clippingPlanes,q),Y&&NA.viewport(H.copy(Y)),v.length>0&&ea(v,L,q),hA.length>0&&ea(hA,L,q),_A.length>0&&ea(_A,L,q),NA.buffers.depth.setTest(!0),NA.buffers.depth.setMask(!0),NA.buffers.color.setMask(!0),NA.setPolygonOffset(!1)}function Dc(m,L,q,Y){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(D.state.transmissionRenderTarget[Y.id]===void 0){const jA=Ee.has("EXT_color_buffer_half_float")||Ee.has("EXT_color_buffer_float");D.state.transmissionRenderTarget[Y.id]=new st(1,1,{generateMipmaps:!0,type:jA?Rt:Sg,minFilter:yi,samples:we.samples,stencilBuffer:I,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ce.workingColorSpace})}const hA=D.state.transmissionRenderTarget[Y.id],_A=Y.viewport||H;hA.setSize(_A.z*x.transmissionResolutionScale,_A.w*x.transmissionResolutionScale);const lA=x.getRenderTarget(),pA=x.getActiveCubeFace(),RA=x.getActiveMipmapLevel();x.setRenderTarget(hA),x.getClearColor(xA),sA=x.getClearAlpha(),sA<1&&x.setClearColor(16777215,.5),x.clear(),OA&&rA.render(q);const FA=x.toneMapping;x.toneMapping=ot;const GA=Y.viewport;if(Y.viewport!==void 0&&(Y.viewport=void 0),D.setupLightsView(Y),yA===!0&&mA.setGlobalState(x.clippingPlanes,Y),ea(m,q,Y),M.updateMultisampleRenderTarget(hA),M.updateRenderTargetMipmap(hA),Ee.has("WEBGL_multisampled_render_to_texture")===!1){let jA=!1;for(let fe=0,Fe=L.length;fe<Fe;fe++){const Ue=L[fe],{object:_e,geometry:MA,material:de,group:ne}=Ue;if(de.side===Nt&&_e.layers.test(Y.layers)){const yg=de.side;de.side=tg,de.needsUpdate=!0,_c(_e,q,Y,MA,de,ne),de.side=yg,de.needsUpdate=!0,jA=!0}}jA===!0&&(M.updateMultisampleRenderTarget(hA),M.updateRenderTargetMipmap(hA))}x.setRenderTarget(lA,pA,RA),x.setClearColor(xA,sA),GA!==void 0&&(Y.viewport=GA),x.toneMapping=FA}function ea(m,L,q){const Y=L.isScene===!0?L.overrideMaterial:null;for(let v=0,hA=m.length;v<hA;v++){const _A=m[v],{object:lA,geometry:pA,group:RA}=_A;let FA=_A.material;FA.allowOverride===!0&&Y!==null&&(FA=Y),lA.layers.test(q.layers)&&_c(lA,L,q,pA,FA,RA)}}function _c(m,L,q,Y,v,hA){m.onBeforeRender(x,L,q,Y,v,hA),m.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse,m.matrixWorld),m.normalMatrix.getNormalMatrix(m.modelViewMatrix),v.onBeforeRender(x,L,q,Y,m,hA),v.transparent===!0&&v.side===Nt&&v.forceSinglePass===!1?(v.side=tg,v.needsUpdate=!0,x.renderBufferDirect(q,L,Y,v,m,hA),v.side=bt,v.needsUpdate=!0,x.renderBufferDirect(q,L,Y,v,m,hA),v.side=Nt):x.renderBufferDirect(q,L,Y,v,m,hA),m.onAfterRender(x,L,q,Y,v,hA)}function ga(m,L,q){L.isScene!==!0&&(L=De);const Y=u.get(m),v=D.state.lights,hA=D.state.shadowsArray,_A=v.state.version,lA=bA.getParameters(m,v.state,hA,L,q),pA=bA.getProgramCacheKey(lA);let RA=Y.programs;Y.environment=m.isMeshStandardMaterial?L.environment:null,Y.fog=L.fog,Y.envMap=(m.isMeshStandardMaterial?gA:X).get(m.envMap||Y.environment),Y.envMapRotation=Y.environment!==null&&m.envMap===null?L.environmentRotation:m.envMapRotation,RA===void 0&&(m.addEventListener("dispose",ht),RA=new Map,Y.programs=RA);let FA=RA.get(pA);if(FA!==void 0){if(Y.currentProgram===FA&&Y.lightsStateVersion===_A)return pc(m,lA),FA}else lA.uniforms=bA.getUniforms(m),m.onBeforeCompile(lA,x),FA=bA.acquireProgram(lA,pA),RA.set(pA,FA),Y.uniforms=lA.uniforms;const GA=Y.uniforms;return(!m.isShaderMaterial&&!m.isRawShaderMaterial||m.clipping===!0)&&(GA.clippingPlanes=mA.uniform),pc(m,lA),Y.needsLights=ap(m),Y.lightsStateVersion=_A,Y.needsLights&&(GA.ambientLightColor.value=v.state.ambient,GA.lightProbe.value=v.state.probe,GA.directionalLights.value=v.state.directional,GA.directionalLightShadows.value=v.state.directionalShadow,GA.spotLights.value=v.state.spot,GA.spotLightShadows.value=v.state.spotShadow,GA.rectAreaLights.value=v.state.rectArea,GA.ltc_1.value=v.state.rectAreaLTC1,GA.ltc_2.value=v.state.rectAreaLTC2,GA.pointLights.value=v.state.point,GA.pointLightShadows.value=v.state.pointShadow,GA.hemisphereLights.value=v.state.hemi,GA.directionalShadowMap.value=v.state.directionalShadowMap,GA.directionalShadowMatrix.value=v.state.directionalShadowMatrix,GA.spotShadowMap.value=v.state.spotShadowMap,GA.spotLightMatrix.value=v.state.spotLightMatrix,GA.spotLightMap.value=v.state.spotLightMap,GA.pointShadowMap.value=v.state.pointShadowMap,GA.pointShadowMatrix.value=v.state.pointShadowMatrix),Y.currentProgram=FA,Y.uniformsList=null,FA}function wc(m){if(m.uniformsList===null){const L=m.currentProgram.getUniforms();m.uniformsList=Oo.seqWithValue(L.seq,m.uniforms)}return m.uniformsList}function pc(m,L){const q=u.get(m);q.outputColorSpace=L.outputColorSpace,q.batching=L.batching,q.batchingColor=L.batchingColor,q.instancing=L.instancing,q.instancingColor=L.instancingColor,q.instancingMorph=L.instancingMorph,q.skinning=L.skinning,q.morphTargets=L.morphTargets,q.morphNormals=L.morphNormals,q.morphColors=L.morphColors,q.morphTargetsCount=L.morphTargetsCount,q.numClippingPlanes=L.numClippingPlanes,q.numIntersection=L.numClipIntersection,q.vertexAlphas=L.vertexAlphas,q.vertexTangents=L.vertexTangents,q.toneMapping=L.toneMapping}function Cp(m,L,q,Y,v){L.isScene!==!0&&(L=De),M.resetTextureUnits();const hA=L.fog,_A=Y.isMeshStandardMaterial?L.environment:null,lA=K===null?x.outputColorSpace:K.isXRRenderTarget===!0?K.texture.colorSpace:sI,pA=(Y.isMeshStandardMaterial?gA:X).get(Y.envMap||_A),RA=Y.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,FA=!!q.attributes.tangent&&(!!Y.normalMap||Y.anisotropy>0),GA=!!q.morphAttributes.position,jA=!!q.morphAttributes.normal,fe=!!q.morphAttributes.color;let Fe=ot;Y.toneMapped&&(K===null||K.isXRRenderTarget===!0)&&(Fe=x.toneMapping);const Ue=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,_e=Ue!==void 0?Ue.length:0,MA=u.get(Y),de=D.state.lights;if(yA===!0&&(Qe===!0||m!==j)){const ng=m===j&&Y.id===P;mA.setState(Y,m,ng)}let ne=!1;Y.version===MA.__version?(MA.needsLights&&MA.lightsStateVersion!==de.state.version||MA.outputColorSpace!==lA||v.isBatchedMesh&&MA.batching===!1||!v.isBatchedMesh&&MA.batching===!0||v.isBatchedMesh&&MA.batchingColor===!0&&v.colorTexture===null||v.isBatchedMesh&&MA.batchingColor===!1&&v.colorTexture!==null||v.isInstancedMesh&&MA.instancing===!1||!v.isInstancedMesh&&MA.instancing===!0||v.isSkinnedMesh&&MA.skinning===!1||!v.isSkinnedMesh&&MA.skinning===!0||v.isInstancedMesh&&MA.instancingColor===!0&&v.instanceColor===null||v.isInstancedMesh&&MA.instancingColor===!1&&v.instanceColor!==null||v.isInstancedMesh&&MA.instancingMorph===!0&&v.morphTexture===null||v.isInstancedMesh&&MA.instancingMorph===!1&&v.morphTexture!==null||MA.envMap!==pA||Y.fog===!0&&MA.fog!==hA||MA.numClippingPlanes!==void 0&&(MA.numClippingPlanes!==mA.numPlanes||MA.numIntersection!==mA.numIntersection)||MA.vertexAlphas!==RA||MA.vertexTangents!==FA||MA.morphTargets!==GA||MA.morphNormals!==jA||MA.morphColors!==fe||MA.toneMapping!==Fe||MA.morphTargetsCount!==_e)&&(ne=!0):(ne=!0,MA.__version=Y.version);let yg=MA.currentProgram;ne===!0&&(yg=ga(Y,L,v));let RI=!1,bg=!1,mC=!1;const me=yg.getUniforms(),dg=MA.uniforms;if(NA.useProgram(yg.program)&&(RI=!0,bg=!0,mC=!0),Y.id!==P&&(P=Y.id,bg=!0),RI||j!==m){NA.buffers.depth.getReversed()&&m.reversedDepth!==!0&&(m._reversedDepth=!0,m.updateProjectionMatrix()),me.setValue(R,"projectionMatrix",m.projectionMatrix),me.setValue(R,"viewMatrix",m.matrixWorldInverse);const xg=me.map.cameraPosition;xg!==void 0&&xg.setValue(R,oe.setFromMatrixPosition(m.matrixWorld)),we.logarithmicDepthBuffer&&me.setValue(R,"logDepthBufFC",2/(Math.log(m.far+1)/Math.LN2)),(Y.isMeshPhongMaterial||Y.isMeshToonMaterial||Y.isMeshLambertMaterial||Y.isMeshBasicMaterial||Y.isMeshStandardMaterial||Y.isShaderMaterial)&&me.setValue(R,"isOrthographic",m.isOrthographicCamera===!0),j!==m&&(j=m,bg=!0,mC=!0)}if(MA.needsLights&&(de.state.directionalShadowMap.length>0&&me.setValue(R,"directionalShadowMap",de.state.directionalShadowMap,M),de.state.spotShadowMap.length>0&&me.setValue(R,"spotShadowMap",de.state.spotShadowMap,M),de.state.pointShadowMap.length>0&&me.setValue(R,"pointShadowMap",de.state.pointShadowMap,M)),v.isSkinnedMesh){me.setOptional(R,v,"bindMatrix"),me.setOptional(R,v,"bindMatrixInverse");const ng=v.skeleton;ng&&(ng.boneTexture===null&&ng.computeBoneTexture(),me.setValue(R,"boneTexture",ng.boneTexture,M))}v.isBatchedMesh&&(me.setOptional(R,v,"batchingTexture"),me.setValue(R,"batchingTexture",v._matricesTexture,M),me.setOptional(R,v,"batchingIdTexture"),me.setValue(R,"batchingIdTexture",v._indirectTexture,M),me.setOptional(R,v,"batchingColorTexture"),v._colorsTexture!==null&&me.setValue(R,"batchingColorTexture",v._colorsTexture,M));const Fg=q.morphAttributes;if((Fg.position!==void 0||Fg.normal!==void 0||Fg.color!==void 0)&&VA.update(v,q,yg),(bg||MA.receiveShadow!==v.receiveShadow)&&(MA.receiveShadow=v.receiveShadow,me.setValue(R,"receiveShadow",v.receiveShadow)),Y.isMeshGouraudMaterial&&Y.envMap!==null&&(dg.envMap.value=pA,dg.flipEnvMap.value=pA.isCubeTexture&&pA.isRenderTargetTexture===!1?-1:1),Y.isMeshStandardMaterial&&Y.envMap===null&&L.environment!==null&&(dg.envMapIntensity.value=L.environmentIntensity),dg.dfgLUT!==void 0&&(dg.dfgLUT.value=bw()),bg&&(me.setValue(R,"toneMappingExposure",x.toneMappingExposure),MA.needsLights&&op(dg,mC),hA&&Y.fog===!0&&UA.refreshFogUniforms(dg,hA),UA.refreshMaterialUniforms(dg,Y,vA,JA,D.state.transmissionRenderTarget[m.id]),Oo.upload(R,wc(MA),dg,M)),Y.isShaderMaterial&&Y.uniformsNeedUpdate===!0&&(Oo.upload(R,wc(MA),dg,M),Y.uniformsNeedUpdate=!1),Y.isSpriteMaterial&&me.setValue(R,"center",v.center),me.setValue(R,"modelViewMatrix",v.modelViewMatrix),me.setValue(R,"normalMatrix",v.normalMatrix),me.setValue(R,"modelMatrix",v.matrixWorld),Y.isShaderMaterial||Y.isRawShaderMaterial){const ng=Y.uniformsGroups;for(let xg=0,ws=ng.length;xg<ws;xg++){const Ji=ng[xg];IA.update(Ji,yg),IA.bind(Ji,yg)}}return yg}function op(m,L){m.ambientLightColor.needsUpdate=L,m.lightProbe.needsUpdate=L,m.directionalLights.needsUpdate=L,m.directionalLightShadows.needsUpdate=L,m.pointLights.needsUpdate=L,m.pointLightShadows.needsUpdate=L,m.spotLights.needsUpdate=L,m.spotLightShadows.needsUpdate=L,m.rectAreaLights.needsUpdate=L,m.hemisphereLights.needsUpdate=L}function ap(m){return m.isMeshLambertMaterial||m.isMeshToonMaterial||m.isMeshPhongMaterial||m.isMeshStandardMaterial||m.isShadowMaterial||m.isShaderMaterial&&m.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return U},this.getRenderTarget=function(){return K},this.setRenderTargetTextures=function(m,L,q){const Y=u.get(m);Y.__autoAllocateDepthBuffer=m.resolveDepthBuffer===!1,Y.__autoAllocateDepthBuffer===!1&&(Y.__useRenderToTexture=!1),u.get(m.texture).__webglTexture=L,u.get(m.depthTexture).__webglTexture=Y.__autoAllocateDepthBuffer?void 0:q,Y.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(m,L){const q=u.get(m);q.__webglFramebuffer=L,q.__useDefaultFramebuffer=L===void 0};const Qp=R.createFramebuffer();this.setRenderTarget=function(m,L=0,q=0){K=m,N=L,U=q;let Y=null,v=!1,hA=!1;if(m){const lA=u.get(m);if(lA.__useDefaultFramebuffer!==void 0){NA.bindFramebuffer(R.FRAMEBUFFER,lA.__webglFramebuffer),H.copy(m.viewport),O.copy(m.scissor),z=m.scissorTest,NA.viewport(H),NA.scissor(O),NA.setScissorTest(z),P=-1;return}else if(lA.__webglFramebuffer===void 0)M.setupRenderTarget(m);else if(lA.__hasExternalTextures)M.rebindTextures(m,u.get(m.texture).__webglTexture,u.get(m.depthTexture).__webglTexture);else if(m.depthBuffer){const FA=m.depthTexture;if(lA.__boundDepthTexture!==FA){if(FA!==null&&u.has(FA)&&(m.width!==FA.image.width||m.height!==FA.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");M.setupDepthRenderbuffer(m)}}const pA=m.texture;(pA.isData3DTexture||pA.isDataArrayTexture||pA.isCompressedArrayTexture)&&(hA=!0);const RA=u.get(m).__webglFramebuffer;m.isWebGLCubeRenderTarget?(Array.isArray(RA[L])?Y=RA[L][q]:Y=RA[L],v=!0):m.samples>0&&M.useMultisampledRTT(m)===!1?Y=u.get(m).__webglMultisampledFramebuffer:Array.isArray(RA)?Y=RA[q]:Y=RA,H.copy(m.viewport),O.copy(m.scissor),z=m.scissorTest}else H.copy(Z).multiplyScalar(vA).floor(),O.copy(iA).multiplyScalar(vA).floor(),z=wA;if(q!==0&&(Y=Qp),NA.bindFramebuffer(R.FRAMEBUFFER,Y)&&NA.drawBuffers(m,Y),NA.viewport(H),NA.scissor(O),NA.setScissorTest(z),v){const lA=u.get(m.texture);R.framebufferTexture2D(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_CUBE_MAP_POSITIVE_X+L,lA.__webglTexture,q)}else if(hA){const lA=L;for(let pA=0;pA<m.textures.length;pA++){const RA=u.get(m.textures[pA]);R.framebufferTextureLayer(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0+pA,RA.__webglTexture,q,lA)}}else if(m!==null&&q!==0){const lA=u.get(m.texture);R.framebufferTexture2D(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,lA.__webglTexture,q)}P=-1},this.readRenderTargetPixels=function(m,L,q,Y,v,hA,_A,lA=0){if(!(m&&m.isWebGLRenderTarget)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let pA=u.get(m).__webglFramebuffer;if(m.isWebGLCubeRenderTarget&&_A!==void 0&&(pA=pA[_A]),pA){NA.bindFramebuffer(R.FRAMEBUFFER,pA);try{const RA=m.textures[lA],FA=RA.format,GA=RA.type;if(!we.textureFormatReadable(FA)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!we.textureTypeReadable(GA)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}L>=0&&L<=m.width-Y&&q>=0&&q<=m.height-v&&(m.textures.length>1&&R.readBuffer(R.COLOR_ATTACHMENT0+lA),R.readPixels(L,q,Y,v,aA.convert(FA),aA.convert(GA),hA))}finally{const RA=K!==null?u.get(K).__webglFramebuffer:null;NA.bindFramebuffer(R.FRAMEBUFFER,RA)}}},this.readRenderTargetPixelsAsync=async function(m,L,q,Y,v,hA,_A,lA=0){if(!(m&&m.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let pA=u.get(m).__webglFramebuffer;if(m.isWebGLCubeRenderTarget&&_A!==void 0&&(pA=pA[_A]),pA)if(L>=0&&L<=m.width-Y&&q>=0&&q<=m.height-v){NA.bindFramebuffer(R.FRAMEBUFFER,pA);const RA=m.textures[lA],FA=RA.format,GA=RA.type;if(!we.textureFormatReadable(FA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!we.textureTypeReadable(GA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const jA=R.createBuffer();R.bindBuffer(R.PIXEL_PACK_BUFFER,jA),R.bufferData(R.PIXEL_PACK_BUFFER,hA.byteLength,R.STREAM_READ),m.textures.length>1&&R.readBuffer(R.COLOR_ATTACHMENT0+lA),R.readPixels(L,q,Y,v,aA.convert(FA),aA.convert(GA),0);const fe=K!==null?u.get(K).__webglFramebuffer:null;NA.bindFramebuffer(R.FRAMEBUFFER,fe);const Fe=R.fenceSync(R.SYNC_GPU_COMMANDS_COMPLETE,0);return R.flush(),await kf(R,Fe,4),R.bindBuffer(R.PIXEL_PACK_BUFFER,jA),R.getBufferSubData(R.PIXEL_PACK_BUFFER,0,hA),R.deleteBuffer(jA),R.deleteSync(Fe),hA}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(m,L=null,q=0){const Y=Math.pow(2,-q),v=Math.floor(m.image.width*Y),hA=Math.floor(m.image.height*Y),_A=L!==null?L.x:0,lA=L!==null?L.y:0;M.setTexture2D(m,0),R.copyTexSubImage2D(R.TEXTURE_2D,q,0,0,_A,lA,v,hA),NA.unbindTexture()};const np=R.createFramebuffer(),sp=R.createFramebuffer();this.copyTextureToTexture=function(m,L,q=null,Y=null,v=0,hA=null){hA===null&&(v!==0?(oC("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),hA=v,v=0):hA=0);let _A,lA,pA,RA,FA,GA,jA,fe,Fe;const Ue=m.isCompressedTexture?m.mipmaps[hA]:m.image;if(q!==null)_A=q.max.x-q.min.x,lA=q.max.y-q.min.y,pA=q.isBox3?q.max.z-q.min.z:1,RA=q.min.x,FA=q.min.y,GA=q.isBox3?q.min.z:0;else{const Fg=Math.pow(2,-v);_A=Math.floor(Ue.width*Fg),lA=Math.floor(Ue.height*Fg),m.isDataArrayTexture?pA=Ue.depth:m.isData3DTexture?pA=Math.floor(Ue.depth*Fg):pA=1,RA=0,FA=0,GA=0}Y!==null?(jA=Y.x,fe=Y.y,Fe=Y.z):(jA=0,fe=0,Fe=0);const _e=aA.convert(L.format),MA=aA.convert(L.type);let de;L.isData3DTexture?(M.setTexture3D(L,0),de=R.TEXTURE_3D):L.isDataArrayTexture||L.isCompressedArrayTexture?(M.setTexture2DArray(L,0),de=R.TEXTURE_2D_ARRAY):(M.setTexture2D(L,0),de=R.TEXTURE_2D),R.pixelStorei(R.UNPACK_FLIP_Y_WEBGL,L.flipY),R.pixelStorei(R.UNPACK_PREMULTIPLY_ALPHA_WEBGL,L.premultiplyAlpha),R.pixelStorei(R.UNPACK_ALIGNMENT,L.unpackAlignment);const ne=R.getParameter(R.UNPACK_ROW_LENGTH),yg=R.getParameter(R.UNPACK_IMAGE_HEIGHT),RI=R.getParameter(R.UNPACK_SKIP_PIXELS),bg=R.getParameter(R.UNPACK_SKIP_ROWS),mC=R.getParameter(R.UNPACK_SKIP_IMAGES);R.pixelStorei(R.UNPACK_ROW_LENGTH,Ue.width),R.pixelStorei(R.UNPACK_IMAGE_HEIGHT,Ue.height),R.pixelStorei(R.UNPACK_SKIP_PIXELS,RA),R.pixelStorei(R.UNPACK_SKIP_ROWS,FA),R.pixelStorei(R.UNPACK_SKIP_IMAGES,GA);const me=m.isDataArrayTexture||m.isData3DTexture,dg=L.isDataArrayTexture||L.isData3DTexture;if(m.isDepthTexture){const Fg=u.get(m),ng=u.get(L),xg=u.get(Fg.__renderTarget),ws=u.get(ng.__renderTarget);NA.bindFramebuffer(R.READ_FRAMEBUFFER,xg.__webglFramebuffer),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,ws.__webglFramebuffer);for(let Ji=0;Ji<pA;Ji++)me&&(R.framebufferTextureLayer(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,u.get(m).__webglTexture,v,GA+Ji),R.framebufferTextureLayer(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,u.get(L).__webglTexture,hA,Fe+Ji)),R.blitFramebuffer(RA,FA,_A,lA,jA,fe,_A,lA,R.DEPTH_BUFFER_BIT,R.NEAREST);NA.bindFramebuffer(R.READ_FRAMEBUFFER,null),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,null)}else if(v!==0||m.isRenderTargetTexture||u.has(m)){const Fg=u.get(m),ng=u.get(L);NA.bindFramebuffer(R.READ_FRAMEBUFFER,np),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,sp);for(let xg=0;xg<pA;xg++)me?R.framebufferTextureLayer(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,Fg.__webglTexture,v,GA+xg):R.framebufferTexture2D(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,Fg.__webglTexture,v),dg?R.framebufferTextureLayer(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,ng.__webglTexture,hA,Fe+xg):R.framebufferTexture2D(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,ng.__webglTexture,hA),v!==0?R.blitFramebuffer(RA,FA,_A,lA,jA,fe,_A,lA,R.COLOR_BUFFER_BIT,R.NEAREST):dg?R.copyTexSubImage3D(de,hA,jA,fe,Fe+xg,RA,FA,_A,lA):R.copyTexSubImage2D(de,hA,jA,fe,RA,FA,_A,lA);NA.bindFramebuffer(R.READ_FRAMEBUFFER,null),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,null)}else dg?m.isDataTexture||m.isData3DTexture?R.texSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,MA,Ue.data):L.isCompressedArrayTexture?R.compressedTexSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,Ue.data):R.texSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,MA,Ue):m.isDataTexture?R.texSubImage2D(R.TEXTURE_2D,hA,jA,fe,_A,lA,_e,MA,Ue.data):m.isCompressedTexture?R.compressedTexSubImage2D(R.TEXTURE_2D,hA,jA,fe,Ue.width,Ue.height,_e,Ue.data):R.texSubImage2D(R.TEXTURE_2D,hA,jA,fe,_A,lA,_e,MA,Ue);R.pixelStorei(R.UNPACK_ROW_LENGTH,ne),R.pixelStorei(R.UNPACK_IMAGE_HEIGHT,yg),R.pixelStorei(R.UNPACK_SKIP_PIXELS,RI),R.pixelStorei(R.UNPACK_SKIP_ROWS,bg),R.pixelStorei(R.UNPACK_SKIP_IMAGES,mC),hA===0&&L.generateMipmaps&&R.generateMipmap(de),NA.unbindTexture()},this.initRenderTarget=function(m){u.get(m).__webglFramebuffer===void 0&&M.setupRenderTarget(m)},this.initTexture=function(m){m.isCubeTexture?M.setTextureCube(m,0):m.isData3DTexture?M.setTexture3D(m,0):m.isDataArrayTexture||m.isCompressedArrayTexture?M.setTexture2DArray(m,0):M.setTexture2D(m,0),NA.unbindTexture()},this.resetState=function(){N=0,U=0,K=null,NA.reset(),DA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return nt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const e=this.getContext();e.drawingBufferColorSpace=Ce._getDrawingBufferColorSpace(A),e.unpackColorSpace=Ce._getUnpackColorSpace()}}const Sw=`
|
|
4165
|
+
}`;class Dw{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,e){if(this.texture===null){const g=new v0(A.texture);(A.depthNear!==e.depthNear||A.depthFar!==e.depthFar)&&(this.depthNear=A.depthNear,this.depthFar=A.depthFar),this.texture=g}}getMesh(A){if(this.texture!==null&&this.mesh===null){const e=A.cameras[0].viewport,g=new Gg({vertexShader:fw,fragmentShader:uw,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Xg(new To(20,20),g)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class _w extends EI{constructor(A,e){super();const g=this;let i=null,I=1,C=null,o="local-floor",a=1,Q=null,n=null,s=null,B=null,E=null,d=null;const c=typeof XRWebGLBinding<"u",h=new Dw,r={},f=e.getContextAttributes();let _=null,l=null;const D=[],p=[],y=new Be;let k=null;const x=new Mg;x.viewport=new Ke;const w=new Mg;w.viewport=new Ke;const N=[x,w],U=new Bu;let K=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getTargetRaySpace()},this.getControllerGrip=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getGripSpace()},this.getHand=function(Z){let iA=D[Z];return iA===void 0&&(iA=new as,D[Z]=iA),iA.getHandSpace()};function j(Z){const iA=p.indexOf(Z.inputSource);if(iA===-1)return;const wA=D[iA];wA!==void 0&&(wA.update(Z.inputSource,Z.frame,Q||C),wA.dispatchEvent({type:Z.type,data:Z.inputSource}))}function H(){i.removeEventListener("select",j),i.removeEventListener("selectstart",j),i.removeEventListener("selectend",j),i.removeEventListener("squeeze",j),i.removeEventListener("squeezestart",j),i.removeEventListener("squeezeend",j),i.removeEventListener("end",H),i.removeEventListener("inputsourceschange",O);for(let Z=0;Z<D.length;Z++){const iA=p[Z];iA!==null&&(p[Z]=null,D[Z].disconnect(iA))}K=null,P=null,h.reset();for(const Z in r)delete r[Z];A.setRenderTarget(_),E=null,B=null,s=null,i=null,l=null,le.stop(),g.isPresenting=!1,A.setPixelRatio(k),A.setSize(y.width,y.height,!1),g.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){I=Z,g.isPresenting===!0&&LA("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){o=Z,g.isPresenting===!0&&LA("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return Q||C},this.setReferenceSpace=function(Z){Q=Z},this.getBaseLayer=function(){return B!==null?B:E},this.getBinding=function(){return s===null&&c&&(s=new XRWebGLBinding(i,e)),s},this.getFrame=function(){return d},this.getSession=function(){return i},this.setSession=async function(Z){if(i=Z,i!==null){if(_=A.getRenderTarget(),i.addEventListener("select",j),i.addEventListener("selectstart",j),i.addEventListener("selectend",j),i.addEventListener("squeeze",j),i.addEventListener("squeezestart",j),i.addEventListener("squeezeend",j),i.addEventListener("end",H),i.addEventListener("inputsourceschange",O),f.xrCompatible!==!0&&await e.makeXRCompatible(),k=A.getPixelRatio(),A.getSize(y),c&&"createProjectionLayer"in XRWebGLBinding.prototype){let wA=null,TA=null,yA=null;f.depth&&(yA=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,wA=f.stencil?Ni:Gt,TA=f.stencil?CC:at);const Qe={colorFormat:e.RGBA8,depthFormat:yA,scaleFactor:I};s=this.getBinding(),B=s.createProjectionLayer(Qe),i.updateRenderState({layers:[B]}),A.setPixelRatio(1),A.setSize(B.textureWidth,B.textureHeight,!1),l=new st(B.textureWidth,B.textureHeight,{format:Hg,type:Sg,depthTexture:new dC(B.textureWidth,B.textureHeight,TA,void 0,void 0,void 0,void 0,void 0,void 0,wA),stencilBuffer:f.stencil,colorSpace:A.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:B.ignoreDepthValues===!1,resolveStencilBuffer:B.ignoreDepthValues===!1})}else{const wA={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:I};E=new XRWebGLLayer(i,e,wA),i.updateRenderState({baseLayer:E}),A.setPixelRatio(1),A.setSize(E.framebufferWidth,E.framebufferHeight,!1),l=new st(E.framebufferWidth,E.framebufferHeight,{format:Hg,type:Sg,colorSpace:A.outputColorSpace,stencilBuffer:f.stencil,resolveDepthBuffer:E.ignoreDepthValues===!1,resolveStencilBuffer:E.ignoreDepthValues===!1})}l.isXRRenderTarget=!0,this.setFoveation(a),Q=null,C=await i.requestReferenceSpace(o),le.setContext(i),le.start(),g.isPresenting=!0,g.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function O(Z){for(let iA=0;iA<Z.removed.length;iA++){const wA=Z.removed[iA],TA=p.indexOf(wA);TA>=0&&(p[TA]=null,D[TA].disconnect(wA))}for(let iA=0;iA<Z.added.length;iA++){const wA=Z.added[iA];let TA=p.indexOf(wA);if(TA===-1){for(let Qe=0;Qe<D.length;Qe++)if(Qe>=p.length){p.push(wA),TA=Qe;break}else if(p[Qe]===null){p[Qe]=wA,TA=Qe;break}if(TA===-1)break}const yA=D[TA];yA&&yA.connect(wA)}}const z=new J,xA=new J;function sA(Z,iA,wA){z.setFromMatrixPosition(iA.matrixWorld),xA.setFromMatrixPosition(wA.matrixWorld);const TA=z.distanceTo(xA),yA=iA.projectionMatrix.elements,Qe=wA.projectionMatrix.elements,Ze=yA[14]/(yA[10]-1),oe=yA[14]/(yA[10]+1),ce=(yA[9]+1)/yA[5],De=(yA[9]-1)/yA[5],OA=(yA[8]-1)/yA[0],qe=(Qe[8]+1)/Qe[0],R=Ze*OA,He=Ze*qe,Ee=TA/(-OA+qe),we=Ee*-OA;if(iA.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(we),Z.translateZ(Ee),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),yA[10]===-1)Z.projectionMatrix.copy(iA.projectionMatrix),Z.projectionMatrixInverse.copy(iA.projectionMatrixInverse);else{const NA=Ze+Ee,b=oe+Ee,u=R-we,M=He+(TA-we),X=ce*oe/b*NA,gA=De*oe/b*NA;Z.projectionMatrix.makePerspective(u,M,X,gA,NA,b),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function fA(Z,iA){iA===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(iA.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;let iA=Z.near,wA=Z.far;h.texture!==null&&(h.depthNear>0&&(iA=h.depthNear),h.depthFar>0&&(wA=h.depthFar)),U.near=w.near=x.near=iA,U.far=w.far=x.far=wA,(K!==U.near||P!==U.far)&&(i.updateRenderState({depthNear:U.near,depthFar:U.far}),K=U.near,P=U.far),U.layers.mask=Z.layers.mask|6,x.layers.mask=U.layers.mask&3,w.layers.mask=U.layers.mask&5;const TA=Z.parent,yA=U.cameras;fA(U,TA);for(let Qe=0;Qe<yA.length;Qe++)fA(yA[Qe],TA);yA.length===2?sA(U,x,w):U.projectionMatrix.copy(x.projectionMatrix),JA(Z,U,TA)};function JA(Z,iA,wA){wA===null?Z.matrix.copy(iA.matrixWorld):(Z.matrix.copy(wA.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(iA.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(iA.projectionMatrix),Z.projectionMatrixInverse.copy(iA.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=Kn*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return U},this.getFoveation=function(){if(!(B===null&&E===null))return a},this.setFoveation=function(Z){a=Z,B!==null&&(B.fixedFoveation=Z),E!==null&&E.fixedFoveation!==void 0&&(E.fixedFoveation=Z)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(U)},this.getCameraTexture=function(Z){return r[Z]};let vA=null;function be(Z,iA){if(n=iA.getViewerPose(Q||C),d=iA,n!==null){const wA=n.views;E!==null&&(A.setRenderTargetFramebuffer(l,E.framebuffer),A.setRenderTarget(l));let TA=!1;wA.length!==U.cameras.length&&(U.cameras.length=0,TA=!0);for(let oe=0;oe<wA.length;oe++){const ce=wA[oe];let De=null;if(E!==null)De=E.getViewport(ce);else{const qe=s.getViewSubImage(B,ce);De=qe.viewport,oe===0&&(A.setRenderTargetTextures(l,qe.colorTexture,qe.depthStencilTexture),A.setRenderTarget(l))}let OA=N[oe];OA===void 0&&(OA=new Mg,OA.layers.enable(oe),OA.viewport=new Ke,N[oe]=OA),OA.matrix.fromArray(ce.transform.matrix),OA.matrix.decompose(OA.position,OA.quaternion,OA.scale),OA.projectionMatrix.fromArray(ce.projectionMatrix),OA.projectionMatrixInverse.copy(OA.projectionMatrix).invert(),OA.viewport.set(De.x,De.y,De.width,De.height),oe===0&&(U.matrix.copy(OA.matrix),U.matrix.decompose(U.position,U.quaternion,U.scale)),TA===!0&&U.cameras.push(OA)}const yA=i.enabledFeatures;if(yA&&yA.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&c){s=g.getBinding();const oe=s.getDepthInformation(wA[0]);oe&&oe.isValid&&oe.texture&&h.init(oe,i.renderState)}if(yA&&yA.includes("camera-access")&&c){A.state.unbindTexture(),s=g.getBinding();for(let oe=0;oe<wA.length;oe++){const ce=wA[oe].camera;if(ce){let De=r[ce];De||(De=new v0,r[ce]=De);const OA=s.getCameraImage(ce);De.sourceTexture=OA}}}}for(let wA=0;wA<D.length;wA++){const TA=p[wA],yA=D[wA];TA!==null&&yA!==void 0&&yA.update(TA,iA,Q||C)}vA&&vA(Z,iA),iA.detectedPlanes&&g.dispatchEvent({type:"planesdetected",data:iA}),d=null}const le=new T0;le.setAnimationLoop(be),this.setAnimationLoop=function(Z){vA=Z},this.dispose=function(){}}}const Li=new Lt,ww=new Ye;function pw(t,A){function e(h,r){h.matrixAutoUpdate===!0&&h.updateMatrix(),r.value.copy(h.matrix)}function g(h,r){r.color.getRGB(h.fogColor.value,R0(t)),r.isFog?(h.fogNear.value=r.near,h.fogFar.value=r.far):r.isFogExp2&&(h.fogDensity.value=r.density)}function i(h,r,f,_,l){r.isMeshBasicMaterial||r.isMeshLambertMaterial?I(h,r):r.isMeshToonMaterial?(I(h,r),s(h,r)):r.isMeshPhongMaterial?(I(h,r),n(h,r)):r.isMeshStandardMaterial?(I(h,r),B(h,r),r.isMeshPhysicalMaterial&&E(h,r,l)):r.isMeshMatcapMaterial?(I(h,r),d(h,r)):r.isMeshDepthMaterial?I(h,r):r.isMeshDistanceMaterial?(I(h,r),c(h,r)):r.isMeshNormalMaterial?I(h,r):r.isLineBasicMaterial?(C(h,r),r.isLineDashedMaterial&&o(h,r)):r.isPointsMaterial?a(h,r,f,_):r.isSpriteMaterial?Q(h,r):r.isShadowMaterial?(h.color.value.copy(r.color),h.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}function I(h,r){h.opacity.value=r.opacity,r.color&&h.diffuse.value.copy(r.color),r.emissive&&h.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(h.map.value=r.map,e(r.map,h.mapTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.bumpMap&&(h.bumpMap.value=r.bumpMap,e(r.bumpMap,h.bumpMapTransform),h.bumpScale.value=r.bumpScale,r.side===tg&&(h.bumpScale.value*=-1)),r.normalMap&&(h.normalMap.value=r.normalMap,e(r.normalMap,h.normalMapTransform),h.normalScale.value.copy(r.normalScale),r.side===tg&&h.normalScale.value.negate()),r.displacementMap&&(h.displacementMap.value=r.displacementMap,e(r.displacementMap,h.displacementMapTransform),h.displacementScale.value=r.displacementScale,h.displacementBias.value=r.displacementBias),r.emissiveMap&&(h.emissiveMap.value=r.emissiveMap,e(r.emissiveMap,h.emissiveMapTransform)),r.specularMap&&(h.specularMap.value=r.specularMap,e(r.specularMap,h.specularMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest);const f=A.get(r),_=f.envMap,l=f.envMapRotation;_&&(h.envMap.value=_,Li.copy(l),Li.x*=-1,Li.y*=-1,Li.z*=-1,_.isCubeTexture&&_.isRenderTargetTexture===!1&&(Li.y*=-1,Li.z*=-1),h.envMapRotation.value.setFromMatrix4(ww.makeRotationFromEuler(Li)),h.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,h.reflectivity.value=r.reflectivity,h.ior.value=r.ior,h.refractionRatio.value=r.refractionRatio),r.lightMap&&(h.lightMap.value=r.lightMap,h.lightMapIntensity.value=r.lightMapIntensity,e(r.lightMap,h.lightMapTransform)),r.aoMap&&(h.aoMap.value=r.aoMap,h.aoMapIntensity.value=r.aoMapIntensity,e(r.aoMap,h.aoMapTransform))}function C(h,r){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,r.map&&(h.map.value=r.map,e(r.map,h.mapTransform))}function o(h,r){h.dashSize.value=r.dashSize,h.totalSize.value=r.dashSize+r.gapSize,h.scale.value=r.scale}function a(h,r,f,_){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,h.size.value=r.size*f,h.scale.value=_*.5,r.map&&(h.map.value=r.map,e(r.map,h.uvTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest)}function Q(h,r){h.diffuse.value.copy(r.color),h.opacity.value=r.opacity,h.rotation.value=r.rotation,r.map&&(h.map.value=r.map,e(r.map,h.mapTransform)),r.alphaMap&&(h.alphaMap.value=r.alphaMap,e(r.alphaMap,h.alphaMapTransform)),r.alphaTest>0&&(h.alphaTest.value=r.alphaTest)}function n(h,r){h.specular.value.copy(r.specular),h.shininess.value=Math.max(r.shininess,1e-4)}function s(h,r){r.gradientMap&&(h.gradientMap.value=r.gradientMap)}function B(h,r){h.metalness.value=r.metalness,r.metalnessMap&&(h.metalnessMap.value=r.metalnessMap,e(r.metalnessMap,h.metalnessMapTransform)),h.roughness.value=r.roughness,r.roughnessMap&&(h.roughnessMap.value=r.roughnessMap,e(r.roughnessMap,h.roughnessMapTransform)),r.envMap&&(h.envMapIntensity.value=r.envMapIntensity)}function E(h,r,f){h.ior.value=r.ior,r.sheen>0&&(h.sheenColor.value.copy(r.sheenColor).multiplyScalar(r.sheen),h.sheenRoughness.value=r.sheenRoughness,r.sheenColorMap&&(h.sheenColorMap.value=r.sheenColorMap,e(r.sheenColorMap,h.sheenColorMapTransform)),r.sheenRoughnessMap&&(h.sheenRoughnessMap.value=r.sheenRoughnessMap,e(r.sheenRoughnessMap,h.sheenRoughnessMapTransform))),r.clearcoat>0&&(h.clearcoat.value=r.clearcoat,h.clearcoatRoughness.value=r.clearcoatRoughness,r.clearcoatMap&&(h.clearcoatMap.value=r.clearcoatMap,e(r.clearcoatMap,h.clearcoatMapTransform)),r.clearcoatRoughnessMap&&(h.clearcoatRoughnessMap.value=r.clearcoatRoughnessMap,e(r.clearcoatRoughnessMap,h.clearcoatRoughnessMapTransform)),r.clearcoatNormalMap&&(h.clearcoatNormalMap.value=r.clearcoatNormalMap,e(r.clearcoatNormalMap,h.clearcoatNormalMapTransform),h.clearcoatNormalScale.value.copy(r.clearcoatNormalScale),r.side===tg&&h.clearcoatNormalScale.value.negate())),r.dispersion>0&&(h.dispersion.value=r.dispersion),r.iridescence>0&&(h.iridescence.value=r.iridescence,h.iridescenceIOR.value=r.iridescenceIOR,h.iridescenceThicknessMinimum.value=r.iridescenceThicknessRange[0],h.iridescenceThicknessMaximum.value=r.iridescenceThicknessRange[1],r.iridescenceMap&&(h.iridescenceMap.value=r.iridescenceMap,e(r.iridescenceMap,h.iridescenceMapTransform)),r.iridescenceThicknessMap&&(h.iridescenceThicknessMap.value=r.iridescenceThicknessMap,e(r.iridescenceThicknessMap,h.iridescenceThicknessMapTransform))),r.transmission>0&&(h.transmission.value=r.transmission,h.transmissionSamplerMap.value=f.texture,h.transmissionSamplerSize.value.set(f.width,f.height),r.transmissionMap&&(h.transmissionMap.value=r.transmissionMap,e(r.transmissionMap,h.transmissionMapTransform)),h.thickness.value=r.thickness,r.thicknessMap&&(h.thicknessMap.value=r.thicknessMap,e(r.thicknessMap,h.thicknessMapTransform)),h.attenuationDistance.value=r.attenuationDistance,h.attenuationColor.value.copy(r.attenuationColor)),r.anisotropy>0&&(h.anisotropyVector.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation)),r.anisotropyMap&&(h.anisotropyMap.value=r.anisotropyMap,e(r.anisotropyMap,h.anisotropyMapTransform))),h.specularIntensity.value=r.specularIntensity,h.specularColor.value.copy(r.specularColor),r.specularColorMap&&(h.specularColorMap.value=r.specularColorMap,e(r.specularColorMap,h.specularColorMapTransform)),r.specularIntensityMap&&(h.specularIntensityMap.value=r.specularIntensityMap,e(r.specularIntensityMap,h.specularIntensityMapTransform))}function d(h,r){r.matcap&&(h.matcap.value=r.matcap)}function c(h,r){const f=A.get(r).light;h.referencePosition.value.setFromMatrixPosition(f.matrixWorld),h.nearDistance.value=f.shadow.camera.near,h.farDistance.value=f.shadow.camera.far}return{refreshFogUniforms:g,refreshMaterialUniforms:i}}function mw(t,A,e,g){let i={},I={},C=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function a(f,_){const l=_.program;g.uniformBlockBinding(f,l)}function Q(f,_){let l=i[f.id];l===void 0&&(d(f),l=n(f),i[f.id]=l,f.addEventListener("dispose",h));const D=_.program;g.updateUBOMapping(f,D);const p=A.render.frame;I[f.id]!==p&&(B(f),I[f.id]=p)}function n(f){const _=s();f.__bindingPointIndex=_;const l=t.createBuffer(),D=f.__size,p=f.usage;return t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,D,p),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,_,l),l}function s(){for(let f=0;f<o;f++)if(C.indexOf(f)===-1)return C.push(f),f;return ae("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function B(f){const _=i[f.id],l=f.uniforms,D=f.__cache;t.bindBuffer(t.UNIFORM_BUFFER,_);for(let p=0,y=l.length;p<y;p++){const k=Array.isArray(l[p])?l[p]:[l[p]];for(let x=0,w=k.length;x<w;x++){const N=k[x];if(E(N,p,x,D)===!0){const U=N.__offset,K=Array.isArray(N.value)?N.value:[N.value];let P=0;for(let j=0;j<K.length;j++){const H=K[j],O=c(H);typeof H=="number"||typeof H=="boolean"?(N.__data[0]=H,t.bufferSubData(t.UNIFORM_BUFFER,U+P,N.__data)):H.isMatrix3?(N.__data[0]=H.elements[0],N.__data[1]=H.elements[1],N.__data[2]=H.elements[2],N.__data[3]=0,N.__data[4]=H.elements[3],N.__data[5]=H.elements[4],N.__data[6]=H.elements[5],N.__data[7]=0,N.__data[8]=H.elements[6],N.__data[9]=H.elements[7],N.__data[10]=H.elements[8],N.__data[11]=0):(H.toArray(N.__data,P),P+=O.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,U,N.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function E(f,_,l,D){const p=f.value,y=_+"_"+l;if(D[y]===void 0)return typeof p=="number"||typeof p=="boolean"?D[y]=p:D[y]=p.clone(),!0;{const k=D[y];if(typeof p=="number"||typeof p=="boolean"){if(k!==p)return D[y]=p,!0}else if(k.equals(p)===!1)return k.copy(p),!0}return!1}function d(f){const _=f.uniforms;let l=0;const D=16;for(let y=0,k=_.length;y<k;y++){const x=Array.isArray(_[y])?_[y]:[_[y]];for(let w=0,N=x.length;w<N;w++){const U=x[w],K=Array.isArray(U.value)?U.value:[U.value];for(let P=0,j=K.length;P<j;P++){const H=K[P],O=c(H),z=l%D,xA=z%O.boundary,sA=z+xA;l+=xA,sA!==0&&D-sA<O.storage&&(l+=D-sA),U.__data=new Float32Array(O.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=l,l+=O.storage}}}const p=l%D;return p>0&&(l+=D-p),f.__size=l,f.__cache={},this}function c(f){const _={boundary:0,storage:0};return typeof f=="number"||typeof f=="boolean"?(_.boundary=4,_.storage=4):f.isVector2?(_.boundary=8,_.storage=8):f.isVector3||f.isColor?(_.boundary=16,_.storage=12):f.isVector4?(_.boundary=16,_.storage=16):f.isMatrix3?(_.boundary=48,_.storage=48):f.isMatrix4?(_.boundary=64,_.storage=64):f.isTexture?LA("WebGLRenderer: Texture samplers can not be part of an uniforms group."):LA("WebGLRenderer: Unsupported uniform value type.",f),_}function h(f){const _=f.target;_.removeEventListener("dispose",h);const l=C.indexOf(_.__bindingPointIndex);C.splice(l,1),t.deleteBuffer(i[_.id]),delete i[_.id],delete I[_.id]}function r(){for(const f in i)t.deleteBuffer(i[f]);C=[],i={},I={}}return{bind:a,update:Q,dispose:r}}const yw=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 rt=null;function bw(){return rt===null&&(rt=new iu(yw,16,16,nI,Rt),rt.name="DFG_LUT",rt.minFilter=Ag,rt.magFilter=Ag,rt.wrapS=kt,rt.wrapT=kt,rt.generateMipmaps=!1,rt.needsUpdate=!0),rt}class Nw{constructor(A={}){const{canvas:e=Sf(),context:g=null,depth:i=!0,stencil:I=!1,alpha:C=!1,antialias:o=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:Q=!1,powerPreference:n="default",failIfMajorPerformanceCaveat:s=!1,reversedDepthBuffer:B=!1,outputBufferType:E=Sg}=A;this.isWebGLRenderer=!0;let d;if(g!==null){if(typeof WebGLRenderingContext<"u"&&g instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=g.getContextAttributes().alpha}else d=C;const c=E,h=new Set([en,An,$Q]),r=new Set([Sg,at,IC,CC,ZQ,zQ]),f=new Uint32Array(4),_=new Int32Array(4);let l=null,D=null;const p=[],y=[];let k=null;this.domElement=e,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=ot,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const x=this;let w=!1;this._outputColorSpace=kg;let N=0,U=0,K=null,P=-1,j=null;const H=new Ke,O=new Ke;let z=null;const xA=new Ie(0);let sA=0,fA=e.width,JA=e.height,vA=1,be=null,le=null;const Z=new Ke(0,0,fA,JA),iA=new Ke(0,0,fA,JA);let wA=!1;const TA=new K0;let yA=!1,Qe=!1;const Ze=new Ye,oe=new J,ce=new Ke,De={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let OA=!1;function qe(){return K===null?vA:1}let R=g;function He(m,L){return e.getContext(m,L)}try{const m={alpha:!0,depth:i,stencil:I,antialias:o,premultipliedAlpha:a,preserveDrawingBuffer:Q,powerPreference:n,failIfMajorPerformanceCaveat:s};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${MQ}`),e.addEventListener("webglcontextlost",KA,!1),e.addEventListener("webglcontextrestored",pe,!1),e.addEventListener("webglcontextcreationerror",he,!1),R===null){const L="webgl2";if(R=He(L,m),R===null)throw He(L)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(m){throw ae("WebGLRenderer: "+m.message),m}let Ee,we,NA,b,u,M,X,gA,V,kA,EA,bA,UA,CA,cA,mA,SA,rA,VA,G,uA,aA,DA,IA;function eA(){Ee=new b_(R),Ee.init(),aA=new lw(R,Ee),we=new l_(R,Ee,A,aA),NA=new dw(R,Ee),we.reversedDepthBuffer&&B&&NA.buffers.depth.setReversed(!0),b=new k_(R),u=new gw,M=new xw(R,Ee,NA,u,we,aA,b),X=new u_(x),gA=new y_(x),V=new cu(R),DA=new d_(R,V),kA=new N_(R,V,b,DA),EA=new G_(R,kA,V,b),VA=new R_(R,we,M),mA=new f_(u),bA=new ew(x,X,gA,Ee,we,DA,mA),UA=new pw(x,u),CA=new iw,cA=new nw(Ee),rA=new h_(x,X,gA,NA,EA,d,a),SA=new cw(x,EA,we),IA=new mw(R,b,we,NA),G=new x_(R,Ee,b),uA=new S_(R,Ee,b),b.programs=bA.programs,x.capabilities=we,x.extensions=Ee,x.properties=u,x.renderLists=CA,x.shadowMap=SA,x.state=NA,x.info=b}eA(),c!==Sg&&(k=new F_(c,e.width,e.height,i,I));const BA=new _w(x,R);this.xr=BA,this.getContext=function(){return R},this.getContextAttributes=function(){return R.getContextAttributes()},this.forceContextLoss=function(){const m=Ee.get("WEBGL_lose_context");m&&m.loseContext()},this.forceContextRestore=function(){const m=Ee.get("WEBGL_lose_context");m&&m.restoreContext()},this.getPixelRatio=function(){return vA},this.setPixelRatio=function(m){m!==void 0&&(vA=m,this.setSize(fA,JA,!1))},this.getSize=function(m){return m.set(fA,JA)},this.setSize=function(m,L,q=!0){if(BA.isPresenting){LA("WebGLRenderer: Can't change size while VR device is presenting.");return}fA=m,JA=L,e.width=Math.floor(m*vA),e.height=Math.floor(L*vA),q===!0&&(e.style.width=m+"px",e.style.height=L+"px"),k!==null&&k.setSize(e.width,e.height),this.setViewport(0,0,m,L)},this.getDrawingBufferSize=function(m){return m.set(fA*vA,JA*vA).floor()},this.setDrawingBufferSize=function(m,L,q){fA=m,JA=L,vA=q,e.width=Math.floor(m*q),e.height=Math.floor(L*q),this.setViewport(0,0,m,L)},this.setEffects=function(m){if(c===Sg){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(m){for(let L=0;L<m.length;L++)if(m[L].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(H)},this.getViewport=function(m){return m.copy(Z)},this.setViewport=function(m,L,q,Y){m.isVector4?Z.set(m.x,m.y,m.z,m.w):Z.set(m,L,q,Y),NA.viewport(H.copy(Z).multiplyScalar(vA).round())},this.getScissor=function(m){return m.copy(iA)},this.setScissor=function(m,L,q,Y){m.isVector4?iA.set(m.x,m.y,m.z,m.w):iA.set(m,L,q,Y),NA.scissor(O.copy(iA).multiplyScalar(vA).round())},this.getScissorTest=function(){return wA},this.setScissorTest=function(m){NA.setScissorTest(wA=m)},this.setOpaqueSort=function(m){be=m},this.setTransparentSort=function(m){le=m},this.getClearColor=function(m){return m.copy(rA.getClearColor())},this.setClearColor=function(){rA.setClearColor(...arguments)},this.getClearAlpha=function(){return rA.getClearAlpha()},this.setClearAlpha=function(){rA.setClearAlpha(...arguments)},this.clear=function(m=!0,L=!0,q=!0){let Y=0;if(m){let v=!1;if(K!==null){const hA=K.texture.format;v=h.has(hA)}if(v){const hA=K.texture.type,_A=r.has(hA),lA=rA.getClearColor(),pA=rA.getClearAlpha(),RA=lA.r,FA=lA.g,GA=lA.b;_A?(f[0]=RA,f[1]=FA,f[2]=GA,f[3]=pA,R.clearBufferuiv(R.COLOR,0,f)):(_[0]=RA,_[1]=FA,_[2]=GA,_[3]=pA,R.clearBufferiv(R.COLOR,0,_))}else Y|=R.COLOR_BUFFER_BIT}L&&(Y|=R.DEPTH_BUFFER_BIT),q&&(Y|=R.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),R.clear(Y)},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(){e.removeEventListener("webglcontextlost",KA,!1),e.removeEventListener("webglcontextrestored",pe,!1),e.removeEventListener("webglcontextcreationerror",he,!1),rA.dispose(),CA.dispose(),cA.dispose(),u.dispose(),X.dispose(),gA.dispose(),EA.dispose(),DA.dispose(),IA.dispose(),bA.dispose(),BA.dispose(),BA.removeEventListener("sessionstart",lc),BA.removeEventListener("sessionend",fc),Ji.stop()};function KA(m){m.preventDefault(),s0("WebGLRenderer: Context Lost."),w=!0}function pe(){s0("WebGLRenderer: Context Restored."),w=!1;const m=b.autoReset,L=SA.enabled,q=SA.autoUpdate,Y=SA.needsUpdate,v=SA.type;eA(),b.autoReset=m,SA.enabled=L,SA.autoUpdate=q,SA.needsUpdate=Y,SA.type=v}function he(m){ae("WebGLRenderer: A WebGL context could not be created. Reason: ",m.statusMessage)}function ht(m){const L=m.target;L.removeEventListener("dispose",ht),Yt(L)}function Yt(m){ip(m),u.remove(m)}function ip(m){const L=u.get(m).programs;L!==void 0&&(L.forEach(function(q){bA.releaseProgram(q)}),m.isShaderMaterial&&bA.releaseShaderCache(m))}this.renderBufferDirect=function(m,L,q,Y,v,hA){L===null&&(L=De);const _A=v.isMesh&&v.matrixWorld.determinant()<0,lA=Cp(m,L,q,Y,v);NA.setMaterial(Y,_A);let pA=q.index,RA=1;if(Y.wireframe===!0){if(pA=kA.getWireframeAttribute(q),pA===void 0)return;RA=2}const FA=q.drawRange,GA=q.attributes.position;let jA=FA.start*RA,fe=(FA.start+FA.count)*RA;hA!==null&&(jA=Math.max(jA,hA.start*RA),fe=Math.min(fe,(hA.start+hA.count)*RA)),pA!==null?(jA=Math.max(jA,0),fe=Math.min(fe,pA.count)):GA!=null&&(jA=Math.max(jA,0),fe=Math.min(fe,GA.count));const Fe=fe-jA;if(Fe<0||Fe===1/0)return;DA.setup(v,Y,lA,q,pA);let Ue,_e=G;if(pA!==null&&(Ue=V.get(pA),_e=uA,_e.setIndex(Ue)),v.isMesh)Y.wireframe===!0?(NA.setLineWidth(Y.wireframeLinewidth*qe()),_e.setMode(R.LINES)):_e.setMode(R.TRIANGLES);else if(v.isLine){let MA=Y.linewidth;MA===void 0&&(MA=1),NA.setLineWidth(MA*qe()),v.isLineSegments?_e.setMode(R.LINES):v.isLineLoop?_e.setMode(R.LINE_LOOP):_e.setMode(R.LINE_STRIP)}else v.isPoints?_e.setMode(R.POINTS):v.isSprite&&_e.setMode(R.TRIANGLES);if(v.isBatchedMesh)if(v._multiDrawInstances!==null)oC("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_e.renderMultiDrawInstances(v._multiDrawStarts,v._multiDrawCounts,v._multiDrawCount,v._multiDrawInstances);else if(Ee.get("WEBGL_multi_draw"))_e.renderMultiDraw(v._multiDrawStarts,v._multiDrawCounts,v._multiDrawCount);else{const MA=v._multiDrawStarts,de=v._multiDrawCounts,ne=v._multiDrawCount,yg=pA?V.get(pA).bytesPerElement:1,RI=u.get(Y).currentProgram.getUniforms();for(let bg=0;bg<ne;bg++)RI.setValue(R,"_gl_DrawID",bg),_e.render(MA[bg]/yg,de[bg])}else if(v.isInstancedMesh)_e.renderInstances(jA,Fe,v.count);else if(q.isInstancedBufferGeometry){const MA=q._maxInstanceCount!==void 0?q._maxInstanceCount:1/0,de=Math.min(q.instanceCount,MA);_e.renderInstances(jA,Fe,de)}else _e.render(jA,Fe)};function xc(m,L,q){m.transparent===!0&&m.side===Nt&&m.forceSinglePass===!1?(m.side=tg,m.needsUpdate=!0,ga(m,L,q),m.side=bt,m.needsUpdate=!0,ga(m,L,q),m.side=Nt):ga(m,L,q)}this.compile=function(m,L,q=null){q===null&&(q=m),D=cA.get(q),D.init(L),y.push(D),q.traverseVisible(function(v){v.isLight&&v.layers.test(L.layers)&&(D.pushLight(v),v.castShadow&&D.pushShadow(v))}),m!==q&&m.traverseVisible(function(v){v.isLight&&v.layers.test(L.layers)&&(D.pushLight(v),v.castShadow&&D.pushShadow(v))}),D.setupLights();const Y=new Set;return m.traverse(function(v){if(!(v.isMesh||v.isPoints||v.isLine||v.isSprite))return;const hA=v.material;if(hA)if(Array.isArray(hA))for(let _A=0;_A<hA.length;_A++){const lA=hA[_A];xc(lA,q,v),Y.add(lA)}else xc(hA,q,v),Y.add(hA)}),D=y.pop(),Y},this.compileAsync=function(m,L,q=null){const Y=this.compile(m,L,q);return new Promise(v=>{function hA(){if(Y.forEach(function(_A){u.get(_A).currentProgram.isReady()&&Y.delete(_A)}),Y.size===0){v(m);return}setTimeout(hA,10)}Ee.get("KHR_parallel_shader_compile")!==null?hA():setTimeout(hA,10)})};let Ds=null;function Ip(m){Ds&&Ds(m)}function lc(){Ji.stop()}function fc(){Ji.start()}const Ji=new T0;Ji.setAnimationLoop(Ip),typeof self<"u"&&Ji.setContext(self),this.setAnimationLoop=function(m){Ds=m,BA.setAnimationLoop(m),m===null?Ji.stop():Ji.start()},BA.addEventListener("sessionstart",lc),BA.addEventListener("sessionend",fc),this.render=function(m,L){if(L!==void 0&&L.isCamera!==!0){ae("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(w===!0)return;const q=BA.enabled===!0&&BA.isPresenting===!0,Y=k!==null&&(K===null||q)&&k.begin(x,K);if(m.matrixWorldAutoUpdate===!0&&m.updateMatrixWorld(),L.parent===null&&L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),BA.enabled===!0&&BA.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(BA.cameraAutoUpdate===!0&&BA.updateCamera(L),L=BA.getCamera()),m.isScene===!0&&m.onBeforeRender(x,m,L,K),D=cA.get(m,y.length),D.init(L),y.push(D),Ze.multiplyMatrices(L.projectionMatrix,L.matrixWorldInverse),TA.setFromProjectionMatrix(Ze,nt,L.reversedDepth),Qe=this.localClippingEnabled,yA=mA.init(this.clippingPlanes,Qe),l=CA.get(m,p.length),l.init(),p.push(l),BA.enabled===!0&&BA.isPresenting===!0){const _A=x.xr.getDepthSensingMesh();_A!==null&&_s(_A,L,-1/0,x.sortObjects)}_s(m,L,0,x.sortObjects),l.finish(),x.sortObjects===!0&&l.sort(be,le),OA=BA.enabled===!1||BA.isPresenting===!1||BA.hasDepthSensing()===!1,OA&&rA.addToRenderList(l,m),this.info.render.frame++,yA===!0&&mA.beginShadows();const v=D.state.shadowsArray;if(SA.render(v,m,L),yA===!0&&mA.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Y&&k.hasRenderPass())===!1){const _A=l.opaque,lA=l.transmissive;if(D.setupLights(),L.isArrayCamera){const pA=L.cameras;if(lA.length>0)for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA];Dc(_A,lA,m,GA)}OA&&rA.render(m);for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA];uc(l,m,GA,GA.viewport)}}else lA.length>0&&Dc(_A,lA,m,L),OA&&rA.render(m),uc(l,m,L)}K!==null&&U===0&&(M.updateMultisampleRenderTarget(K),M.updateRenderTargetMipmap(K)),Y&&k.end(x),m.isScene===!0&&m.onAfterRender(x,m,L),DA.resetDefaultState(),P=-1,j=null,y.pop(),y.length>0?(D=y[y.length-1],yA===!0&&mA.setGlobalState(x.clippingPlanes,D.state.camera)):D=null,p.pop(),p.length>0?l=p[p.length-1]:l=null};function _s(m,L,q,Y){if(m.visible===!1)return;if(m.layers.test(L.layers)){if(m.isGroup)q=m.renderOrder;else if(m.isLOD)m.autoUpdate===!0&&m.update(L);else if(m.isLight)D.pushLight(m),m.castShadow&&D.pushShadow(m);else if(m.isSprite){if(!m.frustumCulled||TA.intersectsSprite(m)){Y&&ce.setFromMatrixPosition(m.matrixWorld).applyMatrix4(Ze);const _A=EA.update(m),lA=m.material;lA.visible&&l.push(m,_A,lA,q,ce.z,null)}}else if((m.isMesh||m.isLine||m.isPoints)&&(!m.frustumCulled||TA.intersectsObject(m))){const _A=EA.update(m),lA=m.material;if(Y&&(m.boundingSphere!==void 0?(m.boundingSphere===null&&m.computeBoundingSphere(),ce.copy(m.boundingSphere.center)):(_A.boundingSphere===null&&_A.computeBoundingSphere(),ce.copy(_A.boundingSphere.center)),ce.applyMatrix4(m.matrixWorld).applyMatrix4(Ze)),Array.isArray(lA)){const pA=_A.groups;for(let RA=0,FA=pA.length;RA<FA;RA++){const GA=pA[RA],jA=lA[GA.materialIndex];jA&&jA.visible&&l.push(m,_A,jA,q,ce.z,GA)}}else lA.visible&&l.push(m,_A,lA,q,ce.z,null)}}const hA=m.children;for(let _A=0,lA=hA.length;_A<lA;_A++)_s(hA[_A],L,q,Y)}function uc(m,L,q,Y){const{opaque:v,transmissive:hA,transparent:_A}=m;D.setupLightsView(q),yA===!0&&mA.setGlobalState(x.clippingPlanes,q),Y&&NA.viewport(H.copy(Y)),v.length>0&&ea(v,L,q),hA.length>0&&ea(hA,L,q),_A.length>0&&ea(_A,L,q),NA.buffers.depth.setTest(!0),NA.buffers.depth.setMask(!0),NA.buffers.color.setMask(!0),NA.setPolygonOffset(!1)}function Dc(m,L,q,Y){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(D.state.transmissionRenderTarget[Y.id]===void 0){const jA=Ee.has("EXT_color_buffer_half_float")||Ee.has("EXT_color_buffer_float");D.state.transmissionRenderTarget[Y.id]=new st(1,1,{generateMipmaps:!0,type:jA?Rt:Sg,minFilter:bi,samples:we.samples,stencilBuffer:I,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ce.workingColorSpace})}const hA=D.state.transmissionRenderTarget[Y.id],_A=Y.viewport||H;hA.setSize(_A.z*x.transmissionResolutionScale,_A.w*x.transmissionResolutionScale);const lA=x.getRenderTarget(),pA=x.getActiveCubeFace(),RA=x.getActiveMipmapLevel();x.setRenderTarget(hA),x.getClearColor(xA),sA=x.getClearAlpha(),sA<1&&x.setClearColor(16777215,.5),x.clear(),OA&&rA.render(q);const FA=x.toneMapping;x.toneMapping=ot;const GA=Y.viewport;if(Y.viewport!==void 0&&(Y.viewport=void 0),D.setupLightsView(Y),yA===!0&&mA.setGlobalState(x.clippingPlanes,Y),ea(m,q,Y),M.updateMultisampleRenderTarget(hA),M.updateRenderTargetMipmap(hA),Ee.has("WEBGL_multisampled_render_to_texture")===!1){let jA=!1;for(let fe=0,Fe=L.length;fe<Fe;fe++){const Ue=L[fe],{object:_e,geometry:MA,material:de,group:ne}=Ue;if(de.side===Nt&&_e.layers.test(Y.layers)){const yg=de.side;de.side=tg,de.needsUpdate=!0,_c(_e,q,Y,MA,de,ne),de.side=yg,de.needsUpdate=!0,jA=!0}}jA===!0&&(M.updateMultisampleRenderTarget(hA),M.updateRenderTargetMipmap(hA))}x.setRenderTarget(lA,pA,RA),x.setClearColor(xA,sA),GA!==void 0&&(Y.viewport=GA),x.toneMapping=FA}function ea(m,L,q){const Y=L.isScene===!0?L.overrideMaterial:null;for(let v=0,hA=m.length;v<hA;v++){const _A=m[v],{object:lA,geometry:pA,group:RA}=_A;let FA=_A.material;FA.allowOverride===!0&&Y!==null&&(FA=Y),lA.layers.test(q.layers)&&_c(lA,L,q,pA,FA,RA)}}function _c(m,L,q,Y,v,hA){m.onBeforeRender(x,L,q,Y,v,hA),m.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse,m.matrixWorld),m.normalMatrix.getNormalMatrix(m.modelViewMatrix),v.onBeforeRender(x,L,q,Y,m,hA),v.transparent===!0&&v.side===Nt&&v.forceSinglePass===!1?(v.side=tg,v.needsUpdate=!0,x.renderBufferDirect(q,L,Y,v,m,hA),v.side=bt,v.needsUpdate=!0,x.renderBufferDirect(q,L,Y,v,m,hA),v.side=Nt):x.renderBufferDirect(q,L,Y,v,m,hA),m.onAfterRender(x,L,q,Y,v,hA)}function ga(m,L,q){L.isScene!==!0&&(L=De);const Y=u.get(m),v=D.state.lights,hA=D.state.shadowsArray,_A=v.state.version,lA=bA.getParameters(m,v.state,hA,L,q),pA=bA.getProgramCacheKey(lA);let RA=Y.programs;Y.environment=m.isMeshStandardMaterial?L.environment:null,Y.fog=L.fog,Y.envMap=(m.isMeshStandardMaterial?gA:X).get(m.envMap||Y.environment),Y.envMapRotation=Y.environment!==null&&m.envMap===null?L.environmentRotation:m.envMapRotation,RA===void 0&&(m.addEventListener("dispose",ht),RA=new Map,Y.programs=RA);let FA=RA.get(pA);if(FA!==void 0){if(Y.currentProgram===FA&&Y.lightsStateVersion===_A)return pc(m,lA),FA}else lA.uniforms=bA.getUniforms(m),m.onBeforeCompile(lA,x),FA=bA.acquireProgram(lA,pA),RA.set(pA,FA),Y.uniforms=lA.uniforms;const GA=Y.uniforms;return(!m.isShaderMaterial&&!m.isRawShaderMaterial||m.clipping===!0)&&(GA.clippingPlanes=mA.uniform),pc(m,lA),Y.needsLights=ap(m),Y.lightsStateVersion=_A,Y.needsLights&&(GA.ambientLightColor.value=v.state.ambient,GA.lightProbe.value=v.state.probe,GA.directionalLights.value=v.state.directional,GA.directionalLightShadows.value=v.state.directionalShadow,GA.spotLights.value=v.state.spot,GA.spotLightShadows.value=v.state.spotShadow,GA.rectAreaLights.value=v.state.rectArea,GA.ltc_1.value=v.state.rectAreaLTC1,GA.ltc_2.value=v.state.rectAreaLTC2,GA.pointLights.value=v.state.point,GA.pointLightShadows.value=v.state.pointShadow,GA.hemisphereLights.value=v.state.hemi,GA.directionalShadowMap.value=v.state.directionalShadowMap,GA.directionalShadowMatrix.value=v.state.directionalShadowMatrix,GA.spotShadowMap.value=v.state.spotShadowMap,GA.spotLightMatrix.value=v.state.spotLightMatrix,GA.spotLightMap.value=v.state.spotLightMap,GA.pointShadowMap.value=v.state.pointShadowMap,GA.pointShadowMatrix.value=v.state.pointShadowMatrix),Y.currentProgram=FA,Y.uniformsList=null,FA}function wc(m){if(m.uniformsList===null){const L=m.currentProgram.getUniforms();m.uniformsList=Oo.seqWithValue(L.seq,m.uniforms)}return m.uniformsList}function pc(m,L){const q=u.get(m);q.outputColorSpace=L.outputColorSpace,q.batching=L.batching,q.batchingColor=L.batchingColor,q.instancing=L.instancing,q.instancingColor=L.instancingColor,q.instancingMorph=L.instancingMorph,q.skinning=L.skinning,q.morphTargets=L.morphTargets,q.morphNormals=L.morphNormals,q.morphColors=L.morphColors,q.morphTargetsCount=L.morphTargetsCount,q.numClippingPlanes=L.numClippingPlanes,q.numIntersection=L.numClipIntersection,q.vertexAlphas=L.vertexAlphas,q.vertexTangents=L.vertexTangents,q.toneMapping=L.toneMapping}function Cp(m,L,q,Y,v){L.isScene!==!0&&(L=De),M.resetTextureUnits();const hA=L.fog,_A=Y.isMeshStandardMaterial?L.environment:null,lA=K===null?x.outputColorSpace:K.isXRRenderTarget===!0?K.texture.colorSpace:sI,pA=(Y.isMeshStandardMaterial?gA:X).get(Y.envMap||_A),RA=Y.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,FA=!!q.attributes.tangent&&(!!Y.normalMap||Y.anisotropy>0),GA=!!q.morphAttributes.position,jA=!!q.morphAttributes.normal,fe=!!q.morphAttributes.color;let Fe=ot;Y.toneMapped&&(K===null||K.isXRRenderTarget===!0)&&(Fe=x.toneMapping);const Ue=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,_e=Ue!==void 0?Ue.length:0,MA=u.get(Y),de=D.state.lights;if(yA===!0&&(Qe===!0||m!==j)){const ng=m===j&&Y.id===P;mA.setState(Y,m,ng)}let ne=!1;Y.version===MA.__version?(MA.needsLights&&MA.lightsStateVersion!==de.state.version||MA.outputColorSpace!==lA||v.isBatchedMesh&&MA.batching===!1||!v.isBatchedMesh&&MA.batching===!0||v.isBatchedMesh&&MA.batchingColor===!0&&v.colorTexture===null||v.isBatchedMesh&&MA.batchingColor===!1&&v.colorTexture!==null||v.isInstancedMesh&&MA.instancing===!1||!v.isInstancedMesh&&MA.instancing===!0||v.isSkinnedMesh&&MA.skinning===!1||!v.isSkinnedMesh&&MA.skinning===!0||v.isInstancedMesh&&MA.instancingColor===!0&&v.instanceColor===null||v.isInstancedMesh&&MA.instancingColor===!1&&v.instanceColor!==null||v.isInstancedMesh&&MA.instancingMorph===!0&&v.morphTexture===null||v.isInstancedMesh&&MA.instancingMorph===!1&&v.morphTexture!==null||MA.envMap!==pA||Y.fog===!0&&MA.fog!==hA||MA.numClippingPlanes!==void 0&&(MA.numClippingPlanes!==mA.numPlanes||MA.numIntersection!==mA.numIntersection)||MA.vertexAlphas!==RA||MA.vertexTangents!==FA||MA.morphTargets!==GA||MA.morphNormals!==jA||MA.morphColors!==fe||MA.toneMapping!==Fe||MA.morphTargetsCount!==_e)&&(ne=!0):(ne=!0,MA.__version=Y.version);let yg=MA.currentProgram;ne===!0&&(yg=ga(Y,L,v));let RI=!1,bg=!1,mC=!1;const me=yg.getUniforms(),dg=MA.uniforms;if(NA.useProgram(yg.program)&&(RI=!0,bg=!0,mC=!0),Y.id!==P&&(P=Y.id,bg=!0),RI||j!==m){NA.buffers.depth.getReversed()&&m.reversedDepth!==!0&&(m._reversedDepth=!0,m.updateProjectionMatrix()),me.setValue(R,"projectionMatrix",m.projectionMatrix),me.setValue(R,"viewMatrix",m.matrixWorldInverse);const xg=me.map.cameraPosition;xg!==void 0&&xg.setValue(R,oe.setFromMatrixPosition(m.matrixWorld)),we.logarithmicDepthBuffer&&me.setValue(R,"logDepthBufFC",2/(Math.log(m.far+1)/Math.LN2)),(Y.isMeshPhongMaterial||Y.isMeshToonMaterial||Y.isMeshLambertMaterial||Y.isMeshBasicMaterial||Y.isMeshStandardMaterial||Y.isShaderMaterial)&&me.setValue(R,"isOrthographic",m.isOrthographicCamera===!0),j!==m&&(j=m,bg=!0,mC=!0)}if(MA.needsLights&&(de.state.directionalShadowMap.length>0&&me.setValue(R,"directionalShadowMap",de.state.directionalShadowMap,M),de.state.spotShadowMap.length>0&&me.setValue(R,"spotShadowMap",de.state.spotShadowMap,M),de.state.pointShadowMap.length>0&&me.setValue(R,"pointShadowMap",de.state.pointShadowMap,M)),v.isSkinnedMesh){me.setOptional(R,v,"bindMatrix"),me.setOptional(R,v,"bindMatrixInverse");const ng=v.skeleton;ng&&(ng.boneTexture===null&&ng.computeBoneTexture(),me.setValue(R,"boneTexture",ng.boneTexture,M))}v.isBatchedMesh&&(me.setOptional(R,v,"batchingTexture"),me.setValue(R,"batchingTexture",v._matricesTexture,M),me.setOptional(R,v,"batchingIdTexture"),me.setValue(R,"batchingIdTexture",v._indirectTexture,M),me.setOptional(R,v,"batchingColorTexture"),v._colorsTexture!==null&&me.setValue(R,"batchingColorTexture",v._colorsTexture,M));const Fg=q.morphAttributes;if((Fg.position!==void 0||Fg.normal!==void 0||Fg.color!==void 0)&&VA.update(v,q,yg),(bg||MA.receiveShadow!==v.receiveShadow)&&(MA.receiveShadow=v.receiveShadow,me.setValue(R,"receiveShadow",v.receiveShadow)),Y.isMeshGouraudMaterial&&Y.envMap!==null&&(dg.envMap.value=pA,dg.flipEnvMap.value=pA.isCubeTexture&&pA.isRenderTargetTexture===!1?-1:1),Y.isMeshStandardMaterial&&Y.envMap===null&&L.environment!==null&&(dg.envMapIntensity.value=L.environmentIntensity),dg.dfgLUT!==void 0&&(dg.dfgLUT.value=bw()),bg&&(me.setValue(R,"toneMappingExposure",x.toneMappingExposure),MA.needsLights&&op(dg,mC),hA&&Y.fog===!0&&UA.refreshFogUniforms(dg,hA),UA.refreshMaterialUniforms(dg,Y,vA,JA,D.state.transmissionRenderTarget[m.id]),Oo.upload(R,wc(MA),dg,M)),Y.isShaderMaterial&&Y.uniformsNeedUpdate===!0&&(Oo.upload(R,wc(MA),dg,M),Y.uniformsNeedUpdate=!1),Y.isSpriteMaterial&&me.setValue(R,"center",v.center),me.setValue(R,"modelViewMatrix",v.modelViewMatrix),me.setValue(R,"normalMatrix",v.normalMatrix),me.setValue(R,"modelMatrix",v.matrixWorld),Y.isShaderMaterial||Y.isRawShaderMaterial){const ng=Y.uniformsGroups;for(let xg=0,ws=ng.length;xg<ws;xg++){const Yi=ng[xg];IA.update(Yi,yg),IA.bind(Yi,yg)}}return yg}function op(m,L){m.ambientLightColor.needsUpdate=L,m.lightProbe.needsUpdate=L,m.directionalLights.needsUpdate=L,m.directionalLightShadows.needsUpdate=L,m.pointLights.needsUpdate=L,m.pointLightShadows.needsUpdate=L,m.spotLights.needsUpdate=L,m.spotLightShadows.needsUpdate=L,m.rectAreaLights.needsUpdate=L,m.hemisphereLights.needsUpdate=L}function ap(m){return m.isMeshLambertMaterial||m.isMeshToonMaterial||m.isMeshPhongMaterial||m.isMeshStandardMaterial||m.isShadowMaterial||m.isShaderMaterial&&m.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return U},this.getRenderTarget=function(){return K},this.setRenderTargetTextures=function(m,L,q){const Y=u.get(m);Y.__autoAllocateDepthBuffer=m.resolveDepthBuffer===!1,Y.__autoAllocateDepthBuffer===!1&&(Y.__useRenderToTexture=!1),u.get(m.texture).__webglTexture=L,u.get(m.depthTexture).__webglTexture=Y.__autoAllocateDepthBuffer?void 0:q,Y.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(m,L){const q=u.get(m);q.__webglFramebuffer=L,q.__useDefaultFramebuffer=L===void 0};const Qp=R.createFramebuffer();this.setRenderTarget=function(m,L=0,q=0){K=m,N=L,U=q;let Y=null,v=!1,hA=!1;if(m){const lA=u.get(m);if(lA.__useDefaultFramebuffer!==void 0){NA.bindFramebuffer(R.FRAMEBUFFER,lA.__webglFramebuffer),H.copy(m.viewport),O.copy(m.scissor),z=m.scissorTest,NA.viewport(H),NA.scissor(O),NA.setScissorTest(z),P=-1;return}else if(lA.__webglFramebuffer===void 0)M.setupRenderTarget(m);else if(lA.__hasExternalTextures)M.rebindTextures(m,u.get(m.texture).__webglTexture,u.get(m.depthTexture).__webglTexture);else if(m.depthBuffer){const FA=m.depthTexture;if(lA.__boundDepthTexture!==FA){if(FA!==null&&u.has(FA)&&(m.width!==FA.image.width||m.height!==FA.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");M.setupDepthRenderbuffer(m)}}const pA=m.texture;(pA.isData3DTexture||pA.isDataArrayTexture||pA.isCompressedArrayTexture)&&(hA=!0);const RA=u.get(m).__webglFramebuffer;m.isWebGLCubeRenderTarget?(Array.isArray(RA[L])?Y=RA[L][q]:Y=RA[L],v=!0):m.samples>0&&M.useMultisampledRTT(m)===!1?Y=u.get(m).__webglMultisampledFramebuffer:Array.isArray(RA)?Y=RA[q]:Y=RA,H.copy(m.viewport),O.copy(m.scissor),z=m.scissorTest}else H.copy(Z).multiplyScalar(vA).floor(),O.copy(iA).multiplyScalar(vA).floor(),z=wA;if(q!==0&&(Y=Qp),NA.bindFramebuffer(R.FRAMEBUFFER,Y)&&NA.drawBuffers(m,Y),NA.viewport(H),NA.scissor(O),NA.setScissorTest(z),v){const lA=u.get(m.texture);R.framebufferTexture2D(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_CUBE_MAP_POSITIVE_X+L,lA.__webglTexture,q)}else if(hA){const lA=L;for(let pA=0;pA<m.textures.length;pA++){const RA=u.get(m.textures[pA]);R.framebufferTextureLayer(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0+pA,RA.__webglTexture,q,lA)}}else if(m!==null&&q!==0){const lA=u.get(m.texture);R.framebufferTexture2D(R.FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,lA.__webglTexture,q)}P=-1},this.readRenderTargetPixels=function(m,L,q,Y,v,hA,_A,lA=0){if(!(m&&m.isWebGLRenderTarget)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let pA=u.get(m).__webglFramebuffer;if(m.isWebGLCubeRenderTarget&&_A!==void 0&&(pA=pA[_A]),pA){NA.bindFramebuffer(R.FRAMEBUFFER,pA);try{const RA=m.textures[lA],FA=RA.format,GA=RA.type;if(!we.textureFormatReadable(FA)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!we.textureTypeReadable(GA)){ae("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}L>=0&&L<=m.width-Y&&q>=0&&q<=m.height-v&&(m.textures.length>1&&R.readBuffer(R.COLOR_ATTACHMENT0+lA),R.readPixels(L,q,Y,v,aA.convert(FA),aA.convert(GA),hA))}finally{const RA=K!==null?u.get(K).__webglFramebuffer:null;NA.bindFramebuffer(R.FRAMEBUFFER,RA)}}},this.readRenderTargetPixelsAsync=async function(m,L,q,Y,v,hA,_A,lA=0){if(!(m&&m.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let pA=u.get(m).__webglFramebuffer;if(m.isWebGLCubeRenderTarget&&_A!==void 0&&(pA=pA[_A]),pA)if(L>=0&&L<=m.width-Y&&q>=0&&q<=m.height-v){NA.bindFramebuffer(R.FRAMEBUFFER,pA);const RA=m.textures[lA],FA=RA.format,GA=RA.type;if(!we.textureFormatReadable(FA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!we.textureTypeReadable(GA))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const jA=R.createBuffer();R.bindBuffer(R.PIXEL_PACK_BUFFER,jA),R.bufferData(R.PIXEL_PACK_BUFFER,hA.byteLength,R.STREAM_READ),m.textures.length>1&&R.readBuffer(R.COLOR_ATTACHMENT0+lA),R.readPixels(L,q,Y,v,aA.convert(FA),aA.convert(GA),0);const fe=K!==null?u.get(K).__webglFramebuffer:null;NA.bindFramebuffer(R.FRAMEBUFFER,fe);const Fe=R.fenceSync(R.SYNC_GPU_COMMANDS_COMPLETE,0);return R.flush(),await kf(R,Fe,4),R.bindBuffer(R.PIXEL_PACK_BUFFER,jA),R.getBufferSubData(R.PIXEL_PACK_BUFFER,0,hA),R.deleteBuffer(jA),R.deleteSync(Fe),hA}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(m,L=null,q=0){const Y=Math.pow(2,-q),v=Math.floor(m.image.width*Y),hA=Math.floor(m.image.height*Y),_A=L!==null?L.x:0,lA=L!==null?L.y:0;M.setTexture2D(m,0),R.copyTexSubImage2D(R.TEXTURE_2D,q,0,0,_A,lA,v,hA),NA.unbindTexture()};const np=R.createFramebuffer(),sp=R.createFramebuffer();this.copyTextureToTexture=function(m,L,q=null,Y=null,v=0,hA=null){hA===null&&(v!==0?(oC("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),hA=v,v=0):hA=0);let _A,lA,pA,RA,FA,GA,jA,fe,Fe;const Ue=m.isCompressedTexture?m.mipmaps[hA]:m.image;if(q!==null)_A=q.max.x-q.min.x,lA=q.max.y-q.min.y,pA=q.isBox3?q.max.z-q.min.z:1,RA=q.min.x,FA=q.min.y,GA=q.isBox3?q.min.z:0;else{const Fg=Math.pow(2,-v);_A=Math.floor(Ue.width*Fg),lA=Math.floor(Ue.height*Fg),m.isDataArrayTexture?pA=Ue.depth:m.isData3DTexture?pA=Math.floor(Ue.depth*Fg):pA=1,RA=0,FA=0,GA=0}Y!==null?(jA=Y.x,fe=Y.y,Fe=Y.z):(jA=0,fe=0,Fe=0);const _e=aA.convert(L.format),MA=aA.convert(L.type);let de;L.isData3DTexture?(M.setTexture3D(L,0),de=R.TEXTURE_3D):L.isDataArrayTexture||L.isCompressedArrayTexture?(M.setTexture2DArray(L,0),de=R.TEXTURE_2D_ARRAY):(M.setTexture2D(L,0),de=R.TEXTURE_2D),R.pixelStorei(R.UNPACK_FLIP_Y_WEBGL,L.flipY),R.pixelStorei(R.UNPACK_PREMULTIPLY_ALPHA_WEBGL,L.premultiplyAlpha),R.pixelStorei(R.UNPACK_ALIGNMENT,L.unpackAlignment);const ne=R.getParameter(R.UNPACK_ROW_LENGTH),yg=R.getParameter(R.UNPACK_IMAGE_HEIGHT),RI=R.getParameter(R.UNPACK_SKIP_PIXELS),bg=R.getParameter(R.UNPACK_SKIP_ROWS),mC=R.getParameter(R.UNPACK_SKIP_IMAGES);R.pixelStorei(R.UNPACK_ROW_LENGTH,Ue.width),R.pixelStorei(R.UNPACK_IMAGE_HEIGHT,Ue.height),R.pixelStorei(R.UNPACK_SKIP_PIXELS,RA),R.pixelStorei(R.UNPACK_SKIP_ROWS,FA),R.pixelStorei(R.UNPACK_SKIP_IMAGES,GA);const me=m.isDataArrayTexture||m.isData3DTexture,dg=L.isDataArrayTexture||L.isData3DTexture;if(m.isDepthTexture){const Fg=u.get(m),ng=u.get(L),xg=u.get(Fg.__renderTarget),ws=u.get(ng.__renderTarget);NA.bindFramebuffer(R.READ_FRAMEBUFFER,xg.__webglFramebuffer),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,ws.__webglFramebuffer);for(let Yi=0;Yi<pA;Yi++)me&&(R.framebufferTextureLayer(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,u.get(m).__webglTexture,v,GA+Yi),R.framebufferTextureLayer(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,u.get(L).__webglTexture,hA,Fe+Yi)),R.blitFramebuffer(RA,FA,_A,lA,jA,fe,_A,lA,R.DEPTH_BUFFER_BIT,R.NEAREST);NA.bindFramebuffer(R.READ_FRAMEBUFFER,null),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,null)}else if(v!==0||m.isRenderTargetTexture||u.has(m)){const Fg=u.get(m),ng=u.get(L);NA.bindFramebuffer(R.READ_FRAMEBUFFER,np),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,sp);for(let xg=0;xg<pA;xg++)me?R.framebufferTextureLayer(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,Fg.__webglTexture,v,GA+xg):R.framebufferTexture2D(R.READ_FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,Fg.__webglTexture,v),dg?R.framebufferTextureLayer(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,ng.__webglTexture,hA,Fe+xg):R.framebufferTexture2D(R.DRAW_FRAMEBUFFER,R.COLOR_ATTACHMENT0,R.TEXTURE_2D,ng.__webglTexture,hA),v!==0?R.blitFramebuffer(RA,FA,_A,lA,jA,fe,_A,lA,R.COLOR_BUFFER_BIT,R.NEAREST):dg?R.copyTexSubImage3D(de,hA,jA,fe,Fe+xg,RA,FA,_A,lA):R.copyTexSubImage2D(de,hA,jA,fe,RA,FA,_A,lA);NA.bindFramebuffer(R.READ_FRAMEBUFFER,null),NA.bindFramebuffer(R.DRAW_FRAMEBUFFER,null)}else dg?m.isDataTexture||m.isData3DTexture?R.texSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,MA,Ue.data):L.isCompressedArrayTexture?R.compressedTexSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,Ue.data):R.texSubImage3D(de,hA,jA,fe,Fe,_A,lA,pA,_e,MA,Ue):m.isDataTexture?R.texSubImage2D(R.TEXTURE_2D,hA,jA,fe,_A,lA,_e,MA,Ue.data):m.isCompressedTexture?R.compressedTexSubImage2D(R.TEXTURE_2D,hA,jA,fe,Ue.width,Ue.height,_e,Ue.data):R.texSubImage2D(R.TEXTURE_2D,hA,jA,fe,_A,lA,_e,MA,Ue);R.pixelStorei(R.UNPACK_ROW_LENGTH,ne),R.pixelStorei(R.UNPACK_IMAGE_HEIGHT,yg),R.pixelStorei(R.UNPACK_SKIP_PIXELS,RI),R.pixelStorei(R.UNPACK_SKIP_ROWS,bg),R.pixelStorei(R.UNPACK_SKIP_IMAGES,mC),hA===0&&L.generateMipmaps&&R.generateMipmap(de),NA.unbindTexture()},this.initRenderTarget=function(m){u.get(m).__webglFramebuffer===void 0&&M.setupRenderTarget(m)},this.initTexture=function(m){m.isCubeTexture?M.setTextureCube(m,0):m.isData3DTexture?M.setTexture3D(m,0):m.isDataArrayTexture||m.isCompressedArrayTexture?M.setTexture2DArray(m,0):M.setTexture2D(m,0),NA.unbindTexture()},this.resetState=function(){N=0,U=0,K=null,NA.reset(),DA.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return nt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(A){this._outputColorSpace=A;const e=this.getContext();e.drawingBufferColorSpace=Ce._getDrawingBufferColorSpace(A),e.unpackColorSpace=Ce._getUnpackColorSpace()}}const Sw=`
|
|
4166
4166
|
uniform float uTime;
|
|
4167
4167
|
uniform float uAudioBass;
|
|
4168
4168
|
uniform float uAudioMid;
|
|
@@ -4545,7 +4545,7 @@ void main() {
|
|
|
4545
4545
|
// Softer alpha for more diffuse appearance
|
|
4546
4546
|
gl_FragColor = vec4(glowColor, glow * 0.4);
|
|
4547
4547
|
}
|
|
4548
|
-
`,Li={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},Mw={size:1,segments:128,colors:Li,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 jo{constructor(A,e={}){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.resizeObserver=null,this.resizeTimeoutId=null,this.isContextLost=!1,this.animate=()=>{if(this.isContextLost)return;this.animationId=requestAnimationFrame(this.animate);const s=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=s,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 B=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,E=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(B-E)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=s,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const B=this.isActive?this.config.glowIntensity*1.5:this.config.glowIntensity*this.config.idleGlowMultiplier,E=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(B-E)*.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+s*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+s*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+s*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+s*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{this.resizeTimeoutId!==null&&clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=setTimeout(()=>{this.resizeTimeoutId=null;const s=this.container.clientWidth,B=this.container.clientHeight;if(s===0||B===0)return;const E=s*this.canvasPadding,d=B*this.canvasPadding;this.camera.aspect=E/d,this.camera.updateProjectionMatrix(),this.renderer.setSize(E,d)},100)},this.handleMouseMove=s=>{const B=this.container.getBoundingClientRect(),E=(s.clientX-B.left)/B.width*2-1,d=-((s.clientY-B.top)/B.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=E*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=A,this.config={...Mw,...e},this.clock=new Eu;const g=/iPhone|iPad|iPod/i.test(navigator.userAgent),i=/Android/i.test(navigator.userAgent);this.canvasPadding=g?1.5:i?2:3,this.boundHandleContextLost=this.handleContextLost.bind(this),this.boundHandleContextRestored=this.handleContextRestored.bind(this),this.scene=new tu;const I=A.clientWidth*this.canvasPadding,C=A.clientHeight*this.canvasPadding,o=I/C;this.camera=new Mg(45,o,.1,100);const a=3,Q=9;this.camera.position.z=Q*(this.canvasPadding/a),this.renderer=new Nw({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(I,C),this.renderer.setClearColor(0,0);const n=this.renderer.domElement;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.pointerEvents="none",A.appendChild(n),n.addEventListener("webglcontextlost",this.boundHandleContextLost),n.addEventListener("webglcontextrestored",this.boundHandleContextRestored),this.createOrb(),window.addEventListener("resize",this.handleResize),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(A),A.addEventListener("mousemove",this.handleMouseMove),A.addEventListener("mouseleave",this.handleMouseLeave)}handleContextLost(A){A.preventDefault(),this.isContextLost=!0,this.stop()}handleContextRestored(A){this.isContextLost=!1,this.recreateAfterContextLoss(),this.start()}recreateAfterContextLoss(){this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.createOrb()}createOrb(){const A={...Li,...this.config.colors},e=new ss(this.config.size,this.config.segments/4);this.orbMaterial=new Gg({vertexShader:Sw,fragmentShader:kw,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 Ie(A.primary)},uColorSecondary:{value:new Ie(A.secondary)},uColorAccent:{value:new Ie(A.accent)},uColorDepth:{value:new Ie(A.depth||Li.depth)},uColorHighlight:{value:new Ie(A.highlight||Li.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:bt}),this.orb=new Xg(e,this.orbMaterial),this.scene.add(this.orb);const g=new Bs(this.config.size,64,64);this.glowMaterial=new Gg({vertexShader:Rw,fragmentShader:Gw,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Ie(A.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:tg,blending:FQ,depthWrite:!1}),this.glowMesh=new Xg(g,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(A){const e=this.config.audioSmoothing;this.audioValues.bass+=(A.bass-this.audioValues.bass)*e,this.audioValues.mid+=(A.mid-this.audioValues.mid)*e,this.audioValues.treble+=(A.treble-this.audioValues.treble)*e,this.audioValues.level+=(A.level-this.audioValues.level)*e}setSimulatedAudio(A,e,g,i){const I=this.config.audioSmoothing;this.audioValues.bass+=(A-this.audioValues.bass)*I,this.audioValues.mid+=(e-this.audioValues.mid)*I,this.audioValues.treble+=(g-this.audioValues.treble)*I,this.audioValues.level+=(i-this.audioValues.level)*I}setActive(A){this.isActive=A}setColors(A){const e={...Li,...this.config.colors,...A};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(e.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(e.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(e.accent),this.orbMaterial.uniforms.uColorDepth.value.set(e.depth||Li.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(e.highlight||Li.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(e.glow)}setGlowSettings(A,e){this.config.glowIntensity=A,this.config.idleGlowMultiplier=e}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(),this.resizeTimeoutId!==null&&(clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=null),window.removeEventListener("resize",this.handleResize),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave);const A=this.renderer.domElement;A.removeEventListener("webglcontextlost",this.boundHandleContextLost),A.removeEventListener("webglcontextrestored",this.boundHandleContextRestored),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.renderer.dispose(),A.parentNode&&A.parentNode.removeChild(A)}}class Wo{constructor(A={}){this.audioContext=null,this.analyser=null,this.source=null,this.localSource=null,this.mixer=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.hasAcquiredContext=!1,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:A.fftSize??2048,smoothingTimeConstant:A.smoothingTimeConstant??.8,minDecibels:A.minDecibels??-90,maxDecibels:A.maxDecibels??-10}}async ensureAudioContext(){if(!this.audioContext)this.audioContext=await Ct.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await Ct.ensureResumed())return null;return this.audioContext}async connectStream(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}this.source=e.createMediaStreamSource(A),this.setupMixerAndAnalyser(),this.mixer&&this.source.connect(this.mixer)}async connectLocalStream(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.localSource)try{this.localSource.disconnect()}catch{}this.localSource=e.createMediaStreamSource(A),this.setupMixerAndAnalyser(),this.mixer&&this.localSource.connect(this.mixer)}setupMixerAndAnalyser(){this.audioContext&&(this.mixer||(this.mixer=this.audioContext.createGain(),this.mixer.gain.value=1),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.mixer.disconnect(),this.mixer.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize))}async connectAudioElement(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}const g=e.createMediaElementSource(A);this.analyser||(this.analyser=e.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,g.connect(this.analyser),this.analyser.connect(e.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:A,mid:e,treble:g}=this.calculateFrequencyBands(),i=this.calculateOverallLevel();return this.smoothedBass+=(A-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(e-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(g-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(i-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 A=this.audioContext.sampleRate,e=this.frequencyData.length,g=A/(e*2),i=Math.floor(250/g),I=Math.floor(2e3/g);let C=0,o=0,a=0;for(let B=0;B<e;B++){const E=this.frequencyData[B]/255;B<i?C+=E:B<I?o+=E:a+=E}const Q=i>0?C/i:0,n=I-i>0?o/(I-i):0,s=e-I>0?a/(e-I):0;return{bass:Math.pow(Q,.8),mid:Math.pow(n,.9),treble:Math.pow(s,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let A=0;for(let g=0;g<this.frequencyData.length;g++)A+=this.frequencyData[g];const e=A/this.frequencyData.length/255;return Math.pow(e,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let A=0;for(let e=0;e<this.frequencyData.length;e++)this.frequencyData[e]>A&&(A=this.frequencyData[e]);return A/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){if(this.source){try{this.source.disconnect()}catch{}this.source=null}if(this.localSource){try{this.localSource.disconnect()}catch{}this.localSource=null}if(this.mixer){try{this.mixer.disconnect()}catch{}this.mixer=null}if(this.analyser){try{this.analyser.disconnect()}catch{}this.analyser=null}this.hasAcquiredContext&&(Ct.release(),this.hasAcquiredContext=!1),this.audioContext=null,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class uC{constructor(A={}){this.hasAcquired=!1,this.config={enabled:!0,volume:.3,preset:"1",...A}}async ensureContext(){if(!this.config.enabled||this.config.preset==="none")return null;const A=await Ct.acquire();return A&&(this.hasAcquired=!0),A}async prewarm(){await this.ensureContext()}async playDrop(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?900:700,C=A?500:400,o=e.createOscillator(),a=e.createGain();o.type="sine",o.frequency.setValueAtTime(I,g),o.frequency.exponentialRampToValueAtTime(C,g+.15),a.gain.setValueAtTime(0,g),a.gain.linearRampToValueAtTime(i*.3,g+.015),a.gain.linearRampToValueAtTime(i*.2,g+.1),a.gain.exponentialRampToValueAtTime(.001,g+.35),o.connect(a).connect(e.destination),o.start(g),o.stop(g+.4)}async playGlassTap(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?2200:1760,C=e.createOscillator(),o=e.createGain();C.type="sine",C.frequency.setValueAtTime(I,g),o.gain.setValueAtTime(0,g),o.gain.linearRampToValueAtTime(i*.25,g+.002),o.gain.exponentialRampToValueAtTime(i*.1,g+.08),o.gain.exponentialRampToValueAtTime(.001,g+.3),C.connect(o).connect(e.destination),C.start(g),C.stop(g+.35);const a=e.createOscillator(),Q=e.createGain();a.type="sine",a.frequency.setValueAtTime(I*2.5,g),Q.gain.setValueAtTime(0,g),Q.gain.linearRampToValueAtTime(i*.08,g+.001),Q.gain.exponentialRampToValueAtTime(.001,g+.12),a.connect(Q).connect(e.destination),a.start(g),a.stop(g+.15)}async playWhoosh(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=e.sampleRate*.5,C=e.createBuffer(1,I,e.sampleRate),o=C.getChannelData(0);for(let E=0;E<I;E++)o[E]=Math.random()*2-1;const a=e.createBufferSource();a.buffer=C;const Q=e.createBiquadFilter();Q.type="bandpass",Q.Q.setValueAtTime(2,g);const n=e.createGain();A?(Q.frequency.setValueAtTime(300,g),Q.frequency.exponentialRampToValueAtTime(2e3,g+.15),Q.frequency.exponentialRampToValueAtTime(800,g+.35),n.gain.setValueAtTime(0,g),n.gain.linearRampToValueAtTime(i*.3,g+.05),n.gain.linearRampToValueAtTime(i*.4,g+.15),n.gain.exponentialRampToValueAtTime(.001,g+.4)):(Q.frequency.setValueAtTime(1500,g),Q.frequency.exponentialRampToValueAtTime(200,g+.3),n.gain.setValueAtTime(0,g),n.gain.linearRampToValueAtTime(i*.35,g+.05),n.gain.exponentialRampToValueAtTime(.001,g+.35));const s=e.createOscillator(),B=e.createGain();s.type="sine",A?(s.frequency.setValueAtTime(300,g),s.frequency.linearRampToValueAtTime(500,g+.2)):(s.frequency.setValueAtTime(400,g),s.frequency.linearRampToValueAtTime(200,g+.25)),B.gain.setValueAtTime(0,g),B.gain.linearRampToValueAtTime(i*.15,g+.05),B.gain.exponentialRampToValueAtTime(.001,g+.35),a.connect(Q).connect(n).connect(e.destination),s.connect(B).connect(e.destination),a.start(g),a.stop(g+.5),s.start(g),s.stop(g+.4)}async playGentleNote(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?659.25:523.25,C=e.createOscillator(),o=e.createGain();C.type="sine",C.frequency.setValueAtTime(I,g),o.gain.setValueAtTime(0,g),o.gain.linearRampToValueAtTime(i*.3,g+.02),o.gain.linearRampToValueAtTime(i*.25,g+.1),o.gain.exponentialRampToValueAtTime(i*.08,g+.3),o.gain.exponentialRampToValueAtTime(.001,g+.5),C.connect(o).connect(e.destination),C.start(g),C.stop(g+.55);const a=e.createOscillator(),Q=e.createGain();a.type="sine",a.frequency.setValueAtTime(I*2,g),Q.gain.setValueAtTime(0,g),Q.gain.linearRampToValueAtTime(i*.06,g+.02),Q.gain.exponentialRampToValueAtTime(.001,g+.2),a.connect(Q).connect(e.destination),a.start(g),a.stop(g+.25)}async playCallStartSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!0);break;case"2":await this.playGlassTap(!0);break;case"3":await this.playWhoosh(!0);break;case"4":await this.playGentleNote(!0);break}}async playCallEndSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!1);break;case"2":await this.playGlassTap(!1);break;case"3":await this.playWhoosh(!1);break;case"4":await this.playGentleNote(!1);break}}setConfig(A){this.config={...this.config,...A}}setEnabled(A){this.config.enabled=A}setVolume(A){this.config.volume=Math.max(0,Math.min(1,A))}setPreset(A){this.config.preset=A}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled&&this.config.preset!=="none"}destroy(){this.hasAcquired&&(Ct.release(),this.hasAcquired=!1)}}const og={default:{primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#34d399",atmosphere:"#a7f3d0",depth:"#064e3b",highlight:"#d1fae5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fb7185",atmosphere:"#fecdd3",depth:"#881337",highlight:"#ffe4e6"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fbbf24",atmosphere:"#fde68a",depth:"#78350f",highlight:"#fef3c7"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#22d3ee",atmosphere:"#a5f3fc",depth:"#164e63",highlight:"#cffafe"},purple:{primary:"#9333ea",secondary:"#a855f7",accent:"#c084fc",glow:"#a855f7",atmosphere:"#d8b4fe",depth:"#581c87",highlight:"#f3e8ff"},blue:{primary:"#2563eb",secondary:"#3b82f6",accent:"#60a5fa",glow:"#3b82f6",atmosphere:"#93c5fd",depth:"#1e3a8a",highlight:"#dbeafe"},white:{primary:"#d1d5db",secondary:"#e5e7eb",accent:"#f3f4f6",glow:"#e5e7eb",atmosphere:"#f9fafb",depth:"#4b5563",highlight:"#ffffff"},black:{primary:"#18182b",secondary:"#242440",accent:"#35355a",glow:"#242440",atmosphere:"#4a4a70",depth:"#08080f",highlight:"#7070a0"},tangerine:{primary:"#ff2d00",secondary:"#ff4500",accent:"#ff6600",glow:"#ff4500",atmosphere:"#ff8533",depth:"#cc1100",highlight:"#ff9955"},ember:{primary:"#ff0000",secondary:"#ff0010",accent:"#ff0018",glow:"#ff0008",atmosphere:"#ff1020",depth:"#aa0008",highlight:"#ff2030"},"tangerine-neon":{primary:"#F97316",secondary:"#EF4444",accent:"#EC4899",glow:"#F97316",atmosphere:"#FB923C",depth:"#C2410C",highlight:"#FDBA74"}},ag={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},violet:{primary:"#5b21b6",secondary:"#6d28d9",accent:"#7c3aed",glow:"#5b21b6",atmosphere:"#6d28d9",depth:"#2e1065",highlight:"#c4b5fd"},teal:{primary:"#0f766e",secondary:"#0d9488",accent:"#14b8a6",glow:"#0f766e",atmosphere:"#0d9488",depth:"#042f2e",highlight:"#5eead4"},orange:{primary:"#c2410c",secondary:"#ea580c",accent:"#f97316",glow:"#c2410c",atmosphere:"#ea580c",depth:"#431407",highlight:"#fed7aa"},blue:{primary:"#1d4ed8",secondary:"#2563eb",accent:"#3b82f6",glow:"#1d4ed8",atmosphere:"#2563eb",depth:"#1e3a8a",highlight:"#93c5fd"},pink:{primary:"#be185d",secondary:"#db2777",accent:"#ec4899",glow:"#be185d",atmosphere:"#db2777",depth:"#500724",highlight:"#f9a8d4"},silver:{primary:"#6b7280",secondary:"#9ca3af",accent:"#d1d5db",glow:"#e5e7eb",atmosphere:"#f3f4f6",depth:"#374151",highlight:"#f9fafb"},charcoal:{primary:"#0f0f1a",secondary:"#1a1a2e",accent:"#2a2a45",glow:"#0f0f1a",atmosphere:"#1a1a2e",depth:"#050509",highlight:"#50507a"},tangerine:{primary:"#d4960a",secondary:"#e6a000",accent:"#fdb813",glow:"#d4960a",atmosphere:"#e6a000",depth:"#a06800",highlight:"#ffe082"},ember:{primary:"#b80000",secondary:"#d50000",accent:"#ff1744",glow:"#d50000",atmosphere:"#ff5252",depth:"#8b0000",highlight:"#ff8a80"},"tangerine-neon":{primary:"#EA580C",secondary:"#F97316",accent:"#FB923C",glow:"#EA580C",atmosphere:"#F97316",depth:"#9A3412",highlight:"#FDBA74"}};function Fw(t,A="dark"){const e=A==="dark"?og:ag;return e[t]||e[Object.keys(e)[0]]}function Uw(t="dark"){return Object.keys(t==="dark"?og:ag)}const SI={default:{dark:{colors:og.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:og.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:og.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:og.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:og.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:og.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:og.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},white:{dark:{colors:og.white,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.silver,glowIntensity:1.8,idleGlowMultiplier:1.2}},black:{dark:{colors:og.black,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.charcoal,glowIntensity:1.8,idleGlowMultiplier:1.2}},tangerine:{dark:{colors:og.tangerine,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.tangerine,glowIntensity:1.8,idleGlowMultiplier:1.2}},ember:{dark:{colors:og.ember,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.ember,glowIntensity:1.8,idleGlowMultiplier:1.2}},"tangerine-neon":{dark:{colors:og["tangerine-neon"],glowIntensity:1.4,idleGlowMultiplier:.7},light:{colors:ag["tangerine-neon"],glowIntensity:2,idleGlowMultiplier:1.3}}},Lw=Object.fromEntries(Object.entries(SI).map(([t,A])=>[t,A.dark])),Kw=Object.fromEntries(Object.entries(SI).map(([t,A])=>[t,A.light]));function kI(t){return(SI[t]||SI.default).dark}function vw(){return Object.keys(SI)}function Jw(t,A){const e=kI(A);t.orbColors=e.colors,t.glowIntensity=e.glowIntensity,t.idleGlowMultiplier=e.idleGlowMultiplier}const hc="privacy_accepted",Xo="user_identity";function Zo(){try{return localStorage.getItem(hc)==="true"}catch{return!1}}function zo(){try{localStorage.setItem(hc,"true")}catch{}}function Bi(){try{let t=localStorage.getItem(Xo);return t||(t=crypto.randomUUID(),localStorage.setItem(Xo,t)),t}catch{const t=crypto.randomUUID();try{localStorage.setItem(Xo,t)}catch{console.warn("[hanc-widget] localStorage unavailable, user_identity will not persist across calls")}return t}}function $o(){try{return localStorage.getItem(Xo)}catch{return null}}function Yw(){if(typeof window>"u")return"https://api.hanc.ai";const t=window.location.hostname;return t.endsWith(".hanc.me")||t==="hanc.me"||t==="localhost"?"https://api.hanc.me":"https://api.hanc.ai"}const DC=Yw(),us={terms_enabled:!1,terms_content:"",terms_url:"https://hanc.ai/terms",privacy_url:"https://hanc.ai/privacy",theme:"default",allow_all_domains:!0,allowed_domains:[]},Aa=new Map,Tw=1e3;async function _C(t,A=DC){if(!t)return console.warn("[hanc-widget] No agentId provided, using default config"),us;const e=Aa.get(t);if(e&&Date.now()-e.timestamp<Tw)return e.config;try{const g=await fetch(`${A}/v1/site/widget-config/${t}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){if(g.status===404)return console.warn(`[hanc-widget] Agent ${t} not found, using default config`),us;throw new Error(`HTTP ${g.status}: ${g.statusText}`)}const i=await g.json();return Aa.set(t,{config:i,timestamp:Date.now()}),i}catch(g){return console.error("[hanc-widget] Failed to fetch widget config:",g),us}}const qw=["hanc.ai","hanc.me","localhost"];function wC(t){const A=window.location.hostname;return qw.some(g=>A===g||A.endsWith(`.${g}`))||t.allow_all_domains||!t.allowed_domains||t.allowed_domains.length===0?!0:t.allowed_domains.some(g=>A===g||A.endsWith(`.${g}`))}function Hw(t){t?Aa.delete(t):Aa.clear()}var Pw=Object.defineProperty,Ow=Object.getOwnPropertyDescriptor,pC=(t,A,e,g)=>{for(var i=g>1?void 0:g?Ow(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&Pw(A,e,i),i};let Ki=class extends Zg{constructor(){super(...arguments),this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsContent="",this.modalTitle="Before we start",this.modalContainer=null}connectedCallback(){super.connectedCallback(),this.createModal()}disconnectedCallback(){super.disconnectedCallback(),this.removeModal()}createModal(){this.modalContainer=document.createElement("div"),this.modalContainer.innerHTML=this.getModalHTML(),document.body.appendChild(this.modalContainer);const t=this.modalContainer.querySelector(".hanc-privacy-overlay"),A=this.modalContainer.querySelector(".hanc-btn-accept"),e=this.modalContainer.querySelector(".hanc-btn-decline");t==null||t.addEventListener("click",g=>{g.target===t&&this.handleDecline()}),A==null||A.addEventListener("click",()=>this.handleAccept()),e==null||e.addEventListener("click",()=>this.handleDecline())}removeModal(){this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null)}renderMarkdown(t){if(!t)return"";let e=(g=>g.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"))(t);return e=e.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),e=e.replace(/^### (.+)$/gm,"<h3>$1</h3>"),e=e.replace(/^## (.+)$/gm,"<h2>$1</h2>"),e=e.replace(/^# (.+)$/gm,"<h1>$1</h1>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/__(.+?)__/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/_(.+?)_/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/^\- (.+)$/gm,"<li>$1</li>"),e=e.replace(/(<li>.*<\/li>\n?)+/g,"<ul>$&</ul>"),e=e.replace(/\n\n/g,"</p><p>"),e="<p>"+e+"</p>",e=e.replace(/<p><\/p>/g,""),e=e.replace(/<p>(<h[1-4]>)/g,"$1"),e=e.replace(/(<\/h[1-4]>)<\/p>/g,"$1"),e=e.replace(/<p>(<ul>)/g,"$1"),e=e.replace(/(<\/ul>)<\/p>/g,"$1"),e=e.replace(/\n/g,"<br>"),e}getModalHTML(){const t=this.termsContent&&this.termsContent.trim().length>0,A=t?this.renderMarkdown(this.termsContent):"By starting this call, you agree to our Terms of Service and Privacy Policy.";return`
|
|
4548
|
+
`,Ki={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},Mw={size:1,segments:128,colors:Ki,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 jo{constructor(A,e={}){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.resizeObserver=null,this.resizeTimeoutId=null,this.isContextLost=!1,this.animate=()=>{if(this.isContextLost)return;this.animationId=requestAnimationFrame(this.animate);const s=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=s,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 B=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,E=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(B-E)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=s,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const B=this.isActive?this.config.glowIntensity*1.5:this.config.glowIntensity*this.config.idleGlowMultiplier,E=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(B-E)*.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+s*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+s*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+s*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+s*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{this.resizeTimeoutId!==null&&clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=setTimeout(()=>{this.resizeTimeoutId=null;const s=this.container.clientWidth,B=this.container.clientHeight;if(s===0||B===0)return;const E=s*this.canvasPadding,d=B*this.canvasPadding;this.camera.aspect=E/d,this.camera.updateProjectionMatrix(),this.renderer.setSize(E,d)},100)},this.handleMouseMove=s=>{const B=this.container.getBoundingClientRect(),E=(s.clientX-B.left)/B.width*2-1,d=-((s.clientY-B.top)/B.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=E*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=A,this.config={...Mw,...e},this.clock=new Eu;const g=/iPhone|iPad|iPod/i.test(navigator.userAgent),i=/Android/i.test(navigator.userAgent);this.canvasPadding=g?1.5:i?2:3,this.boundHandleContextLost=this.handleContextLost.bind(this),this.boundHandleContextRestored=this.handleContextRestored.bind(this),this.scene=new tu;const I=A.clientWidth*this.canvasPadding,C=A.clientHeight*this.canvasPadding,o=I/C;this.camera=new Mg(45,o,.1,100);const a=3,Q=9;this.camera.position.z=Q*(this.canvasPadding/a),this.renderer=new Nw({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(I,C),this.renderer.setClearColor(0,0);const n=this.renderer.domElement;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.pointerEvents="none",A.appendChild(n),n.addEventListener("webglcontextlost",this.boundHandleContextLost),n.addEventListener("webglcontextrestored",this.boundHandleContextRestored),this.createOrb(),window.addEventListener("resize",this.handleResize),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(A),A.addEventListener("mousemove",this.handleMouseMove),A.addEventListener("mouseleave",this.handleMouseLeave)}handleContextLost(A){A.preventDefault(),this.isContextLost=!0,this.stop()}handleContextRestored(A){this.isContextLost=!1,this.recreateAfterContextLoss(),this.start()}recreateAfterContextLoss(){this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.createOrb()}createOrb(){const A={...Ki,...this.config.colors},e=new ss(this.config.size,this.config.segments/4);this.orbMaterial=new Gg({vertexShader:Sw,fragmentShader:kw,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 Ie(A.primary)},uColorSecondary:{value:new Ie(A.secondary)},uColorAccent:{value:new Ie(A.accent)},uColorDepth:{value:new Ie(A.depth||Ki.depth)},uColorHighlight:{value:new Ie(A.highlight||Ki.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:bt}),this.orb=new Xg(e,this.orbMaterial),this.scene.add(this.orb);const g=new Bs(this.config.size,64,64);this.glowMaterial=new Gg({vertexShader:Rw,fragmentShader:Gw,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Ie(A.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:tg,blending:FQ,depthWrite:!1}),this.glowMesh=new Xg(g,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(A){const e=this.config.audioSmoothing;this.audioValues.bass+=(A.bass-this.audioValues.bass)*e,this.audioValues.mid+=(A.mid-this.audioValues.mid)*e,this.audioValues.treble+=(A.treble-this.audioValues.treble)*e,this.audioValues.level+=(A.level-this.audioValues.level)*e}setSimulatedAudio(A,e,g,i){const I=this.config.audioSmoothing;this.audioValues.bass+=(A-this.audioValues.bass)*I,this.audioValues.mid+=(e-this.audioValues.mid)*I,this.audioValues.treble+=(g-this.audioValues.treble)*I,this.audioValues.level+=(i-this.audioValues.level)*I}setActive(A){this.isActive=A}setColors(A){const e={...Ki,...this.config.colors,...A};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(e.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(e.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(e.accent),this.orbMaterial.uniforms.uColorDepth.value.set(e.depth||Ki.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(e.highlight||Ki.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(e.glow)}setGlowSettings(A,e){this.config.glowIntensity=A,this.config.idleGlowMultiplier=e}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(),this.resizeTimeoutId!==null&&(clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=null),window.removeEventListener("resize",this.handleResize),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave);const A=this.renderer.domElement;A.removeEventListener("webglcontextlost",this.boundHandleContextLost),A.removeEventListener("webglcontextrestored",this.boundHandleContextRestored),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.renderer.dispose(),A.parentNode&&A.parentNode.removeChild(A)}}class Wo{constructor(A={}){this.audioContext=null,this.analyser=null,this.source=null,this.localSource=null,this.mixer=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.hasAcquiredContext=!1,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:A.fftSize??2048,smoothingTimeConstant:A.smoothingTimeConstant??.8,minDecibels:A.minDecibels??-90,maxDecibels:A.maxDecibels??-10}}async ensureAudioContext(){if(!this.audioContext)this.audioContext=await Ct.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await Ct.ensureResumed())return null;return this.audioContext}async connectStream(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}this.source=e.createMediaStreamSource(A),this.setupMixerAndAnalyser(),this.mixer&&this.source.connect(this.mixer)}async connectLocalStream(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.localSource)try{this.localSource.disconnect()}catch{}this.localSource=e.createMediaStreamSource(A),this.setupMixerAndAnalyser(),this.mixer&&this.localSource.connect(this.mixer)}setupMixerAndAnalyser(){this.audioContext&&(this.mixer||(this.mixer=this.audioContext.createGain(),this.mixer.gain.value=1),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.mixer.disconnect(),this.mixer.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize))}async connectAudioElement(A){const e=await this.ensureAudioContext();if(!e){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}const g=e.createMediaElementSource(A);this.analyser||(this.analyser=e.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,g.connect(this.analyser),this.analyser.connect(e.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:A,mid:e,treble:g}=this.calculateFrequencyBands(),i=this.calculateOverallLevel();return this.smoothedBass+=(A-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(e-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(g-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(i-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 A=this.audioContext.sampleRate,e=this.frequencyData.length,g=A/(e*2),i=Math.floor(250/g),I=Math.floor(2e3/g);let C=0,o=0,a=0;for(let B=0;B<e;B++){const E=this.frequencyData[B]/255;B<i?C+=E:B<I?o+=E:a+=E}const Q=i>0?C/i:0,n=I-i>0?o/(I-i):0,s=e-I>0?a/(e-I):0;return{bass:Math.pow(Q,.8),mid:Math.pow(n,.9),treble:Math.pow(s,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let A=0;for(let g=0;g<this.frequencyData.length;g++)A+=this.frequencyData[g];const e=A/this.frequencyData.length/255;return Math.pow(e,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let A=0;for(let e=0;e<this.frequencyData.length;e++)this.frequencyData[e]>A&&(A=this.frequencyData[e]);return A/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){if(this.source){try{this.source.disconnect()}catch{}this.source=null}if(this.localSource){try{this.localSource.disconnect()}catch{}this.localSource=null}if(this.mixer){try{this.mixer.disconnect()}catch{}this.mixer=null}if(this.analyser){try{this.analyser.disconnect()}catch{}this.analyser=null}this.hasAcquiredContext&&(Ct.release(),this.hasAcquiredContext=!1),this.audioContext=null,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class uC{constructor(A={}){this.hasAcquired=!1,this.config={enabled:!0,volume:.3,preset:"1",...A}}async ensureContext(){if(!this.config.enabled||this.config.preset==="none")return null;const A=await Ct.acquire();return A&&(this.hasAcquired=!0),A}async prewarm(){await this.ensureContext()}async playDrop(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?900:700,C=A?500:400,o=e.createOscillator(),a=e.createGain();o.type="sine",o.frequency.setValueAtTime(I,g),o.frequency.exponentialRampToValueAtTime(C,g+.15),a.gain.setValueAtTime(0,g),a.gain.linearRampToValueAtTime(i*.3,g+.015),a.gain.linearRampToValueAtTime(i*.2,g+.1),a.gain.exponentialRampToValueAtTime(.001,g+.35),o.connect(a).connect(e.destination),o.start(g),o.stop(g+.4)}async playGlassTap(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?2200:1760,C=e.createOscillator(),o=e.createGain();C.type="sine",C.frequency.setValueAtTime(I,g),o.gain.setValueAtTime(0,g),o.gain.linearRampToValueAtTime(i*.25,g+.002),o.gain.exponentialRampToValueAtTime(i*.1,g+.08),o.gain.exponentialRampToValueAtTime(.001,g+.3),C.connect(o).connect(e.destination),C.start(g),C.stop(g+.35);const a=e.createOscillator(),Q=e.createGain();a.type="sine",a.frequency.setValueAtTime(I*2.5,g),Q.gain.setValueAtTime(0,g),Q.gain.linearRampToValueAtTime(i*.08,g+.001),Q.gain.exponentialRampToValueAtTime(.001,g+.12),a.connect(Q).connect(e.destination),a.start(g),a.stop(g+.15)}async playWhoosh(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=e.sampleRate*.5,C=e.createBuffer(1,I,e.sampleRate),o=C.getChannelData(0);for(let E=0;E<I;E++)o[E]=Math.random()*2-1;const a=e.createBufferSource();a.buffer=C;const Q=e.createBiquadFilter();Q.type="bandpass",Q.Q.setValueAtTime(2,g);const n=e.createGain();A?(Q.frequency.setValueAtTime(300,g),Q.frequency.exponentialRampToValueAtTime(2e3,g+.15),Q.frequency.exponentialRampToValueAtTime(800,g+.35),n.gain.setValueAtTime(0,g),n.gain.linearRampToValueAtTime(i*.3,g+.05),n.gain.linearRampToValueAtTime(i*.4,g+.15),n.gain.exponentialRampToValueAtTime(.001,g+.4)):(Q.frequency.setValueAtTime(1500,g),Q.frequency.exponentialRampToValueAtTime(200,g+.3),n.gain.setValueAtTime(0,g),n.gain.linearRampToValueAtTime(i*.35,g+.05),n.gain.exponentialRampToValueAtTime(.001,g+.35));const s=e.createOscillator(),B=e.createGain();s.type="sine",A?(s.frequency.setValueAtTime(300,g),s.frequency.linearRampToValueAtTime(500,g+.2)):(s.frequency.setValueAtTime(400,g),s.frequency.linearRampToValueAtTime(200,g+.25)),B.gain.setValueAtTime(0,g),B.gain.linearRampToValueAtTime(i*.15,g+.05),B.gain.exponentialRampToValueAtTime(.001,g+.35),a.connect(Q).connect(n).connect(e.destination),s.connect(B).connect(e.destination),a.start(g),a.stop(g+.5),s.start(g),s.stop(g+.4)}async playGentleNote(A){const e=await this.ensureContext();if(!e)return;const g=e.currentTime,i=this.config.volume,I=A?659.25:523.25,C=e.createOscillator(),o=e.createGain();C.type="sine",C.frequency.setValueAtTime(I,g),o.gain.setValueAtTime(0,g),o.gain.linearRampToValueAtTime(i*.3,g+.02),o.gain.linearRampToValueAtTime(i*.25,g+.1),o.gain.exponentialRampToValueAtTime(i*.08,g+.3),o.gain.exponentialRampToValueAtTime(.001,g+.5),C.connect(o).connect(e.destination),C.start(g),C.stop(g+.55);const a=e.createOscillator(),Q=e.createGain();a.type="sine",a.frequency.setValueAtTime(I*2,g),Q.gain.setValueAtTime(0,g),Q.gain.linearRampToValueAtTime(i*.06,g+.02),Q.gain.exponentialRampToValueAtTime(.001,g+.2),a.connect(Q).connect(e.destination),a.start(g),a.stop(g+.25)}async playCallStartSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!0);break;case"2":await this.playGlassTap(!0);break;case"3":await this.playWhoosh(!0);break;case"4":await this.playGentleNote(!0);break}}async playCallEndSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!1);break;case"2":await this.playGlassTap(!1);break;case"3":await this.playWhoosh(!1);break;case"4":await this.playGentleNote(!1);break}}setConfig(A){this.config={...this.config,...A}}setEnabled(A){this.config.enabled=A}setVolume(A){this.config.volume=Math.max(0,Math.min(1,A))}setPreset(A){this.config.preset=A}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled&&this.config.preset!=="none"}destroy(){this.hasAcquired&&(Ct.release(),this.hasAcquired=!1)}}const og={default:{primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#34d399",atmosphere:"#a7f3d0",depth:"#064e3b",highlight:"#d1fae5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fb7185",atmosphere:"#fecdd3",depth:"#881337",highlight:"#ffe4e6"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fbbf24",atmosphere:"#fde68a",depth:"#78350f",highlight:"#fef3c7"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#22d3ee",atmosphere:"#a5f3fc",depth:"#164e63",highlight:"#cffafe"},purple:{primary:"#9333ea",secondary:"#a855f7",accent:"#c084fc",glow:"#a855f7",atmosphere:"#d8b4fe",depth:"#581c87",highlight:"#f3e8ff"},blue:{primary:"#2563eb",secondary:"#3b82f6",accent:"#60a5fa",glow:"#3b82f6",atmosphere:"#93c5fd",depth:"#1e3a8a",highlight:"#dbeafe"},white:{primary:"#d1d5db",secondary:"#e5e7eb",accent:"#f3f4f6",glow:"#e5e7eb",atmosphere:"#f9fafb",depth:"#4b5563",highlight:"#ffffff"},black:{primary:"#18182b",secondary:"#242440",accent:"#35355a",glow:"#242440",atmosphere:"#4a4a70",depth:"#08080f",highlight:"#7070a0"},tangerine:{primary:"#ff2d00",secondary:"#ff4500",accent:"#ff6600",glow:"#ff4500",atmosphere:"#ff8533",depth:"#cc1100",highlight:"#ff9955"},ember:{primary:"#ff0000",secondary:"#ff0010",accent:"#ff0018",glow:"#ff0008",atmosphere:"#ff1020",depth:"#aa0008",highlight:"#ff2030"},"tangerine-neon":{primary:"#F97316",secondary:"#EF4444",accent:"#EC4899",glow:"#F97316",atmosphere:"#FB923C",depth:"#C2410C",highlight:"#FDBA74"}},ag={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},violet:{primary:"#5b21b6",secondary:"#6d28d9",accent:"#7c3aed",glow:"#5b21b6",atmosphere:"#6d28d9",depth:"#2e1065",highlight:"#c4b5fd"},teal:{primary:"#0f766e",secondary:"#0d9488",accent:"#14b8a6",glow:"#0f766e",atmosphere:"#0d9488",depth:"#042f2e",highlight:"#5eead4"},orange:{primary:"#c2410c",secondary:"#ea580c",accent:"#f97316",glow:"#c2410c",atmosphere:"#ea580c",depth:"#431407",highlight:"#fed7aa"},blue:{primary:"#1d4ed8",secondary:"#2563eb",accent:"#3b82f6",glow:"#1d4ed8",atmosphere:"#2563eb",depth:"#1e3a8a",highlight:"#93c5fd"},pink:{primary:"#be185d",secondary:"#db2777",accent:"#ec4899",glow:"#be185d",atmosphere:"#db2777",depth:"#500724",highlight:"#f9a8d4"},silver:{primary:"#6b7280",secondary:"#9ca3af",accent:"#d1d5db",glow:"#e5e7eb",atmosphere:"#f3f4f6",depth:"#374151",highlight:"#f9fafb"},charcoal:{primary:"#0f0f1a",secondary:"#1a1a2e",accent:"#2a2a45",glow:"#0f0f1a",atmosphere:"#1a1a2e",depth:"#050509",highlight:"#50507a"},tangerine:{primary:"#d4960a",secondary:"#e6a000",accent:"#fdb813",glow:"#d4960a",atmosphere:"#e6a000",depth:"#a06800",highlight:"#ffe082"},ember:{primary:"#b80000",secondary:"#d50000",accent:"#ff1744",glow:"#d50000",atmosphere:"#ff5252",depth:"#8b0000",highlight:"#ff8a80"},"tangerine-neon":{primary:"#EA580C",secondary:"#F97316",accent:"#FB923C",glow:"#EA580C",atmosphere:"#F97316",depth:"#9A3412",highlight:"#FDBA74"}};function Fw(t,A="dark"){const e=A==="dark"?og:ag;return e[t]||e[Object.keys(e)[0]]}function Uw(t="dark"){return Object.keys(t==="dark"?og:ag)}const SI={default:{dark:{colors:og.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:og.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:og.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:og.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:og.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:og.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:og.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},white:{dark:{colors:og.white,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.silver,glowIntensity:1.8,idleGlowMultiplier:1.2}},black:{dark:{colors:og.black,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.charcoal,glowIntensity:1.8,idleGlowMultiplier:1.2}},tangerine:{dark:{colors:og.tangerine,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.tangerine,glowIntensity:1.8,idleGlowMultiplier:1.2}},ember:{dark:{colors:og.ember,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ag.ember,glowIntensity:1.8,idleGlowMultiplier:1.2}},"tangerine-neon":{dark:{colors:og["tangerine-neon"],glowIntensity:1.4,idleGlowMultiplier:.7},light:{colors:ag["tangerine-neon"],glowIntensity:2,idleGlowMultiplier:1.3}}},Lw=Object.fromEntries(Object.entries(SI).map(([t,A])=>[t,A.dark])),Kw=Object.fromEntries(Object.entries(SI).map(([t,A])=>[t,A.light]));function kI(t){return(SI[t]||SI.default).dark}function vw(){return Object.keys(SI)}function Jw(t,A){const e=kI(A);t.orbColors=e.colors,t.glowIntensity=e.glowIntensity,t.idleGlowMultiplier=e.idleGlowMultiplier}const hc="privacy_accepted",Xo="user_identity";function Zo(){try{return localStorage.getItem(hc)==="true"}catch{return!1}}function zo(){try{localStorage.setItem(hc,"true")}catch{}}function Bi(){try{let t=localStorage.getItem(Xo);return t||(t=crypto.randomUUID(),localStorage.setItem(Xo,t)),t}catch{const t=crypto.randomUUID();try{localStorage.setItem(Xo,t)}catch{console.warn("[hanc-widget] localStorage unavailable, user_identity will not persist across calls")}return t}}function $o(){try{return localStorage.getItem(Xo)}catch{return null}}function Yw(){if(typeof window>"u")return"https://api.hanc.ai";const t=window.location.hostname;return t.endsWith(".hanc.me")||t==="hanc.me"||t==="localhost"?"https://api.hanc.me":"https://api.hanc.ai"}const DC=Yw(),us={terms_enabled:!1,terms_content:"",terms_url:"https://hanc.ai/terms",privacy_url:"https://hanc.ai/privacy",theme:"default",allow_all_domains:!0,allowed_domains:[]},Aa=new Map,Tw=1e3;async function _C(t,A=DC){if(!t)return console.warn("[hanc-widget] No agentId provided, using default config"),us;const e=Aa.get(t);if(e&&Date.now()-e.timestamp<Tw)return e.config;try{const g=await fetch(`${A}/v1/site/widget-config/${t}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!g.ok){if(g.status===404)return console.warn(`[hanc-widget] Agent ${t} not found, using default config`),us;throw new Error(`HTTP ${g.status}: ${g.statusText}`)}const i=await g.json();return Aa.set(t,{config:i,timestamp:Date.now()}),i}catch(g){return console.error("[hanc-widget] Failed to fetch widget config:",g),us}}const qw=["hanc.ai","hanc.me","localhost"];function wC(t){const A=window.location.hostname;return qw.some(g=>A===g||A.endsWith(`.${g}`))||t.allow_all_domains||!t.allowed_domains||t.allowed_domains.length===0?!0:t.allowed_domains.some(g=>A===g||A.endsWith(`.${g}`))}function Hw(t){t?Aa.delete(t):Aa.clear()}var Pw=Object.defineProperty,Ow=Object.getOwnPropertyDescriptor,pC=(t,A,e,g)=>{for(var i=g>1?void 0:g?Ow(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&Pw(A,e,i),i};let vi=class extends Zg{constructor(){super(...arguments),this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsContent="",this.modalTitle="Before we start",this.modalContainer=null}connectedCallback(){super.connectedCallback(),this.createModal()}disconnectedCallback(){super.disconnectedCallback(),this.removeModal()}createModal(){this.modalContainer=document.createElement("div"),this.modalContainer.innerHTML=this.getModalHTML(),document.body.appendChild(this.modalContainer);const t=this.modalContainer.querySelector(".hanc-privacy-overlay"),A=this.modalContainer.querySelector(".hanc-btn-accept"),e=this.modalContainer.querySelector(".hanc-btn-decline");t==null||t.addEventListener("click",g=>{g.target===t&&this.handleDecline()}),A==null||A.addEventListener("click",()=>this.handleAccept()),e==null||e.addEventListener("click",()=>this.handleDecline())}removeModal(){this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null)}renderMarkdown(t){if(!t)return"";let e=(g=>g.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"))(t);return e=e.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),e=e.replace(/^### (.+)$/gm,"<h3>$1</h3>"),e=e.replace(/^## (.+)$/gm,"<h2>$1</h2>"),e=e.replace(/^# (.+)$/gm,"<h1>$1</h1>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/__(.+?)__/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/_(.+?)_/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/^\- (.+)$/gm,"<li>$1</li>"),e=e.replace(/(<li>.*<\/li>\n?)+/g,"<ul>$&</ul>"),e=e.replace(/\n\n/g,"</p><p>"),e="<p>"+e+"</p>",e=e.replace(/<p><\/p>/g,""),e=e.replace(/<p>(<h[1-4]>)/g,"$1"),e=e.replace(/(<\/h[1-4]>)<\/p>/g,"$1"),e=e.replace(/<p>(<ul>)/g,"$1"),e=e.replace(/(<\/ul>)<\/p>/g,"$1"),e=e.replace(/\n/g,"<br>"),e}getModalHTML(){const t=this.termsContent&&this.termsContent.trim().length>0,A=t?this.renderMarkdown(this.termsContent):"By starting this call, you agree to our Terms of Service and Privacy Policy.";return`
|
|
4549
4549
|
<style>
|
|
4550
4550
|
.hanc-privacy-overlay {
|
|
4551
4551
|
position: fixed;
|
|
@@ -4754,11 +4754,11 @@ void main() {
|
|
|
4754
4754
|
</div>
|
|
4755
4755
|
</div>
|
|
4756
4756
|
</div>
|
|
4757
|
-
`}escapeHtml(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}handleAccept(){this.dispatchEvent(new CustomEvent("accept",{bubbles:!0,composed:!0}))}handleDecline(){this.dispatchEvent(new CustomEvent("decline",{bubbles:!0,composed:!0}))}render(){return zA``}};
|
|
4757
|
+
`}escapeHtml(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}handleAccept(){this.dispatchEvent(new CustomEvent("accept",{bubbles:!0,composed:!0}))}handleDecline(){this.dispatchEvent(new CustomEvent("decline",{bubbles:!0,composed:!0}))}render(){return zA``}};vi.styles=Ti`
|
|
4758
4758
|
:host {
|
|
4759
4759
|
display: contents;
|
|
4760
4760
|
}
|
|
4761
|
-
`,pC([W({type:String,attribute:"privacy-url"})],
|
|
4761
|
+
`,pC([W({type:String,attribute:"privacy-url"})],vi.prototype,"privacyUrl",2),pC([W({type:String,attribute:"terms-url"})],vi.prototype,"termsUrl",2),pC([W({type:String,attribute:"terms-content"})],vi.prototype,"termsContent",2),pC([W({type:String,attribute:"modal-title"})],vi.prototype,"modalTitle",2),vi=pC([Oi("hanc-privacy-modal")],vi);const Vw=Ti`
|
|
4762
4762
|
:host {
|
|
4763
4763
|
display: block;
|
|
4764
4764
|
position: fixed;
|
|
@@ -4994,7 +4994,7 @@ void main() {
|
|
|
4994
4994
|
`}
|
|
4995
4995
|
</div>
|
|
4996
4996
|
</div>
|
|
4997
|
-
`:ke}};ct.styles=Vw,Ei([W({type:String})],ct.prototype,"requestId",2),Ei([W({type:Array})],ct.prototype,"fields",2),Ei([W({type:Boolean})],ct.prototype,"visible",2),Ei([
|
|
4997
|
+
`:ke}};ct.styles=Vw,Ei([W({type:String})],ct.prototype,"requestId",2),Ei([W({type:Array})],ct.prototype,"fields",2),Ei([W({type:Boolean})],ct.prototype,"visible",2),Ei([$A()],ct.prototype,"_values",2),Ei([$A()],ct.prototype,"_errors",2),Ei([$A()],ct.prototype,"_submitted",2),Ei([$A()],ct.prototype,"_animateIn",2),ct=Ei([Oi("form-overlay")],ct);var Xw=Object.defineProperty,Zw=Object.getOwnPropertyDescriptor,HA=(t,A,e,g)=>{for(var i=g>1?void 0:g?Zw(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&Xw(A,e,i),i};F.InlineCall=class extends Zg{constructor(){super(...arguments),this.callManager=new pi,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.formVisible=!1,this.formRequestId="",this.formFields=[],this.domainBlocked=!1,this.errorKind=null,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Try to call",this.buttonConnectingText="Connecting...",this.size=370,this.containerPadding=45,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleError=A=>{const e=A.detail;this.errorKind=(e==null?void 0:e.status)===429?"rate-limit":"generic"},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.errorKind=null,this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",this.resetCallManager(),await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handleAgentCommand=A=>{var g;const e=A.detail;if(e.type==="show_form"&&((g=e.payload)!=null&&g.fields)){const I=e.payload.fields.filter(C=>C.show_in_form!==!1);if(I.length===0)return;this.formRequestId=e.payload.request_id??"",this.formFields=I,this.formVisible=!0}else e.type==="hide_form"&&(this.formVisible=!1)},this.handleFormSubmit=A=>{const{requestId:e,data:g}=A.detail;this.callManager.sendDataToAgent({type:"form_response",payload:{request_id:e,data:g}})},this.handleFormDone=()=>{this.formVisible=!1},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",this.resetCallManager(),await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.attachCallManagerListeners(this.callManager),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){var A;super.disconnectedCallback(),this.detachCallManagerListeners(this.callManager),this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}attachCallManagerListeners(A){A.addEventListener("status-changed",this.handleStatusChange),A.addEventListener("audio-track",this.handleAudioTrack),A.addEventListener("local-audio-track",this.handleLocalAudioTrack),A.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),A.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),A.addEventListener("agent-command",this.handleAgentCommand),A.addEventListener("error",this.handleError)}detachCallManagerListeners(A){A.removeEventListener("status-changed",this.handleStatusChange),A.removeEventListener("audio-track",this.handleAudioTrack),A.removeEventListener("local-audio-track",this.handleLocalAudioTrack),A.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),A.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),A.removeEventListener("agent-command",this.handleAgentCommand),A.removeEventListener("error",this.handleError)}resetCallManager(){this.detachCallManagerListeners(this.callManager),this.callManager.hangUp(),this.callManager=new pi,this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.attachCallManagerListeners(this.callManager)}getButtonIcon(){return this.callStatus==="connecting"?zA`
|
|
4998
4998
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
|
|
4999
4999
|
<circle
|
|
5000
5000
|
cx="8"
|
|
@@ -5058,7 +5058,7 @@ void main() {
|
|
|
5058
5058
|
fill="white"
|
|
5059
5059
|
/>
|
|
5060
5060
|
</svg>
|
|
5061
|
-
`}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"error":return"Error";default:return this.buttonStartText}}render(){var g,i,I;const A=this.size,e=A-this.containerPadding*2;return zA`
|
|
5061
|
+
`}get buttonText(){switch(this.callStatus){case"connecting":return this.buttonConnectingText;case"error":return this.errorKind==="rate-limit"?"Too many attempts, try again soon":"Error";default:return this.buttonStartText}}render(){var g,i,I;const A=this.size,e=A-this.containerPadding*2;return zA`
|
|
5062
5062
|
<style>
|
|
5063
5063
|
.container {
|
|
5064
5064
|
position: relative;
|
|
@@ -5304,12 +5304,12 @@ void main() {
|
|
|
5304
5304
|
@form-submit=${this.handleFormSubmit}
|
|
5305
5305
|
@form-done=${this.handleFormDone}
|
|
5306
5306
|
></form-overlay>
|
|
5307
|
-
`}},F.InlineCall.styles=
|
|
5307
|
+
`}},F.InlineCall.styles=Ti`
|
|
5308
5308
|
:host {
|
|
5309
5309
|
display: inline-block;
|
|
5310
5310
|
contain: layout style;
|
|
5311
5311
|
}
|
|
5312
|
-
`,PA([W({type:String,attribute:"agent-id"})],F.InlineCall.prototype,"agentId",2),PA([W({type:String,attribute:"voice-service-url"})],F.InlineCall.prototype,"voiceServiceUrl",2),PA([ge()],F.InlineCall.prototype,"callStatus",2),PA([ge()],F.InlineCall.prototype,"microphoneEnabled",2),PA([ge()],F.InlineCall.prototype,"microphoneInitialized",2),PA([ge()],F.InlineCall.prototype,"showPrivacyModal",2),PA([ge()],F.InlineCall.prototype,"widgetConfig",2),PA([ge()],F.InlineCall.prototype,"configLoading",2),PA([ge()],F.InlineCall.prototype,"formVisible",2),PA([ge()],F.InlineCall.prototype,"formRequestId",2),PA([ge()],F.InlineCall.prototype,"formFields",2),PA([ge()],F.InlineCall.prototype,"domainBlocked",2),PA([W({type:String,attribute:"privacy-url"})],F.InlineCall.prototype,"privacyUrl",2),PA([W({type:String,attribute:"terms-url"})],F.InlineCall.prototype,"termsUrl",2),PA([W({type:Boolean,attribute:"terms-enabled"})],F.InlineCall.prototype,"termsEnabled",2),PA([W({type:String,attribute:"terms-content"})],F.InlineCall.prototype,"termsContent",2),PA([W({type:Boolean,attribute:"skip-fetch"})],F.InlineCall.prototype,"skipFetch",2),PA([W({type:String,attribute:"api-base-url"})],F.InlineCall.prototype,"apiBaseUrl",2),PA([W({type:String,attribute:"button-start-text"})],F.InlineCall.prototype,"buttonStartText",2),PA([W({type:String,attribute:"button-connecting-text"})],F.InlineCall.prototype,"buttonConnectingText",2),PA([W({type:Number,attribute:"size"})],F.InlineCall.prototype,"size",2),PA([W({type:Number,attribute:"container-padding"})],F.InlineCall.prototype,"containerPadding",2),PA([W({type:String,attribute:"theme",reflect:!0})],F.InlineCall.prototype,"theme",2),PA([W({type:Object,attribute:"orb-colors"})],F.InlineCall.prototype,"orbColors",2),PA([W({type:Number,attribute:"glow-intensity"})],F.InlineCall.prototype,"glowIntensity",2),PA([W({type:Number,attribute:"idle-glow-multiplier"})],F.InlineCall.prototype,"idleGlowMultiplier",2),PA([W({type:Number,attribute:"morph-strength"})],F.InlineCall.prototype,"morphStrength",2),PA([W({type:Number,attribute:"noise-scale"})],F.InlineCall.prototype,"noiseScale",2),PA([W({type:Number,attribute:"noise-speed"})],F.InlineCall.prototype,"noiseSpeed",2),PA([W({type:Number,attribute:"fresnel-power"})],F.InlineCall.prototype,"fresnelPower",2),PA([W({type:Number,attribute:"rotation-speed"})],F.InlineCall.prototype,"rotationSpeed",2),PA([W({type:Number,attribute:"audio-reactivity"})],F.InlineCall.prototype,"audioReactivity",2),PA([W({type:Number,attribute:"audio-smoothing"})],F.InlineCall.prototype,"audioSmoothing",2),PA([W({type:Number,attribute:"idle-morph-multiplier"})],F.InlineCall.prototype,"idleMorphMultiplier",2),PA([W({type:Number,attribute:"color-contrast"})],F.InlineCall.prototype,"colorContrast",2),PA([W({type:Boolean,attribute:"sound-enabled"})],F.InlineCall.prototype,"soundEnabled",2),PA([W({type:Number,attribute:"sound-volume"})],F.InlineCall.prototype,"soundVolume",2),PA([W({type:String,attribute:"sound-preset"})],F.InlineCall.prototype,"soundPreset",2),F.InlineCall=PA([Pi("hanc-ai-inline-call")],F.InlineCall);var zw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,Ae=(t,A,e,g)=>{for(var i=g>1?void 0:g?$w(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&zw(A,e,i),i};F.FloatingCall=class extends Zg{constructor(){super(...arguments),this.callManager=new CI,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this._disconnectTimer=null,this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){if(super.connectedCallback(),this._disconnectTimer!==null){clearTimeout(this._disconnectTimer),this._disconnectTimer=null,this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.orbRenderer||this.updateComplete.then(()=>this.initializeOrb());return}this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this._disconnectTimer=setTimeout(()=>{var A;this._disconnectTimer=null,this.isConnected||(this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null)},0)}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){return this.callStatus==="connecting"?zA`
|
|
5312
|
+
`,HA([W({type:String,attribute:"agent-id"})],F.InlineCall.prototype,"agentId",2),HA([W({type:String,attribute:"voice-service-url"})],F.InlineCall.prototype,"voiceServiceUrl",2),HA([$A()],F.InlineCall.prototype,"callStatus",2),HA([$A()],F.InlineCall.prototype,"microphoneEnabled",2),HA([$A()],F.InlineCall.prototype,"microphoneInitialized",2),HA([$A()],F.InlineCall.prototype,"showPrivacyModal",2),HA([$A()],F.InlineCall.prototype,"widgetConfig",2),HA([$A()],F.InlineCall.prototype,"configLoading",2),HA([$A()],F.InlineCall.prototype,"formVisible",2),HA([$A()],F.InlineCall.prototype,"formRequestId",2),HA([$A()],F.InlineCall.prototype,"formFields",2),HA([$A()],F.InlineCall.prototype,"domainBlocked",2),HA([$A()],F.InlineCall.prototype,"errorKind",2),HA([W({type:String,attribute:"privacy-url"})],F.InlineCall.prototype,"privacyUrl",2),HA([W({type:String,attribute:"terms-url"})],F.InlineCall.prototype,"termsUrl",2),HA([W({type:Boolean,attribute:"terms-enabled"})],F.InlineCall.prototype,"termsEnabled",2),HA([W({type:String,attribute:"terms-content"})],F.InlineCall.prototype,"termsContent",2),HA([W({type:Boolean,attribute:"skip-fetch"})],F.InlineCall.prototype,"skipFetch",2),HA([W({type:String,attribute:"api-base-url"})],F.InlineCall.prototype,"apiBaseUrl",2),HA([W({type:String,attribute:"button-start-text"})],F.InlineCall.prototype,"buttonStartText",2),HA([W({type:String,attribute:"button-connecting-text"})],F.InlineCall.prototype,"buttonConnectingText",2),HA([W({type:Number,attribute:"size"})],F.InlineCall.prototype,"size",2),HA([W({type:Number,attribute:"container-padding"})],F.InlineCall.prototype,"containerPadding",2),HA([W({type:String,attribute:"theme",reflect:!0})],F.InlineCall.prototype,"theme",2),HA([W({type:Object,attribute:"orb-colors"})],F.InlineCall.prototype,"orbColors",2),HA([W({type:Number,attribute:"glow-intensity"})],F.InlineCall.prototype,"glowIntensity",2),HA([W({type:Number,attribute:"idle-glow-multiplier"})],F.InlineCall.prototype,"idleGlowMultiplier",2),HA([W({type:Number,attribute:"morph-strength"})],F.InlineCall.prototype,"morphStrength",2),HA([W({type:Number,attribute:"noise-scale"})],F.InlineCall.prototype,"noiseScale",2),HA([W({type:Number,attribute:"noise-speed"})],F.InlineCall.prototype,"noiseSpeed",2),HA([W({type:Number,attribute:"fresnel-power"})],F.InlineCall.prototype,"fresnelPower",2),HA([W({type:Number,attribute:"rotation-speed"})],F.InlineCall.prototype,"rotationSpeed",2),HA([W({type:Number,attribute:"audio-reactivity"})],F.InlineCall.prototype,"audioReactivity",2),HA([W({type:Number,attribute:"audio-smoothing"})],F.InlineCall.prototype,"audioSmoothing",2),HA([W({type:Number,attribute:"idle-morph-multiplier"})],F.InlineCall.prototype,"idleMorphMultiplier",2),HA([W({type:Number,attribute:"color-contrast"})],F.InlineCall.prototype,"colorContrast",2),HA([W({type:Boolean,attribute:"sound-enabled"})],F.InlineCall.prototype,"soundEnabled",2),HA([W({type:Number,attribute:"sound-volume"})],F.InlineCall.prototype,"soundVolume",2),HA([W({type:String,attribute:"sound-preset"})],F.InlineCall.prototype,"soundPreset",2),F.InlineCall=HA([Oi("hanc-ai-inline-call")],F.InlineCall);var zw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,ee=(t,A,e,g)=>{for(var i=g>1?void 0:g?$w(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&zw(A,e,i),i};F.FloatingCall=class extends Zg{constructor(){super(...arguments),this.callManager=new pi,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this._disconnectTimer=null,this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){if(super.connectedCallback(),this._disconnectTimer!==null){clearTimeout(this._disconnectTimer),this._disconnectTimer=null,this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.orbRenderer||this.updateComplete.then(()=>this.initializeOrb());return}this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this._disconnectTimer=setTimeout(()=>{var A;this._disconnectTimer=null,this.isConnected||(this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null)},0)}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){return this.callStatus==="connecting"?zA`
|
|
5313
5313
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
|
|
5314
5314
|
<circle
|
|
5315
5315
|
cx="8"
|
|
@@ -5601,11 +5601,11 @@ void main() {
|
|
|
5601
5601
|
@decline=${this.handlePrivacyDecline}
|
|
5602
5602
|
></hanc-privacy-modal>
|
|
5603
5603
|
`:""}
|
|
5604
|
-
`}},F.FloatingCall.styles=
|
|
5604
|
+
`}},F.FloatingCall.styles=Ti`
|
|
5605
5605
|
:host {
|
|
5606
5606
|
display: block;
|
|
5607
5607
|
}
|
|
5608
|
-
`,Ae([W({type:String,attribute:"agent-id"})],F.FloatingCall.prototype,"agentId",2),Ae([W({type:String,attribute:"voice-service-url"})],F.FloatingCall.prototype,"voiceServiceUrl",2),Ae([ge()],F.FloatingCall.prototype,"callStatus",2),Ae([ge()],F.FloatingCall.prototype,"microphoneEnabled",2),Ae([ge()],F.FloatingCall.prototype,"microphoneInitialized",2),Ae([ge()],F.FloatingCall.prototype,"showPrivacyModal",2),Ae([ge()],F.FloatingCall.prototype,"widgetConfig",2),Ae([ge()],F.FloatingCall.prototype,"configLoading",2),Ae([ge()],F.FloatingCall.prototype,"domainBlocked",2),Ae([W({type:String,attribute:"privacy-url"})],F.FloatingCall.prototype,"privacyUrl",2),Ae([W({type:String,attribute:"terms-url"})],F.FloatingCall.prototype,"termsUrl",2),Ae([W({type:Boolean,attribute:"terms-enabled"})],F.FloatingCall.prototype,"termsEnabled",2),Ae([W({type:String,attribute:"terms-content"})],F.FloatingCall.prototype,"termsContent",2),Ae([W({type:Boolean,attribute:"skip-fetch"})],F.FloatingCall.prototype,"skipFetch",2),Ae([W({type:String,attribute:"api-base-url"})],F.FloatingCall.prototype,"apiBaseUrl",2),Ae([W({type:String,attribute:"button-start-text"})],F.FloatingCall.prototype,"buttonStartText",2),Ae([W({type:String,attribute:"button-connecting-text"})],F.FloatingCall.prototype,"buttonConnectingText",2),Ae([W({type:String,attribute:"position"})],F.FloatingCall.prototype,"position",2),Ae([W({type:Number,attribute:"size"})],F.FloatingCall.prototype,"size",2),Ae([W({type:String,attribute:"theme"})],F.FloatingCall.prototype,"theme",2),Ae([W({type:Object,attribute:"orb-colors"})],F.FloatingCall.prototype,"orbColors",2),Ae([W({type:Number,attribute:"glow-intensity"})],F.FloatingCall.prototype,"glowIntensity",2),Ae([W({type:Number,attribute:"idle-glow-multiplier"})],F.FloatingCall.prototype,"idleGlowMultiplier",2),Ae([W({type:Number,attribute:"morph-strength"})],F.FloatingCall.prototype,"morphStrength",2),Ae([W({type:Number,attribute:"noise-scale"})],F.FloatingCall.prototype,"noiseScale",2),Ae([W({type:Number,attribute:"noise-speed"})],F.FloatingCall.prototype,"noiseSpeed",2),Ae([W({type:Number,attribute:"fresnel-power"})],F.FloatingCall.prototype,"fresnelPower",2),Ae([W({type:Number,attribute:"rotation-speed"})],F.FloatingCall.prototype,"rotationSpeed",2),Ae([W({type:Number,attribute:"audio-reactivity"})],F.FloatingCall.prototype,"audioReactivity",2),Ae([W({type:Number,attribute:"audio-smoothing"})],F.FloatingCall.prototype,"audioSmoothing",2),Ae([W({type:Number,attribute:"idle-morph-multiplier"})],F.FloatingCall.prototype,"idleMorphMultiplier",2),Ae([W({type:Number,attribute:"color-contrast"})],F.FloatingCall.prototype,"colorContrast",2),Ae([W({type:Boolean,attribute:"sound-enabled"})],F.FloatingCall.prototype,"soundEnabled",2),Ae([W({type:Number,attribute:"sound-volume"})],F.FloatingCall.prototype,"soundVolume",2),Ae([W({type:String,attribute:"sound-preset"})],F.FloatingCall.prototype,"soundPreset",2),F.FloatingCall=Ae([Pi("hanc-ai-floating-call")],F.FloatingCall);var Ap=Object.defineProperty,ep=Object.getOwnPropertyDescriptor,ee=(t,A,e,g)=>{for(var i=g>1?void 0:g?ep(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&Ap(A,e,i),i};F.PillCall=class extends Zg{constructor(){super(...arguments),this.callManager=new CI,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){var A;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){return this.callStatus==="connecting"?zA`
|
|
5608
|
+
`,ee([W({type:String,attribute:"agent-id"})],F.FloatingCall.prototype,"agentId",2),ee([W({type:String,attribute:"voice-service-url"})],F.FloatingCall.prototype,"voiceServiceUrl",2),ee([$A()],F.FloatingCall.prototype,"callStatus",2),ee([$A()],F.FloatingCall.prototype,"microphoneEnabled",2),ee([$A()],F.FloatingCall.prototype,"microphoneInitialized",2),ee([$A()],F.FloatingCall.prototype,"showPrivacyModal",2),ee([$A()],F.FloatingCall.prototype,"widgetConfig",2),ee([$A()],F.FloatingCall.prototype,"configLoading",2),ee([$A()],F.FloatingCall.prototype,"domainBlocked",2),ee([W({type:String,attribute:"privacy-url"})],F.FloatingCall.prototype,"privacyUrl",2),ee([W({type:String,attribute:"terms-url"})],F.FloatingCall.prototype,"termsUrl",2),ee([W({type:Boolean,attribute:"terms-enabled"})],F.FloatingCall.prototype,"termsEnabled",2),ee([W({type:String,attribute:"terms-content"})],F.FloatingCall.prototype,"termsContent",2),ee([W({type:Boolean,attribute:"skip-fetch"})],F.FloatingCall.prototype,"skipFetch",2),ee([W({type:String,attribute:"api-base-url"})],F.FloatingCall.prototype,"apiBaseUrl",2),ee([W({type:String,attribute:"button-start-text"})],F.FloatingCall.prototype,"buttonStartText",2),ee([W({type:String,attribute:"button-connecting-text"})],F.FloatingCall.prototype,"buttonConnectingText",2),ee([W({type:String,attribute:"position"})],F.FloatingCall.prototype,"position",2),ee([W({type:Number,attribute:"size"})],F.FloatingCall.prototype,"size",2),ee([W({type:String,attribute:"theme"})],F.FloatingCall.prototype,"theme",2),ee([W({type:Object,attribute:"orb-colors"})],F.FloatingCall.prototype,"orbColors",2),ee([W({type:Number,attribute:"glow-intensity"})],F.FloatingCall.prototype,"glowIntensity",2),ee([W({type:Number,attribute:"idle-glow-multiplier"})],F.FloatingCall.prototype,"idleGlowMultiplier",2),ee([W({type:Number,attribute:"morph-strength"})],F.FloatingCall.prototype,"morphStrength",2),ee([W({type:Number,attribute:"noise-scale"})],F.FloatingCall.prototype,"noiseScale",2),ee([W({type:Number,attribute:"noise-speed"})],F.FloatingCall.prototype,"noiseSpeed",2),ee([W({type:Number,attribute:"fresnel-power"})],F.FloatingCall.prototype,"fresnelPower",2),ee([W({type:Number,attribute:"rotation-speed"})],F.FloatingCall.prototype,"rotationSpeed",2),ee([W({type:Number,attribute:"audio-reactivity"})],F.FloatingCall.prototype,"audioReactivity",2),ee([W({type:Number,attribute:"audio-smoothing"})],F.FloatingCall.prototype,"audioSmoothing",2),ee([W({type:Number,attribute:"idle-morph-multiplier"})],F.FloatingCall.prototype,"idleMorphMultiplier",2),ee([W({type:Number,attribute:"color-contrast"})],F.FloatingCall.prototype,"colorContrast",2),ee([W({type:Boolean,attribute:"sound-enabled"})],F.FloatingCall.prototype,"soundEnabled",2),ee([W({type:Number,attribute:"sound-volume"})],F.FloatingCall.prototype,"soundVolume",2),ee([W({type:String,attribute:"sound-preset"})],F.FloatingCall.prototype,"soundPreset",2),F.FloatingCall=ee([Oi("hanc-ai-floating-call")],F.FloatingCall);var Ap=Object.defineProperty,ep=Object.getOwnPropertyDescriptor,ge=(t,A,e,g)=>{for(var i=g>1?void 0:g?ep(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&Ap(A,e,i),i};F.PillCall=class extends Zg{constructor(){super(...arguments),this.callManager=new pi,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){var A;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){return this.callStatus==="connecting"?zA`
|
|
5609
5609
|
<svg
|
|
5610
5610
|
width="16"
|
|
5611
5611
|
height="16"
|
|
@@ -5827,12 +5827,12 @@ void main() {
|
|
|
5827
5827
|
@decline=${this.handlePrivacyDecline}
|
|
5828
5828
|
></hanc-privacy-modal>
|
|
5829
5829
|
`:""}
|
|
5830
|
-
`}},F.PillCall.styles=
|
|
5830
|
+
`}},F.PillCall.styles=Ti`
|
|
5831
5831
|
:host {
|
|
5832
5832
|
display: inline-block;
|
|
5833
5833
|
contain: layout style;
|
|
5834
5834
|
}
|
|
5835
|
-
`,ee([W({type:String,attribute:"agent-id"})],F.PillCall.prototype,"agentId",2),ee([W({type:String,attribute:"voice-service-url"})],F.PillCall.prototype,"voiceServiceUrl",2),ee([ge()],F.PillCall.prototype,"callStatus",2),ee([ge()],F.PillCall.prototype,"microphoneEnabled",2),ee([ge()],F.PillCall.prototype,"microphoneInitialized",2),ee([ge()],F.PillCall.prototype,"showPrivacyModal",2),ee([ge()],F.PillCall.prototype,"widgetConfig",2),ee([ge()],F.PillCall.prototype,"configLoading",2),ee([ge()],F.PillCall.prototype,"domainBlocked",2),ee([W({type:String,attribute:"privacy-url"})],F.PillCall.prototype,"privacyUrl",2),ee([W({type:String,attribute:"terms-url"})],F.PillCall.prototype,"termsUrl",2),ee([W({type:Boolean,attribute:"terms-enabled"})],F.PillCall.prototype,"termsEnabled",2),ee([W({type:String,attribute:"terms-content"})],F.PillCall.prototype,"termsContent",2),ee([W({type:Boolean,attribute:"skip-fetch"})],F.PillCall.prototype,"skipFetch",2),ee([W({type:String,attribute:"api-base-url"})],F.PillCall.prototype,"apiBaseUrl",2),ee([W({type:String,attribute:"button-start-text"})],F.PillCall.prototype,"buttonStartText",2),ee([W({type:String,attribute:"button-connecting-text"})],F.PillCall.prototype,"buttonConnectingText",2),ee([W({type:String,attribute:"button-end-text"})],F.PillCall.prototype,"buttonEndText",2),ee([W({type:Number,attribute:"orb-size"})],F.PillCall.prototype,"orbSize",2),ee([W({type:String,attribute:"theme"})],F.PillCall.prototype,"theme",2),ee([W({type:Object,attribute:"orb-colors"})],F.PillCall.prototype,"orbColors",2),ee([W({type:Number,attribute:"glow-intensity"})],F.PillCall.prototype,"glowIntensity",2),ee([W({type:Number,attribute:"idle-glow-multiplier"})],F.PillCall.prototype,"idleGlowMultiplier",2),ee([W({type:Number,attribute:"morph-strength"})],F.PillCall.prototype,"morphStrength",2),ee([W({type:Number,attribute:"noise-scale"})],F.PillCall.prototype,"noiseScale",2),ee([W({type:Number,attribute:"noise-speed"})],F.PillCall.prototype,"noiseSpeed",2),ee([W({type:Number,attribute:"fresnel-power"})],F.PillCall.prototype,"fresnelPower",2),ee([W({type:Number,attribute:"rotation-speed"})],F.PillCall.prototype,"rotationSpeed",2),ee([W({type:Number,attribute:"audio-reactivity"})],F.PillCall.prototype,"audioReactivity",2),ee([W({type:Number,attribute:"audio-smoothing"})],F.PillCall.prototype,"audioSmoothing",2),ee([W({type:Number,attribute:"idle-morph-multiplier"})],F.PillCall.prototype,"idleMorphMultiplier",2),ee([W({type:Number,attribute:"color-contrast"})],F.PillCall.prototype,"colorContrast",2),ee([W({type:Boolean,attribute:"sound-enabled"})],F.PillCall.prototype,"soundEnabled",2),ee([W({type:Number,attribute:"sound-volume"})],F.PillCall.prototype,"soundVolume",2),ee([W({type:String,attribute:"sound-preset"})],F.PillCall.prototype,"soundPreset",2),F.PillCall=ee([Pi("hanc-ai-pill-call")],F.PillCall);var gp=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,ZA=(t,A,e,g)=>{for(var i=g>1?void 0:g?tp(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&gp(A,e,i),i};F.PillFloatingCall=class extends Zg{constructor(){super(...arguments),this.callManager=new CI,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.position="bottom-right",this.orbSize=48,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){var A;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){const A=16*this.scale;return this.callStatus==="connecting"?zA`
|
|
5835
|
+
`,ge([W({type:String,attribute:"agent-id"})],F.PillCall.prototype,"agentId",2),ge([W({type:String,attribute:"voice-service-url"})],F.PillCall.prototype,"voiceServiceUrl",2),ge([$A()],F.PillCall.prototype,"callStatus",2),ge([$A()],F.PillCall.prototype,"microphoneEnabled",2),ge([$A()],F.PillCall.prototype,"microphoneInitialized",2),ge([$A()],F.PillCall.prototype,"showPrivacyModal",2),ge([$A()],F.PillCall.prototype,"widgetConfig",2),ge([$A()],F.PillCall.prototype,"configLoading",2),ge([$A()],F.PillCall.prototype,"domainBlocked",2),ge([W({type:String,attribute:"privacy-url"})],F.PillCall.prototype,"privacyUrl",2),ge([W({type:String,attribute:"terms-url"})],F.PillCall.prototype,"termsUrl",2),ge([W({type:Boolean,attribute:"terms-enabled"})],F.PillCall.prototype,"termsEnabled",2),ge([W({type:String,attribute:"terms-content"})],F.PillCall.prototype,"termsContent",2),ge([W({type:Boolean,attribute:"skip-fetch"})],F.PillCall.prototype,"skipFetch",2),ge([W({type:String,attribute:"api-base-url"})],F.PillCall.prototype,"apiBaseUrl",2),ge([W({type:String,attribute:"button-start-text"})],F.PillCall.prototype,"buttonStartText",2),ge([W({type:String,attribute:"button-connecting-text"})],F.PillCall.prototype,"buttonConnectingText",2),ge([W({type:String,attribute:"button-end-text"})],F.PillCall.prototype,"buttonEndText",2),ge([W({type:Number,attribute:"orb-size"})],F.PillCall.prototype,"orbSize",2),ge([W({type:String,attribute:"theme"})],F.PillCall.prototype,"theme",2),ge([W({type:Object,attribute:"orb-colors"})],F.PillCall.prototype,"orbColors",2),ge([W({type:Number,attribute:"glow-intensity"})],F.PillCall.prototype,"glowIntensity",2),ge([W({type:Number,attribute:"idle-glow-multiplier"})],F.PillCall.prototype,"idleGlowMultiplier",2),ge([W({type:Number,attribute:"morph-strength"})],F.PillCall.prototype,"morphStrength",2),ge([W({type:Number,attribute:"noise-scale"})],F.PillCall.prototype,"noiseScale",2),ge([W({type:Number,attribute:"noise-speed"})],F.PillCall.prototype,"noiseSpeed",2),ge([W({type:Number,attribute:"fresnel-power"})],F.PillCall.prototype,"fresnelPower",2),ge([W({type:Number,attribute:"rotation-speed"})],F.PillCall.prototype,"rotationSpeed",2),ge([W({type:Number,attribute:"audio-reactivity"})],F.PillCall.prototype,"audioReactivity",2),ge([W({type:Number,attribute:"audio-smoothing"})],F.PillCall.prototype,"audioSmoothing",2),ge([W({type:Number,attribute:"idle-morph-multiplier"})],F.PillCall.prototype,"idleMorphMultiplier",2),ge([W({type:Number,attribute:"color-contrast"})],F.PillCall.prototype,"colorContrast",2),ge([W({type:Boolean,attribute:"sound-enabled"})],F.PillCall.prototype,"soundEnabled",2),ge([W({type:Number,attribute:"sound-volume"})],F.PillCall.prototype,"soundVolume",2),ge([W({type:String,attribute:"sound-preset"})],F.PillCall.prototype,"soundPreset",2),F.PillCall=ge([Oi("hanc-ai-pill-call")],F.PillCall);var gp=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,ZA=(t,A,e,g)=>{for(var i=g>1?void 0:g?tp(A,e):A,I=t.length-1,C;I>=0;I--)(C=t[I])&&(i=(g?C(A,e,i):C(i))||i);return g&&i&&gp(A,e,i),i};F.PillFloatingCall=class extends Zg{constructor(){super(...arguments),this.callManager=new pi,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=kC(),this.animationId=null,this.user_identity=$o(),this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.showPrivacyModal=!1,this.widgetConfig=null,this.configLoading=!1,this.domainBlocked=!1,this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsEnabled=!1,this.termsContent="",this.skipFetch=!1,this.apiBaseUrl=DC,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.position="bottom-right",this.orbSize=48,this.theme="default",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectStream(i)}catch(i){console.error("Failed to connect audio stream:",i)}},this.handleLocalAudioTrack=async A=>{const g=A.detail;if(!(!g||!this.audioAnalyzer))try{const i=new MediaStream([g]);await this.audioAnalyzer.connectLocalStream(i)}catch(i){console.error("Failed to connect local audio stream:",i)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleStatusChange=A=>{var g,i,I,C,o;switch(A.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(g=this.orbRenderer)==null||g.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(i=this.orbRenderer)==null||i.setActive(!1),(I=this.audioAnalyzer)==null||I.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var a;(a=this.soundManager)==null||a.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(C=this.orbRenderer)==null||C.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var A,e;if(this.agentId){if(this.domainBlocked){console.warn("[hanc-widget] Call blocked: widget not allowed on this domain");return}if(await((A=this.soundManager)==null?void 0:A.prewarm()),this.callStatus==="idle"){if((((e=this.widgetConfig)==null?void 0:e.terms_enabled)??!1)&&!Zo()){this.showPrivacyModal=!0;return}this.user_identity=Bi(),this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})}else this.callStatus==="connected"&&this.callManager.hangUp()}},this.handlePrivacyAccept=async()=>{zo(),this.user_identity=Bi(),this.showPrivacyModal=!1,this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId,user_identity:this.user_identity})},this.handlePrivacyDecline=()=>{this.showPrivacyModal=!1}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new uC({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.loadWidgetConfig()}async loadWidgetConfig(){if(this.skipFetch){this.widgetConfig={terms_enabled:this.termsEnabled,terms_content:this.termsContent,terms_url:this.termsUrl,privacy_url:this.privacyUrl,theme:this.theme,allow_all_domains:!0,allowed_domains:[]};return}if(!(!this.agentId||this.configLoading)){this.configLoading=!0;try{const A=await _C(this.agentId,this.apiBaseUrl);this.widgetConfig=A,wC(A)||(this.domainBlocked=!0,console.warn("[hanc-widget] Widget is not allowed on this domain")),A.theme&&A.theme!=="default"&&!this.hasAttribute("theme")&&(this.theme=A.theme,this.applyTheme())}catch(A){console.error("[hanc-widget] Failed to load widget config:",A)}finally{this.configLoading=!1}}}disconnectedCallback(){var A;super.disconnectedCallback(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.callManager.hangUp(),this.cleanupOrb(),(A=this.soundManager)==null||A.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(A){var e,g,i;super.updated(A),A.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle",this.widgetConfig=null,this.domainBlocked=!1,this.loadWidgetConfig()),A.has("apiBaseUrl")&&this.agentId&&this.loadWidgetConfig(),this.skipFetch&&(A.has("termsEnabled")||A.has("termsContent")||A.has("termsUrl")||A.has("privacyUrl")||A.has("theme"))&&this.loadWidgetConfig(),A.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),A.has("theme")&&this.applyTheme(),A.has("soundEnabled")&&((e=this.soundManager)==null||e.setEnabled(this.soundEnabled)),A.has("soundVolume")&&((g=this.soundManager)==null||g.setVolume(this.soundVolume)),A.has("soundPreset")&&((i=this.soundManager)==null||i.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const A=kI(this.theme);this.orbColors=A.colors,this.glowIntensity=A.glowIntensity,this.idleGlowMultiplier=A.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const A=this.orbContainerRef.value;A&&(this.orbRenderer=new jo(A,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Wo,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var A,e;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(A=this.audioAnalyzer)==null||A.disconnect(),(e=this.orbRenderer)==null||e.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const e=performance.now()/1e3,g=Math.sin(e*.5)*.15+.15,i=Math.sin(e*.7+1)*.12+.12,I=Math.sin(e*.9+2)*.08+.08,C=(g+i+I)/3;this.orbRenderer.setSimulatedAudio(g,i,I,C),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const A=()=>{var g;if(this.callStatus!=="connected"||!this.orbRenderer)return;const e=(g=this.audioAnalyzer)==null?void 0:g.getAudioData();e&&this.orbRenderer.updateAudio(e),this.animationId=requestAnimationFrame(A)};this.animationId=requestAnimationFrame(A)}getButtonIcon(){const A=16*this.scale;return this.callStatus==="connecting"?zA`
|
|
5836
5836
|
<svg width="${A}" height="${A}" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
|
|
5837
5837
|
<circle
|
|
5838
5838
|
cx="8"
|
|
@@ -6056,8 +6056,8 @@ void main() {
|
|
|
6056
6056
|
@decline=${this.handlePrivacyDecline}
|
|
6057
6057
|
></hanc-privacy-modal>
|
|
6058
6058
|
`:""}
|
|
6059
|
-
`}},F.PillFloatingCall.styles=
|
|
6059
|
+
`}},F.PillFloatingCall.styles=Ti`
|
|
6060
6060
|
:host {
|
|
6061
6061
|
display: block;
|
|
6062
6062
|
}
|
|
6063
|
-
`,ZA([W({type:String,attribute:"agent-id"})],F.PillFloatingCall.prototype,"agentId",2),ZA([W({type:String,attribute:"voice-service-url"})],F.PillFloatingCall.prototype,"voiceServiceUrl",2),ZA([
|
|
6063
|
+
`,ZA([W({type:String,attribute:"agent-id"})],F.PillFloatingCall.prototype,"agentId",2),ZA([W({type:String,attribute:"voice-service-url"})],F.PillFloatingCall.prototype,"voiceServiceUrl",2),ZA([$A()],F.PillFloatingCall.prototype,"callStatus",2),ZA([$A()],F.PillFloatingCall.prototype,"microphoneEnabled",2),ZA([$A()],F.PillFloatingCall.prototype,"microphoneInitialized",2),ZA([$A()],F.PillFloatingCall.prototype,"showPrivacyModal",2),ZA([$A()],F.PillFloatingCall.prototype,"widgetConfig",2),ZA([$A()],F.PillFloatingCall.prototype,"configLoading",2),ZA([$A()],F.PillFloatingCall.prototype,"domainBlocked",2),ZA([W({type:String,attribute:"privacy-url"})],F.PillFloatingCall.prototype,"privacyUrl",2),ZA([W({type:String,attribute:"terms-url"})],F.PillFloatingCall.prototype,"termsUrl",2),ZA([W({type:Boolean,attribute:"terms-enabled"})],F.PillFloatingCall.prototype,"termsEnabled",2),ZA([W({type:String,attribute:"terms-content"})],F.PillFloatingCall.prototype,"termsContent",2),ZA([W({type:Boolean,attribute:"skip-fetch"})],F.PillFloatingCall.prototype,"skipFetch",2),ZA([W({type:String,attribute:"api-base-url"})],F.PillFloatingCall.prototype,"apiBaseUrl",2),ZA([W({type:String,attribute:"button-start-text"})],F.PillFloatingCall.prototype,"buttonStartText",2),ZA([W({type:String,attribute:"button-connecting-text"})],F.PillFloatingCall.prototype,"buttonConnectingText",2),ZA([W({type:String,attribute:"button-end-text"})],F.PillFloatingCall.prototype,"buttonEndText",2),ZA([W({type:String,attribute:"position"})],F.PillFloatingCall.prototype,"position",2),ZA([W({type:Number,attribute:"orb-size"})],F.PillFloatingCall.prototype,"orbSize",2),ZA([W({type:String,attribute:"theme"})],F.PillFloatingCall.prototype,"theme",2),ZA([W({type:Object,attribute:"orb-colors"})],F.PillFloatingCall.prototype,"orbColors",2),ZA([W({type:Number,attribute:"glow-intensity"})],F.PillFloatingCall.prototype,"glowIntensity",2),ZA([W({type:Number,attribute:"idle-glow-multiplier"})],F.PillFloatingCall.prototype,"idleGlowMultiplier",2),ZA([W({type:Number,attribute:"morph-strength"})],F.PillFloatingCall.prototype,"morphStrength",2),ZA([W({type:Number,attribute:"noise-scale"})],F.PillFloatingCall.prototype,"noiseScale",2),ZA([W({type:Number,attribute:"noise-speed"})],F.PillFloatingCall.prototype,"noiseSpeed",2),ZA([W({type:Number,attribute:"fresnel-power"})],F.PillFloatingCall.prototype,"fresnelPower",2),ZA([W({type:Number,attribute:"rotation-speed"})],F.PillFloatingCall.prototype,"rotationSpeed",2),ZA([W({type:Number,attribute:"audio-reactivity"})],F.PillFloatingCall.prototype,"audioReactivity",2),ZA([W({type:Number,attribute:"audio-smoothing"})],F.PillFloatingCall.prototype,"audioSmoothing",2),ZA([W({type:Number,attribute:"idle-morph-multiplier"})],F.PillFloatingCall.prototype,"idleMorphMultiplier",2),ZA([W({type:Number,attribute:"color-contrast"})],F.PillFloatingCall.prototype,"colorContrast",2),ZA([W({type:Boolean,attribute:"sound-enabled"})],F.PillFloatingCall.prototype,"soundEnabled",2),ZA([W({type:Number,attribute:"sound-volume"})],F.PillFloatingCall.prototype,"soundVolume",2),ZA([W({type:String,attribute:"sound-preset"})],F.PillFloatingCall.prototype,"soundPreset",2),F.PillFloatingCall=ZA([Oi("hanc-ai-pill-floating-call")],F.PillFloatingCall),F.SoundManager=uC,F.applyTheme=Jw,F.clearConfigCache=Hw,F.darkPresets=og,F.darkThemes=Lw,F.fetchWidgetConfig=_C,F.getColorPreset=Fw,F.getPresetNames=Uw,F.getTheme=kI,F.getThemeNames=vw,F.isDomainAllowed=wC,F.lightPresets=ag,F.lightThemes=Kw,F.themes=SI,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})});
|